| import json |
| import re |
| from pathlib import Path |
| import pandas as pd |
| import pyarrow as pa |
| import pyarrow.parquet as pq |
| from tqdm import tqdm |
| import concurrent.futures |
| from typing import List, Dict |
| import argparse |
|
|
| class SelfiesTokenizer: |
| def __init__(self, tokenizer_path: str): |
| with open(tokenizer_path, 'r') as f: |
| config = json.load(f) |
| self.vocab = config['vocab'] |
| self.special_tokens = config['special_tokens'] |
| self.max_length = config['model_max_length'] |
| self.id2token = {v: k for k, v in self.vocab.items()} |
| |
| def tokenize(self, selfies_string: str) -> List[str]: |
| """Split SELFIES string into tokens""" |
| return re.findall(r'\[.*?\]', selfies_string) |
| |
| def convert_tokens_to_ids(self, tokens: List[str]) -> List[int]: |
| """Convert tokens to their IDs""" |
| return [self.vocab.get(token, self.vocab['[UNK]']) for token in tokens] |
| |
| def encode(self, selfies_string: str, add_special_tokens: bool = True) -> List[int]: |
| """Full encoding process""" |
| tokens = self.tokenize(selfies_string) |
| ids = self.convert_tokens_to_ids(tokens) |
| |
| if add_special_tokens: |
| ids = [self.vocab['[CLS]']] + ids + [self.vocab['[SEP]']] |
| |
| if len(ids) > self.max_length: |
| ids = ids[:self.max_length] |
| else: |
| ids.extend([self.vocab['[PAD]']] * (self.max_length - len(ids))) |
| |
| return ids |
|
|
| def process_chunk(chunk: List[str], tokenizer: SelfiesTokenizer) -> Dict[str, List]: |
| """Process a chunk of SELFIES strings""" |
| sequences = [seq.strip() for seq in chunk] |
| tokenized = [tokenizer.encode(seq) for seq in sequences] |
| return { |
| 'sequence': sequences, |
| 'tokenized_sequence': tokenized |
| } |
|
|
| def convert_to_parquet(input_files: List[str], output_file: str, tokenizer_path: str, |
| chunk_size: int = 10000, num_workers: int = 4): |
| """Convert SELFIES files to parquet with optimized settings""" |
| |
| tokenizer = SelfiesTokenizer(tokenizer_path) |
| |
| |
| schema = pa.schema([ |
| ('sequence', pa.string()), |
| ('tokenized_sequence', pa.list_(pa.int16())) |
| ]) |
| |
| |
| writer = pq.ParquetWriter( |
| output_file, |
| schema, |
| compression='zstd', |
| compression_level=9, |
| use_dictionary=True, |
| write_statistics=True |
| ) |
| |
| |
| for input_file in input_files: |
| print(f"Processing {input_file}...") |
| |
| |
| total_lines = sum(1 for _ in open(input_file, 'r')) |
| |
| with open(input_file, 'r') as f: |
| |
| for chunk_start in tqdm(range(0, total_lines, chunk_size)): |
| chunk = [] |
| for _ in range(chunk_size): |
| line = f.readline() |
| if not line: |
| break |
| chunk.append(line) |
| |
| if not chunk: |
| break |
| |
| |
| with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor: |
| chunk_size_per_worker = len(chunk) // num_workers |
| futures = [] |
| |
| for i in range(0, len(chunk), chunk_size_per_worker): |
| chunk_part = chunk[i:i + chunk_size_per_worker] |
| futures.append( |
| executor.submit(process_chunk, chunk_part, tokenizer) |
| ) |
| |
| |
| results = { |
| 'sequence': [], |
| 'tokenized_sequence': [] |
| } |
| |
| for future in concurrent.futures.as_completed(futures): |
| chunk_results = future.result() |
| results['sequence'].extend(chunk_results['sequence']) |
| results['tokenized_sequence'].extend(chunk_results['tokenized_sequence']) |
| |
| |
| table = pa.Table.from_pydict(results, schema=schema) |
| writer.write_table(table) |
| |
| writer.close() |
| |
| |
| parquet_file = pq.ParquetFile(output_file) |
| print(f"\nParquet file statistics:") |
| print(f"Number of row groups: {parquet_file.num_row_groups}") |
| print(f"Number of rows: {parquet_file.metadata.num_rows}") |
| print(f"File size: {Path(output_file).stat().st_size / (1024*1024):.2f} MB") |
|
|
| if __name__ == "__main__": |
| parser = argparse.ArgumentParser(description='Convert SELFIES files to parquet dataset') |
| parser.add_argument('input_files', nargs='+', help='Input SELFIES files') |
| parser.add_argument('output_file', help='Output parquet file') |
| parser.add_argument('tokenizer_path', help='Path to tokenizer config JSON') |
| parser.add_argument('--chunk-size', type=int, default=10000, help='Chunk size for processing') |
| parser.add_argument('--num-workers', type=int, default=4, help='Number of worker threads') |
| |
| args = parser.parse_args() |
| |
| convert_to_parquet( |
| args.input_files, |
| args.output_file, |
| args.tokenizer_path, |
| args.chunk_size, |
| args.num_workers |
| ) |
|
|