import os import pandas as pd import gzip from datasets import GeneratorBasedBuilder, DatasetInfo, SplitGenerator, Split, BuilderConfig, Features, Value from Bio import SeqIO from typing import Dict, Any class VepOmimConfig(BuilderConfig): def __init__(self, sequence_length=2048, fasta_path=None, **kwargs): super().__init__(**kwargs) self.sequence_length = sequence_length self.fasta_path = fasta_path @property def sequence_length(self): return self._sequence_length @sequence_length.setter def sequence_length(self, value): self._sequence_length = value @property def fasta_path(self): return self._fasta_path @fasta_path.setter def fasta_path(self, value): self._fasta_path = value class VepOmimSplit(GeneratorBasedBuilder): BUILDER_CONFIG_CLASS = VepOmimConfig BUILDER_CONFIGS = [ VepOmimConfig(name="default", sequence_length=2048, fasta_path=None) ] DEFAULT_CONFIG_NAME = "default" def _info(self): return DatasetInfo( features=Features({ "ref_forward_sequence": Value("string"), "alt_forward_sequence": Value("string"), "label": Value("int32"), "chromosome": Value("string"), "position": Value("int32"), "ref": Value("string"), "alt": Value("string"), "consequence": Value("string"), }) ) def _split_generators(self, dl_manager): data_files = { "omim": "omim.csv", } downloaded_files = dl_manager.download(data_files) return [ SplitGenerator(name="omim", gen_kwargs={"filepath": downloaded_files["omim"]}), # type: ignore ] def _load_fasta_sequences(self, fasta_path: str) -> Dict[str, str]: """加载 fasta 序列到内存字典,支持 gzip 压缩""" sequences = {} if fasta_path.endswith('.gz'): with gzip.open(fasta_path, 'rt') as f: for record in SeqIO.parse(f, 'fasta'): sequences[record.id] = str(record.seq) else: with open(fasta_path, 'r') as f: for record in SeqIO.parse(f, 'fasta'): sequences[record.id] = str(record.seq) return sequences def _generate_examples(self, filepath: str): df = pd.read_csv(filepath) config: VepOmimConfig = self.config # type: ignore seq_len = config.sequence_length fasta_path = config.fasta_path if fasta_path is None: raise ValueError("You must provide fasta_path when loading the dataset!") # 加载所有序列到内存 sequences = self._load_fasta_sequences(fasta_path) for idx, row in df.iterrows(): chrom = str(row['chromosome']) if not chrom.startswith('chr'): chrom = 'chr' + chrom if chrom not in sequences: raise ValueError(f"Chromosome {chrom} not found in fasta. Available: {list(sequences.keys())[:5]}...") pos = int(row['position']) ref = str(row['ref']) alt = str(row['alt']) half = seq_len // 2 start = max(0, pos - half - 1) # 0-based indexing end = pos + half - 1 seq = sequences[chrom][start:end] seq_list = list(seq) center_idx = half ref_seq = seq_list.copy() ref_seq[center_idx] = ref ref_seq = ''.join(ref_seq) alt_seq = seq_list.copy() alt_seq[center_idx] = alt alt_seq = ''.join(alt_seq) yield idx, { "ref_forward_sequence": ref_seq, "alt_forward_sequence": alt_seq, "label": int(row["label"]), "chromosome": str(row["chromosome"]), "position": int(row["position"]), "consequence": row["consequence"], "ref": row["ref"], "alt": row["alt"] }