| import argparse |
| import os |
| import selfies as sf |
| from tqdm import tqdm |
|
|
| def convert_file(input_file, verbose=False, batch_size=10000): |
| base_name = os.path.splitext(input_file)[0] |
| selfies_file = f"{base_name}.selfies" |
| alphabet_file = f"{base_name}.alph" |
| |
| alphabet = set() |
| total_lines = 0 |
| processed_lines = 0 |
| error_count = 0 |
|
|
| |
| if verbose: |
| with open(input_file, 'r') as fin: |
| total_lines = sum(1 for _ in fin) |
|
|
| with open(input_file, 'r') as fin, open(selfies_file, 'w') as fout: |
| if verbose: |
| pbar = tqdm(total=total_lines, desc=f"Converting {input_file}") |
|
|
| batch = [] |
| for line in fin: |
| |
| smiles = line.split()[0] |
| batch.append(smiles) |
| if len(batch) == batch_size: |
| error_count += process_batch(batch, fout, alphabet) |
| processed_lines += len(batch) |
| if verbose: |
| pbar.update(len(batch)) |
| batch = [] |
|
|
| |
| if batch: |
| error_count += process_batch(batch, fout, alphabet) |
| processed_lines += len(batch) |
| if verbose: |
| pbar.update(len(batch)) |
|
|
| if verbose: |
| pbar.close() |
|
|
| with open(alphabet_file, 'w') as f: |
| for symbol in sorted(alphabet): |
| f.write(f"{symbol}\n") |
| |
| if verbose: |
| print(f"Conversion complete. Processed {processed_lines} lines.") |
| print(f"Encountered {error_count} errors during conversion.") |
| print(f"SELFIES saved to {selfies_file}") |
| print(f"Alphabet saved to {alphabet_file}") |
|
|
| def process_batch(batch, fout, alphabet): |
| error_count = 0 |
| for smiles in batch: |
| try: |
| selfies = sf.encoder(smiles, strict=False) |
| if selfies: |
| fout.write(f"{selfies}\n") |
| alphabet.update(sf.split_selfies(selfies)) |
| else: |
| error_count += 1 |
| except sf.EncoderError: |
| error_count += 1 |
| return error_count |
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="SELFIES Converter") |
| parser.add_argument("input_file", help="Input SMILES file (.smi)") |
| parser.add_argument("-v", "--verbose", action="store_true", help="Increase output verbosity") |
| parser.add_argument("-b", "--batch-size", type=int, default=10000, help="Batch size for processing") |
| args = parser.parse_args() |
|
|
| convert_file(args.input_file, args.verbose, args.batch_size) |
|
|
| if __name__ == "__main__": |
| main() |