|
|
|
import gradio as gr |
|
import torch |
|
import torch.nn.functional as F |
|
import pytorch_lightning as pl |
|
import os |
|
import json |
|
import logging |
|
from tokenizers import Tokenizer |
|
from huggingface_hub import hf_hub_download |
|
import gc |
|
import math |
|
|
|
|
|
|
|
MODEL_REPO_ID = ( |
|
"AdrianM0/smiles-to-iupac-translator" |
|
) |
|
CHECKPOINT_FILENAME = "last.ckpt" |
|
SMILES_TOKENIZER_FILENAME = "smiles_bytelevel_bpe_tokenizer_scaled.json" |
|
IUPAC_TOKENIZER_FILENAME = "iupac_unigram_tokenizer_scaled.json" |
|
CONFIG_FILENAME = ( |
|
"config.json" |
|
) |
|
|
|
|
|
|
|
logging.basicConfig( |
|
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" |
|
) |
|
|
|
|
|
try: |
|
|
|
|
|
from enhanced_trainer import SmilesIupacLitModule, generate_square_subsequent_mask |
|
|
|
logging.info("Successfully imported from enhanced_trainer.py.") |
|
|
|
|
|
|
|
|
|
except ImportError as e: |
|
logging.error( |
|
f"Failed to import helper code from enhanced_trainer.py: {e}. " |
|
f"Make sure enhanced_trainer.py is in the root of the Hugging Face repo '{MODEL_REPO_ID}'." |
|
) |
|
|
|
raise gr.Error( |
|
f"Initialization Error: Could not load necessary Python modules (enhanced_trainer.py). Check Space logs. Error: {e}" |
|
) |
|
except Exception as e: |
|
logging.error( |
|
f"An unexpected error occurred during helper code import: {e}", exc_info=True |
|
) |
|
raise gr.Error( |
|
f"Initialization Error: An unexpected error occurred loading helper modules. Check Space logs. Error: {e}" |
|
) |
|
|
|
|
|
model: pl.LightningModule | None = None |
|
smiles_tokenizer: Tokenizer | None = None |
|
iupac_tokenizer: Tokenizer | None = None |
|
device: torch.device | None = None |
|
config: dict | None = None |
|
|
|
|
|
|
|
def beam_search_decode( |
|
model: pl.LightningModule, |
|
src: torch.Tensor, |
|
src_padding_mask: torch.Tensor, |
|
max_len: int, |
|
sos_idx: int, |
|
eos_idx: int, |
|
pad_idx: int, |
|
device: torch.device, |
|
beam_width: int = 5, |
|
n_best: int = 5, |
|
length_penalty: float = 0.6, |
|
) -> list[torch.Tensor]: |
|
""" |
|
Performs beam search decoding using the LightningModule's model. |
|
(Ensures this code is self-contained within app.py or correctly imported) |
|
""" |
|
model.eval() |
|
transformer_model = model.model |
|
n_best = min(n_best, beam_width) |
|
|
|
try: |
|
with torch.no_grad(): |
|
|
|
memory = transformer_model.encode( |
|
src, src_padding_mask |
|
) |
|
memory = memory.to(device) |
|
memory_key_padding_mask = src_padding_mask.to(memory.device) |
|
|
|
|
|
initial_beam_seq = torch.ones(1, 1, dtype=torch.long, device=device).fill_( |
|
sos_idx |
|
) |
|
initial_beam_score = torch.zeros(1, dtype=torch.float, device=device) |
|
active_beams = [(initial_beam_seq, initial_beam_score)] |
|
finished_beams = [] |
|
|
|
|
|
for step in range(max_len - 1): |
|
if not active_beams: |
|
break |
|
|
|
potential_next_beams = [] |
|
for current_seq, current_score in active_beams: |
|
|
|
if current_seq[0, -1].item() == eos_idx: |
|
|
|
finished_beams.append((current_seq, current_score)) |
|
continue |
|
|
|
|
|
tgt_input = current_seq |
|
tgt_seq_len = tgt_input.shape[1] |
|
tgt_mask = generate_square_subsequent_mask(tgt_seq_len, device).to( |
|
device |
|
) |
|
|
|
tgt_padding_mask = torch.zeros( |
|
tgt_input.shape, dtype=torch.bool, device=device |
|
) |
|
|
|
|
|
decoder_output = transformer_model.decode( |
|
tgt=tgt_input, |
|
memory=memory, |
|
tgt_mask=tgt_mask, |
|
tgt_padding_mask=tgt_padding_mask, |
|
memory_key_padding_mask=memory_key_padding_mask, |
|
) |
|
|
|
|
|
next_token_logits = transformer_model.generator( |
|
decoder_output[ |
|
:, -1, : |
|
] |
|
) |
|
|
|
|
|
log_probs = F.log_softmax( |
|
next_token_logits, dim=-1 |
|
) |
|
combined_scores = ( |
|
log_probs + current_score |
|
) |
|
|
|
|
|
topk_log_probs, topk_indices = torch.topk( |
|
combined_scores, beam_width, dim=-1 |
|
) |
|
|
|
|
|
for i in range(beam_width): |
|
next_token_id = topk_indices[0, i].item() |
|
|
|
next_score = topk_log_probs[0, i].reshape( |
|
1 |
|
) |
|
next_token_tensor = torch.tensor( |
|
[[next_token_id]], dtype=torch.long, device=device |
|
) |
|
new_seq = torch.cat( |
|
[current_seq, next_token_tensor], dim=1 |
|
) |
|
potential_next_beams.append((new_seq, next_score)) |
|
|
|
|
|
|
|
potential_next_beams.sort(key=lambda x: x[1].item(), reverse=True) |
|
|
|
|
|
active_beams = [] |
|
temp_finished_beams = [] |
|
for seq, score in potential_next_beams: |
|
if ( |
|
len(active_beams) >= beam_width |
|
and len(temp_finished_beams) >= beam_width |
|
): |
|
break |
|
|
|
is_finished = seq[0, -1].item() == eos_idx |
|
if is_finished: |
|
|
|
if len(temp_finished_beams) < beam_width: |
|
temp_finished_beams.append((seq, score)) |
|
elif len(active_beams) < beam_width: |
|
|
|
active_beams.append((seq, score)) |
|
|
|
|
|
finished_beams.extend(temp_finished_beams) |
|
|
|
finished_beams.sort(key=lambda x: x[1].item(), reverse=True) |
|
finished_beams = finished_beams[ |
|
: beam_width * 2 |
|
] |
|
|
|
|
|
|
|
finished_beams.extend(active_beams) |
|
|
|
|
|
def get_score_with_penalty(beam_tuple): |
|
seq, score = beam_tuple |
|
seq_len = seq.shape[1] |
|
|
|
if length_penalty <= 0.0 or seq_len <= 1: |
|
return score.item() |
|
else: |
|
|
|
penalty = ( |
|
(5.0 + float(seq_len)) / 6.0 |
|
) ** length_penalty |
|
return score.item() / penalty |
|
|
|
|
|
|
|
finished_beams.sort( |
|
key=get_score_with_penalty, reverse=True |
|
) |
|
|
|
|
|
top_sequences = [ |
|
seq[:, 1:] |
|
for seq, score in finished_beams[:n_best] |
|
if seq.shape[1] > 1 |
|
] |
|
return top_sequences |
|
|
|
except RuntimeError as e: |
|
logging.error(f"Runtime error during beam search decode: {e}", exc_info=True) |
|
if "CUDA out of memory" in str(e) and device.type == "cuda": |
|
gc.collect() |
|
torch.cuda.empty_cache() |
|
return [] |
|
except Exception as e: |
|
logging.error(f"Unexpected error during beam search decode: {e}", exc_info=True) |
|
return [] |
|
|
|
|
|
|
|
def translate( |
|
model: pl.LightningModule, |
|
src_sentence: str, |
|
smiles_tokenizer: Tokenizer, |
|
iupac_tokenizer: Tokenizer, |
|
device: torch.device, |
|
max_len: int, |
|
sos_idx: int, |
|
eos_idx: int, |
|
pad_idx: int, |
|
beam_width: int = 5, |
|
n_best: int = 5, |
|
length_penalty: float = 0.6, |
|
) -> list[str]: |
|
""" |
|
Translates a single SMILES string using beam search. |
|
(Ensures this code is self-contained within app.py or correctly imported) |
|
""" |
|
model.eval() |
|
translations = [] |
|
n_best = min(n_best, beam_width) |
|
|
|
|
|
try: |
|
|
|
smiles_tokenizer.enable_truncation(max_length=max_len) |
|
src_encoded = smiles_tokenizer.encode(src_sentence) |
|
if not src_encoded or not src_encoded.ids: |
|
logging.warning(f"Encoding failed or empty for SMILES: {src_sentence}") |
|
return ["[Encoding Error]"] * n_best |
|
|
|
src_ids = src_encoded.ids |
|
|
|
except Exception as e: |
|
logging.error(f"Error tokenizing SMILES '{src_sentence}': {e}", exc_info=True) |
|
return ["[Encoding Error]"] * n_best |
|
|
|
|
|
src = ( |
|
torch.tensor(src_ids, dtype=torch.long).unsqueeze(0).to(device) |
|
) |
|
|
|
src_padding_mask = (src == pad_idx).to(device) |
|
|
|
|
|
|
|
|
|
generation_max_len = config.get( |
|
"max_len", 256 |
|
) |
|
tgt_tokens_list = beam_search_decode( |
|
model=model, |
|
src=src, |
|
src_padding_mask=src_padding_mask, |
|
max_len=generation_max_len, |
|
sos_idx=sos_idx, |
|
eos_idx=eos_idx, |
|
pad_idx=pad_idx, |
|
device=device, |
|
beam_width=beam_width, |
|
n_best=n_best, |
|
length_penalty=length_penalty, |
|
) |
|
|
|
|
|
if not tgt_tokens_list: |
|
logging.warning(f"Beam search returned empty list for SMILES: {src_sentence}") |
|
|
|
return ["[Decoding Error - Empty Output]"] * n_best |
|
|
|
for i, tgt_tokens_tensor in enumerate(tgt_tokens_list): |
|
if tgt_tokens_tensor is not None and tgt_tokens_tensor.numel() > 0: |
|
tgt_tokens = tgt_tokens_tensor.flatten().cpu().numpy().tolist() |
|
try: |
|
|
|
translation = iupac_tokenizer.decode( |
|
tgt_tokens, skip_special_tokens=True |
|
) |
|
translations.append(translation) |
|
except Exception as e: |
|
logging.error( |
|
f"Error decoding target tokens {tgt_tokens} for beam {i}: {e}", |
|
exc_info=True, |
|
) |
|
translations.append("[Decoding Error]") |
|
else: |
|
logging.warning( |
|
f"Beam {i} result was empty or None for SMILES: {src_sentence}" |
|
) |
|
translations.append("[Decoding Error - Empty Tensor]") |
|
|
|
|
|
while len(translations) < n_best: |
|
translations.append("[Decoding Error - Fewer Results]") |
|
|
|
return translations |
|
|
|
|
|
|
|
def load_model_and_tokenizers(): |
|
"""Loads tokenizers, config, and model from Hugging Face Hub.""" |
|
global model, smiles_tokenizer, iupac_tokenizer, device, config |
|
if model is not None: |
|
logging.info("Model and tokenizers already loaded.") |
|
return |
|
|
|
logging.info(f"Starting model and tokenizer loading from {MODEL_REPO_ID}...") |
|
try: |
|
|
|
|
|
if torch.cuda.is_available(): |
|
logging.warning( |
|
"CUDA is available, but forcing CPU for Gradio app simplicity. Modify if GPU is intended." |
|
) |
|
device = torch.device("cpu") |
|
|
|
|
|
|
|
else: |
|
device = torch.device("cpu") |
|
logging.info("CUDA not available, using CPU.") |
|
|
|
|
|
logging.info("Downloading files from Hugging Face Hub...") |
|
try: |
|
|
|
cache_dir = os.environ.get( |
|
"GRADIO_CACHE", "./hf_cache" |
|
) |
|
os.makedirs(cache_dir, exist_ok=True) |
|
logging.info(f"Using cache directory: {cache_dir}") |
|
|
|
checkpoint_path = hf_hub_download( |
|
repo_id=MODEL_REPO_ID, filename=CHECKPOINT_FILENAME, cache_dir=cache_dir |
|
) |
|
smiles_tokenizer_path = hf_hub_download( |
|
repo_id=MODEL_REPO_ID, |
|
filename=SMILES_TOKENIZER_FILENAME, |
|
cache_dir=cache_dir, |
|
) |
|
iupac_tokenizer_path = hf_hub_download( |
|
repo_id=MODEL_REPO_ID, |
|
filename=IUPAC_TOKENIZER_FILENAME, |
|
cache_dir=cache_dir, |
|
) |
|
config_path = hf_hub_download( |
|
repo_id=MODEL_REPO_ID, filename=CONFIG_FILENAME, cache_dir=cache_dir |
|
) |
|
logging.info("Files downloaded successfully.") |
|
except Exception as e: |
|
logging.error( |
|
f"Failed to download files from {MODEL_REPO_ID}. Check filenames ({CHECKPOINT_FILENAME}, {SMILES_TOKENIZER_FILENAME}, etc.) and repo status. Error: {e}", |
|
exc_info=True, |
|
) |
|
raise gr.Error( |
|
f"Download Error: Could not download required files from {MODEL_REPO_ID}. Check Space logs. Error: {e}" |
|
) |
|
|
|
|
|
logging.info("Loading configuration...") |
|
try: |
|
with open(config_path, "r") as f: |
|
config = json.load(f) |
|
logging.info("Configuration loaded.") |
|
|
|
|
|
|
|
|
|
required_keys = [ |
|
|
|
"actual_src_vocab_size", |
|
"actual_tgt_vocab_size", |
|
|
|
"emb_size", |
|
"nhead", |
|
"ffn_hid_dim", |
|
"num_encoder_layers", |
|
"num_decoder_layers", |
|
"dropout", |
|
"max_len", |
|
|
|
|
|
"pad_token_id", |
|
"bos_token_id", |
|
"eos_token_id", |
|
] |
|
|
|
config_key_mapping = { |
|
"actual_src_vocab_size": config.get( |
|
"actual_src_vocab_size", config.get("src_vocab_size") |
|
), |
|
"actual_tgt_vocab_size": config.get( |
|
"actual_tgt_vocab_size", config.get("tgt_vocab_size") |
|
), |
|
"emb_size": config.get("emb_size"), |
|
"nhead": config.get("nhead"), |
|
"ffn_hid_dim": config.get("ffn_hid_dim"), |
|
"num_encoder_layers": config.get("num_encoder_layers"), |
|
"num_decoder_layers": config.get("num_decoder_layers"), |
|
"dropout": config.get("dropout"), |
|
"max_len": config.get("max_len"), |
|
"pad_token_id": config.get( |
|
"pad_token_id" |
|
), |
|
"bos_token_id": config.get( |
|
"bos_token_id" |
|
), |
|
"eos_token_id": config.get( |
|
"eos_token_id" |
|
), |
|
} |
|
|
|
config.update(config_key_mapping) |
|
|
|
missing_keys = [key for key in required_keys if config.get(key) is None] |
|
if missing_keys: |
|
|
|
defaults_used = [] |
|
|
|
missing_keys = [key for key in required_keys if config.get(key) is None] |
|
if missing_keys: |
|
raise ValueError( |
|
f"Config file '{CONFIG_FILENAME}' is missing required keys: {missing_keys}. " |
|
f"Ensure these were saved in the hyperparameters during training." |
|
) |
|
else: |
|
logging.warning( |
|
f"Config file was missing keys, used defaults for: {defaults_used}. This might be incorrect!" |
|
) |
|
|
|
|
|
logging.info( |
|
f"Using config values: src_vocab={config['actual_src_vocab_size']}, tgt_vocab={config['actual_tgt_vocab_size']}, " |
|
f"emb={config['emb_size']}, nhead={config['nhead']}, enc={config['num_encoder_layers']}, dec={config['num_decoder_layers']}, " |
|
f"pad={config['pad_token_id']}, sos={config['bos_token_id']}, eos={config['eos_token_id']}, max_len={config['max_len']}" |
|
) |
|
|
|
except FileNotFoundError: |
|
logging.error( |
|
f"Config file not found locally after download attempt: {config_path}" |
|
) |
|
raise gr.Error( |
|
f"Config Error: Config file '{CONFIG_FILENAME}' not found. Check file exists in repo." |
|
) |
|
except json.JSONDecodeError as e: |
|
logging.error(f"Error decoding JSON from config file {config_path}: {e}") |
|
raise gr.Error( |
|
f"Config Error: Could not parse '{CONFIG_FILENAME}'. Check its format. Error: {e}" |
|
) |
|
except ValueError as e: |
|
logging.error(f"Config validation error: {e}") |
|
raise gr.Error(f"Config Error: {e}") |
|
except Exception as e: |
|
logging.error( |
|
f"Unexpected error loading or validating config: {e}", exc_info=True |
|
) |
|
raise gr.Error( |
|
f"Config Error: Unexpected error processing config. Check logs. Error: {e}" |
|
) |
|
|
|
|
|
logging.info("Loading tokenizers...") |
|
try: |
|
smiles_tokenizer = Tokenizer.from_file(smiles_tokenizer_path) |
|
iupac_tokenizer = Tokenizer.from_file(iupac_tokenizer_path) |
|
logging.info("Tokenizers loaded.") |
|
|
|
|
|
pad_token = "<pad>" |
|
sos_token = "<sos>" |
|
eos_token = "<eos>" |
|
unk_token = "<unk>" |
|
|
|
issues = [] |
|
if smiles_tokenizer.token_to_id(pad_token) != config["pad_token_id"]: |
|
issues.append( |
|
f"SMILES PAD ID mismatch (tokenizer={smiles_tokenizer.token_to_id(pad_token)}, config={config['pad_token_id']})" |
|
) |
|
if smiles_tokenizer.token_to_id(unk_token) is None: |
|
issues.append("SMILES UNK token not found") |
|
|
|
if iupac_tokenizer.token_to_id(pad_token) != config["pad_token_id"]: |
|
issues.append( |
|
f"IUPAC PAD ID mismatch (tokenizer={iupac_tokenizer.token_to_id(pad_token)}, config={config['pad_token_id']})" |
|
) |
|
if iupac_tokenizer.token_to_id(sos_token) != config["bos_token_id"]: |
|
issues.append( |
|
f"IUPAC SOS ID mismatch (tokenizer={iupac_tokenizer.token_to_id(sos_token)}, config={config['bos_token_id']})" |
|
) |
|
if iupac_tokenizer.token_to_id(eos_token) != config["eos_token_id"]: |
|
issues.append( |
|
f"IUPAC EOS ID mismatch (tokenizer={iupac_tokenizer.token_to_id(eos_token)}, config={config['eos_token_id']})" |
|
) |
|
if iupac_tokenizer.token_to_id(unk_token) is None: |
|
issues.append("IUPAC UNK token not found") |
|
|
|
if issues: |
|
logging.warning( |
|
"Tokenizer validation issues detected: " + "; ".join(issues) |
|
) |
|
|
|
|
|
|
|
except Exception as e: |
|
logging.error( |
|
f"Failed to load tokenizers from {smiles_tokenizer_path} or {iupac_tokenizer_path}: {e}", |
|
exc_info=True, |
|
) |
|
raise gr.Error( |
|
f"Tokenizer Error: Could not load tokenizer files. Check Space logs. Error: {e}" |
|
) |
|
|
|
|
|
logging.info("Loading model from checkpoint...") |
|
try: |
|
|
|
|
|
model = SmilesIupacLitModule.load_from_checkpoint( |
|
checkpoint_path, |
|
|
|
|
|
src_vocab_size=config["actual_src_vocab_size"], |
|
tgt_vocab_size=config["actual_tgt_vocab_size"], |
|
hparams_dict=config, |
|
map_location=device, |
|
strict=False, |
|
|
|
) |
|
|
|
|
|
model.to(device) |
|
model.eval() |
|
model.freeze() |
|
logging.info( |
|
f"Model loaded successfully from {checkpoint_path}, set to eval mode, frozen, and moved to device '{device}'." |
|
) |
|
|
|
except FileNotFoundError: |
|
logging.error( |
|
f"Checkpoint file not found locally after download attempt: {checkpoint_path}" |
|
) |
|
raise gr.Error( |
|
f"Model Error: Checkpoint file '{CHECKPOINT_FILENAME}' not found." |
|
) |
|
except Exception as e: |
|
logging.error( |
|
f"Error loading model from checkpoint {checkpoint_path}: {e}", |
|
exc_info=True, |
|
) |
|
|
|
if "size mismatch" in str(e): |
|
error_detail = ( |
|
f"Potential size mismatch. Check if vocab sizes in config.json ({config.get('actual_src_vocab_size')}, " |
|
f"{config.get('actual_tgt_vocab_size')}) match the loaded checkpoint's embedding layers." |
|
) |
|
logging.error(error_detail) |
|
raise gr.Error(f"Model Error: {error_detail} Original error: {e}") |
|
elif "memory" in str(e).lower(): |
|
logging.warning("Potential Out-of-Memory error during model loading.") |
|
gc.collect() |
|
if device.type == "cuda": |
|
torch.cuda.empty_cache() |
|
raise gr.Error( |
|
f"Model Error: Out of memory loading model. Check Space resources. Error: {e}" |
|
) |
|
else: |
|
raise gr.Error( |
|
f"Model Error: Failed to load model checkpoint. Check Space logs. Error: {e}" |
|
) |
|
|
|
except gr.Error: |
|
raise |
|
except Exception as e: |
|
logging.error( |
|
f"Unexpected error during model/tokenizer loading: {e}", exc_info=True |
|
) |
|
raise gr.Error( |
|
f"Initialization Error: An unexpected error occurred. Check Space logs. Error: {e}" |
|
) |
|
|
|
|
|
|
|
def predict_iupac(smiles_string, beam_width_str, n_best_str): |
|
""" |
|
Performs SMILES to IUPAC translation using the loaded model and beam search. |
|
Takes string inputs from Gradio sliders/inputs and converts them. |
|
""" |
|
global model, smiles_tokenizer, iupac_tokenizer, device, config |
|
|
|
if not all([model, smiles_tokenizer, iupac_tokenizer, device, config]): |
|
error_msg = "Error: Model or tokenizers not loaded properly. App initialization might have failed. Check Space logs." |
|
logging.error(error_msg) |
|
|
|
try: |
|
n_best_int = int(n_best_str) |
|
except: |
|
n_best_int = 1 |
|
return "\n".join([f"{i + 1}. {error_msg}" for i in range(n_best_int)]) |
|
|
|
if not smiles_string or not smiles_string.strip(): |
|
error_msg = "Error: Please enter a valid SMILES string." |
|
try: |
|
n_best_int = int(n_best_str) |
|
except: |
|
n_best_int = 1 |
|
return "\n".join([f"{i + 1}. {error_msg}" for i in range(n_best_int)]) |
|
|
|
smiles_input = smiles_string.strip() |
|
|
|
|
|
try: |
|
beam_width = int(beam_width_str) |
|
n_best = int(n_best_str) |
|
if beam_width < 1 or n_best < 1 or n_best > beam_width: |
|
raise ValueError( |
|
"Beam width and n_best must be >= 1, and n_best <= beam width." |
|
) |
|
except ValueError as e: |
|
error_msg = f"Error: Invalid input parameter ({e}). Please check beam width, n_best, and length penalty values." |
|
logging.error(error_msg) |
|
|
|
return f"1. {error_msg}" |
|
|
|
try: |
|
|
|
|
|
sos_idx = config["bos_token_id"] |
|
eos_idx = config["eos_token_id"] |
|
pad_idx = config["pad_token_id"] |
|
gen_max_len = config["max_len"] |
|
|
|
predicted_names = translate( |
|
model=model, |
|
src_sentence=smiles_input, |
|
smiles_tokenizer=smiles_tokenizer, |
|
iupac_tokenizer=iupac_tokenizer, |
|
device=device, |
|
max_len=gen_max_len, |
|
sos_idx=sos_idx, |
|
eos_idx=eos_idx, |
|
pad_idx=pad_idx, |
|
beam_width=beam_width, |
|
n_best=n_best, |
|
length_penalty=0.0, |
|
) |
|
logging.info(f"Predictions returned: {predicted_names}") |
|
|
|
|
|
if not predicted_names: |
|
output_text = f"Input SMILES: {smiles_input}\n\nNo predictions generated (beam search might have failed)." |
|
else: |
|
|
|
display_names = predicted_names[:n_best] |
|
output_text = ( |
|
f"Input SMILES: {smiles_input}\n\n" |
|
f"Top {len(display_names)} Predictions (Beam Width={beam_width}, n_best={n_best}):\n" |
|
) |
|
output_text += "\n".join( |
|
[f"{i + 1}. {name}" for i, name in enumerate(display_names)] |
|
) |
|
|
|
if len(display_names) < n_best: |
|
output_text += f"\n\nNote: Only {len(display_names)} result(s) generated successfully." |
|
|
|
return output_text |
|
|
|
except RuntimeError as e: |
|
logging.error(f"Runtime error during translation: {e}", exc_info=True) |
|
error_msg = f"Runtime Error during translation: {e}" |
|
if "memory" in str(e).lower(): |
|
gc.collect() |
|
if device.type == "cuda": |
|
torch.cuda.empty_cache() |
|
error_msg += " (Potential OOM - try reducing beam width or input length)" |
|
|
|
return "\n".join([f"{i + 1}. {error_msg}" for i in range(n_best)]) |
|
|
|
except Exception as e: |
|
logging.error(f"Unexpected error during translation: {e}", exc_info=True) |
|
error_msg = f"Unexpected Error during translation: {e}" |
|
return "\n".join([f"{i + 1}. {error_msg}" for i in range(n_best)]) |
|
|
|
|
|
|
|
|
|
|
|
try: |
|
load_model_and_tokenizers() |
|
except gr.Error as ge: |
|
logging.error(f"Gradio Initialization Error: {ge}") |
|
|
|
|
|
pass |
|
except Exception as e: |
|
|
|
logging.error( |
|
f"Critical error during initial model loading sequence: {e}", exc_info=True |
|
) |
|
|
|
|
|
|
|
|
|
|
|
title = "SMILES to IUPAC Name Translator" |
|
description = f""" |
|
Enter a SMILES string to translate it into its IUPAC chemical name using a Transformer model ({MODEL_REPO_ID}) trained via PyTorch Lightning. |
|
Translation uses beam search decoding. Adjust parameters below. |
|
**Note:** Model loaded on **{str(device).upper()}**. Performance may vary. Check `config.json` in the repo for model details. |
|
""" |
|
|
|
|
|
examples = [ |
|
["CCO", 5, 3, 0.6], |
|
["C1=CC=CC=C1", 5, 3, 0.6], |
|
["CC(=O)Oc1ccccc1C(=O)O", 5, 3, 0.6], |
|
["CC(C)CC1=CC=C(C=C1)C(C)C(=O)O", 5, 3, 0.6], |
|
|
|
|
|
["INVALID_SMILES", 3, 1, 0.6], |
|
] |
|
|
|
|
|
smiles_input = gr.Textbox( |
|
label="SMILES String", |
|
placeholder="Enter SMILES string here (e.g., CCO for Ethanol)", |
|
lines=1, |
|
) |
|
|
|
beam_width_input = gr.Slider( |
|
minimum=1, |
|
maximum=10, |
|
value=5, |
|
step=1, |
|
label="Beam Width (k)", |
|
info="Number of sequences kept at each step (higher = more exploration, slower). Affects memory usage.", |
|
) |
|
n_best_input = gr.Slider( |
|
minimum=1, |
|
maximum=10, |
|
value=3, |
|
step=1, |
|
label="Number of Results (n_best)", |
|
info="How many top sequences to return (must be <= Beam Width).", |
|
) |
|
|
|
output_text = gr.Textbox( |
|
label="Predicted IUPAC Name(s)", lines=5, show_copy_button=True |
|
) |
|
|
|
|
|
iface = gr.Interface( |
|
fn=predict_iupac, |
|
inputs=[ |
|
smiles_input, |
|
beam_width_input, |
|
n_best_input, |
|
], |
|
outputs=output_text, |
|
title=title, |
|
description=description, |
|
examples=examples, |
|
allow_flagging="never", |
|
theme=gr.themes.Soft(primary_hue="blue", secondary_hue="cyan"), |
|
article=""" |
|
**Limitations:** Translation quality depends heavily on the model size, training data, and the complexity of the SMILES input. |
|
Very long or unusual SMILES strings may result in errors, timeouts, or inaccurate translations. |
|
Beam search parameters (width, penalty) significantly impact results and performance. |
|
""", |
|
|
|
|
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
iface.launch() |
|
|