rnacentral-non-coding-rna / rnacentral-non-coding-rna.py
suzuki-2001's picture
Update rnacentral-non-coding-rna.py
d739c9a verified
raw
history blame
6.41 kB
from typing import Dict, Optional
import datasets
from Bio import SeqIO
import os
import gzip
import wget
import logging
import tqdm
from collections import defaultdict
import tempfile
class RNACentralDownloader:
"""Helper class to manage RNAcentral downloads"""
BASE_URL = "https://ftp.ebi.ac.uk/pub/databases/RNAcentral/current_release"
@staticmethod
def download_file(url: str, output_dir: str) -> str:
"""Download a file with progress bar and return local path"""
os.makedirs(output_dir, exist_ok=True)
output_path = os.path.join(output_dir, os.path.basename(url))
if os.path.exists(output_path):
logging.info(f"File already exists: {output_path}")
return output_path
logging.info(f"Downloading {url} to {output_path}")
wget.download(url, output_path)
print() # New line after wget progress bar
return output_path
class RNACentralMinimalConfig(datasets.BuilderConfig):
"""BuilderConfig for RNAcentral minimal corpus."""
def __init__(
self,
*args,
min_length: int = 10,
max_length: int = 10000,
max_sequences: Optional[int] = None,
include_metadata: bool = True,
cache_dir: Optional[str] = None,
**kwargs,
):
super().__init__(*args, **kwargs)
self.min_length = min_length
self.max_length = max_length
self.max_sequences = max_sequences
self.include_metadata = include_metadata
self.cache_dir = cache_dir or tempfile.gettempdir()
class RNACentralMinimalCorpus(datasets.GeneratorBasedBuilder):
"""Minimal RNAcentral corpus for pre-training."""
VERSION = datasets.Version("1.0.0")
BUILDER_CONFIG_CLASS = RNACentralMinimalConfig
DEFAULT_CONFIG_NAME = "default"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.config = self.config or self.BUILDER_CONFIG_CLASS(
name=self.DEFAULT_CONFIG_NAME,
min_length=10,
max_length=1000,
max_sequences=1000000,
include_metadata=True
)
self.downloader = RNACentralDownloader()
def _info(self):
features = {
"id": datasets.Value("string"),
"sequence": datasets.Value("string"),
"length": datasets.Value("int32"),
}
if self.config.include_metadata:
features.update({
"rna_type": datasets.Value("string"),
"rfam_family": datasets.Value("string"),
})
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(features),
homepage="https://rnacentral.org/",
license="CC0",
citation=_CITATION,
)
def _load_minimal_rfam(self, filepath: str) -> Dict[str, str]:
"""Load minimal Rfam annotations (family only)."""
rfam_families = {}
with gzip.open(filepath, 'rt') as f:
next(f)
for line in f:
fields = line.strip().split('\t')
if len(fields) >= 3:
rna_id = fields[0]
family = fields[2]
rfam_families[rna_id] = family
return rfam_families
def _split_generators(self, dl_manager: datasets.DownloadManager):
# Direct download using wget instead of datasets downloader
sequences_url = f"{self.downloader.BASE_URL}/sequences/rnacentral_active.fasta.gz"
sequences_path = self.downloader.download_file(sequences_url, self.config.cache_dir)
rfam_families = {}
if self.config.include_metadata:
rfam_url = f"{self.downloader.BASE_URL}/rfam/rfam_annotations.tsv.gz"
rfam_path = self.downloader.download_file(rfam_url, self.config.cache_dir)
rfam_families = self._load_minimal_rfam(rfam_path)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"filepath": sequences_path,
"rfam_families": rfam_families,
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"filepath": sequences_path,
"rfam_families": rfam_families,
"split": "validation",
},
),
]
def _generate_examples(self, filepath: str, rfam_families: Dict[str, str], split: str):
"""Generate examples with size and content restrictions."""
processed_count = 0
split_start = 0.0 if split == "train" else 0.9
split_end = 0.9 if split == "train" else 1.0
with gzip.open(filepath, 'rt') as handle:
for idx, record in enumerate(SeqIO.parse(handle, 'fasta')):
if self.config.max_sequences and processed_count >= self.config.max_sequences:
break
if not (split_start <= (idx % 10) / 10 < split_end):
continue
sequence = str(record.seq)
length = len(sequence)
if length < self.config.min_length or length > self.config.max_length:
continue
rna_id = record.id.split('|')[0]
example = {
"id": rna_id,
"sequence": sequence,
"length": length,
}
if self.config.include_metadata:
description_parts = record.description.split('|')
rna_type = "unknown"
for part in description_parts:
if "RNA_type:" in part:
rna_type = part.split(':')[1].strip()
break
example.update({
"rna_type": rna_type,
"rfam_family": rfam_families.get(rna_id, "unknown"),
})
yield processed_count, example
processed_count += 1