ADMETlab 3.0 versus ADMETsar 3.0 frente a la base de datos Drugbank approved.


Ya hemos desarrollado un 'bot' para calculos con ADMETlab 3.0, a continuación se muestra un 'bot' para calculos con ADMETsar 3.0. Hemos aplicado ambos scripts sobre la base de datos Drugbank approved (puedes descargar una copia con estructuras 3D). Puedes descargar una copia de los cálculos de ADMET en este fichero Excel con macros.


Los colores de fondo en las celdas del fichero Excel de la figura anterior se consiguen con un script de Visual Basic para Aplicaciones (VBA) que puedes ver justo debajo.

¿Cómo se aplicar sobre un fichero Excel?

  1. Abre tu archivo admetlab30-DRUGBank-approved.xlsm.
  2. Pulsa ALT + F11 para abrir el editor de VBA.
  3. Ve a Insertar > Módulo.
  4. Pega el código de abajo.
  5. Cierra el editor de VBA y vuelve a Excel.
  6. Pulsa ALT + F8, selecciona ColorearSemaforosADMET y pulsa Ejecutar.

Option Explicit

' =========================================================================
' MACRO PRINCIPAL PARA COLOREAR LA TABLA ADMET
' =========================================================================
Sub ColorearSemaforosADMET()
    Dim ws As Worksheet
    Set ws = ActiveSheet
    Dim lastRow As Long, lastCol As Long
    
    ' Encontrar los límites de los datos
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).row
    lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column

    Dim col As Long, row As Long
    Dim rawHeader As String, cleanHeader As String
    Dim cellValue As Variant
    Dim bgColor As Long, fontColor As Long

    ' Apagamos la actualización de pantalla para que la macro vuele
    Application.ScreenUpdating = False

    ' Recorremos todas las columnas
    For col = 1 To lastCol
        rawHeader = CStr(ws.Cells(1, col).Value)
        cleanHeader = LimpiarCabecera(rawHeader)
        
        ' Recorremos todas las filas de esa columna
        For row = 2 To lastRow
            cellValue = ws.Cells(row, col).Value
            
            ' Solo procesamos si la celda no está vacía
            If Not IsEmpty(cellValue) Then
                bgColor = -1
                fontColor = RGB(0, 0, 0) ' Texto negro por defecto
                
                ' Obtenemos el color según las reglas
                bgColor = ObtenerColorADMET(cleanHeader, cellValue, fontColor)
                
                ' Si hay una regla para esta celda, la coloreamos
                If bgColor <> -1 Then
                    ws.Cells(row, col).Interior.Color = bgColor
                    ws.Cells(row, col).Font.Color = fontColor
                    ' Si el fondo es oscuro y el texto blanco, lo ponemos en negrita
                    If fontColor = RGB(255, 255, 255) Then ws.Cells(row, col).Font.Bold = True
                End If
            End If
        Next row
    Next col

    Application.ScreenUpdating = True
    MsgBox "¡La coloración del semáforo ADMET se ha completado con éxito!", vbInformation, "Proceso Terminado"
End Sub

' =========================================================================
' FUNCIÓN PARA LIMPIAR LOS NOMBRES DE LAS COLUMNAS (VERSIÓN MEJORADA)
' =========================================================================
Function LimpiarCabecera(ByVal header As String) As String
    header = LCase(Trim(header))
    
    ' 1. Quitar sufijos comunes
    header = Replace(header, " (prob)", "")
    header = Replace(header, " (da)", "")
    header = Replace(header, " (å²)", "")
    header = Replace(header, " (papp)", "")
    header = Replace(header, " (l/kg)", "")
    header = Replace(header, " (l/h/kg)", "")
    header = Replace(header, " (-log h)", "")
    header = Replace(header, " (log)", "")
    header = Replace(header, " (-log (td50 [mg/kg/day]))", "")
    header = Replace(header, " (-log ld50, mg/kg)", "")
    header = Replace(header, " (-log nmol/kg/day)", "")
    header = Replace(header, " (-log [igc50])", "")
    header = Replace(header, " (logbcf)", "")
    
    ' 2. Reemplazar símbolos problemáticos
    header = Replace(header, "µ", "u") ' Signo micro real
    header = Replace(header, "µ", "u") ' Letra griega mu
    
    ' 3. Aspiradora de prefijos: Quita cualquier número, punto, guion o espacio inicial
    Dim c As String
    Do While Len(header) > 0
        c = Left(header, 1)
        If IsNumeric(c) Or c = "." Or c = "-" Or c = " " Then
            header = Mid(header, 2)
        Else
            Exit Do
        End If
    Loop
    
    LimpiarCabecera = Trim(header)
End Function

' =========================================================================
' MOTOR DE REGLAS ADMET
' =========================================================================
Function ObtenerColorADMET(header As String, v As Variant, ByRef fontCol As Long) As Long
    ' Colores base
    Dim r As Long, Y As Long, g As Long
    r = HexToRGB("#C14E4E") ' Rojo
    Y = HexToRGB("#FFDF33") ' Amarillo
    g = HexToRGB("#63C28D") ' Verde
    
    Dim bg As Long
    bg = -1
    
    ' 1. REGLAS DE TEXTO
    Select Case header
        Case "gsk_rule", "lipinski_rule", "pfizer_rule"
            If LCase(CStr(v)) = "accept" Then bg = g
            If LCase(CStr(v)) = "not accept" Then bg = r
            GoTo FinishColor
            
        Case "bbb+/bbb-"
            If LCase(CStr(v)) = "bbb+" Then bg = g
            If LCase(CStr(v)) = "bbb-" Then bg = r
            GoTo FinishColor
    End Select
    
    ' Si el valor no es un número para el resto, salimos
    If Not IsNumeric(v) Then GoTo FinishColor
    
    ' 2. REGLAS NUMÉRICAS
    Select Case header
        Case "molecular weight", "mw"
            If v < 100 Or v > 600 Then bg = r
            If (v >= 100 And v < 200) Or (v > 500 And v <= 600) Then bg = Y
            If v >= 200 And v <= 500 Then bg = g
            
        Case "natom"
            If v < 5 Or v > 50 Then bg = r
            If (v >= 5 And v <= 14) Or (v >= 36 And v <= 50) Then bg = Y
            If v >= 15 And v <= 35 Then bg = g
            
        Case "nhet"
            If v = 0 Or v >= 16 Then bg = r
            If v = 1 Or (v >= 10 And v <= 15) Then bg = Y
            If v >= 2 And v <= 9 Then bg = g
            
        Case "nring"
            If v >= 7 Then bg = r
            If v = 0 Or (v >= 5 And v <= 6) Then bg = Y
            If v >= 1 And v <= 4 Then bg = g
            
        Case "nrot"
            If v >= 16 Then bg = r
            If v >= 10 And v <= 15 Then bg = Y
            If v >= 0 And v <= 9 Then bg = g
            
        Case "hba"
            If v >= 13 Then bg = r
            If v = 0 Or (v >= 11 And v <= 12) Then bg = Y
            If v >= 1 And v <= 10 Then bg = g
            
        Case "hbd"
            If v >= 6 Then bg = r
            If v >= 4 And v <= 5 Then bg = Y
            If v >= 0 And v <= 3 Then bg = g
            
        Case "tpsa"
            If v > 160 Then bg = r
            If v < 20 Or (v > 140 And v <= 160) Then bg = Y
            If v >= 20 And v <= 140 Then bg = g
            
        Case "slogp", "logp"
            If v < 0 Or v > 5 Then bg = r
            If (v >= 0 And v <= 1) Or (v > 3 And v <= 5) Then bg = Y
            If v > 1 And v <= 3 Then bg = g
            
        Case "logs"
            If v < -6 Or v > 1 Then bg = r
            If (v >= -6 And v <= -4) Or (v > 0.5 And v <= 1) Then bg = Y
            If v > -4 And v <= 0.5 Then bg = g
            
        Case "qed"
            bg = GetRangeCol(v, 0.35, 0.6, r, Y, g)
            
        Case "pka"
            If v < 0 Or v > 11 Then bg = r
            If (v >= 0 And v <= 3) Or (v > 8 And v <= 11) Then bg = Y
            If v > 3 And v <= 8 Then bg = g
            
        ' ====== NUEVAS REGLAS AÑADIDAS ======
        Case "acidic_pka"
            If v < 0 Or v > 12 Then bg = r
            If (v >= 0 And v < 3) Or (v > 9 And v <= 12) Then bg = Y
            If v >= 3 And v <= 9 Then bg = g
            
        Case "basic_pka"
            If v < 0 Or v > 11 Then bg = r
            If (v >= 0 And v < 3) Or (v > 9 And v <= 11) Then bg = Y
            If v >= 3 And v <= 9 Then bg = g
        ' ====================================

        Case "caco_2"
            bg = GetRangeCol(v, -6, -5.15, r, Y, g)
        Case "caco_2_c", "hia", "ugt_substrate", "ppb"
            bg = GetRangeCol(v, 0.3, 0.7, r, Y, g)
        Case "mdck"
            bg = GetRangeCol(v, 0.4, 0.6, r, Y, g)
        Case "f50", "f30", "f20"
            bg = GetRangeCol(v, 0.3, 0.5, r, Y, g)
        Case "bbb", "eye_irritation", "skin_corrosion", "skin_sensitisation"
            bg = GetRangeCol(v, 0.3, 0.8, r, Y, g)
            
        Case "oatp1b1_inhibitor"
            bg = GetRangeCol(v, 0.5, 0.8, HexToRGB("#DBDBDB"), HexToRGB("#FFB733"), r)
        Case "oatp1b3_inhibitor"
            bg = GetRangeCol(v, 0.6, 0.85, HexToRGB("#DBDBDB"), HexToRGB("#FF926A"), r)
        Case "oatp2b1_inhibitor"
            bg = GetRangeCol(v, 0.25, 0.45, g, Y, r)
        Case "oct1_inhibitor"
            bg = GetRangeCol(v, 0.25, 0.55, g, Y, r)
        Case "oct2_inhibitor"
            bg = GetRangeCol(v, 0.15, 0.45, g, Y, r)
        Case "bcrp_inhibitor", "cyp2b6_inhibitor"
            bg = GetRangeCol(v, 0.25, 0.6, g, Y, r)
        Case "bsep_inhibitor"
            bg = GetRangeCol(v, 0.25, 0.7, g, Y, r)
        Case "mate1_inhibitor"
            If v < 0.55 Then bg = g Else bg = r
            
        Case "pgp_inhibitor", "cyp1a2_inhibitor"
            bg = GetRangeCol(v, 0.2, 0.6, g, Y, r)
        Case "pgp_substrate"
            bg = GetRangeCol(v, 0.3, 0.7, HexToRGB("#3CB371"), HexToRGB("#FFD700"), HexToRGB("#FF8C00"))
        Case "vdss"
            bg = GetRangeCol(v, -0.6, 0.5, HexToRGB("#C96464"), HexToRGB("#FFE24C"), HexToRGB("#7995E9"))
            
        Case "cyp3a4_inhibitor", "cyp2c9_inhibitor", "cyp2c19_inhibitor"
            bg = GetRangeCol(v, 0.15, 0.5, g, Y, r)
        Case "cyp2d6_inhibitor"
            bg = GetRangeCol(v, 0.15, 0.8, g, Y, r)
            
        Case "cyp1a2_substrate"
            bg = GetRangeCol(v, 0.2, 0.6, HexToRGB("#9FD7EF"), HexToRGB("#DBDBDB"), HexToRGB("#6787E7"))
        Case "cyp3a4_substrate"
            bg = GetRangeCol(v, 0.3, 0.65, HexToRGB("#9FD7EF"), HexToRGB("#DBDBDB"), HexToRGB("#FFA333"))
        Case "cyp2b6_substrate"
            bg = GetRangeCol(v, 0.2, 0.8, HexToRGB("#9FD7EF"), HexToRGB("#DFCBDF"), HexToRGB("#845CAD"))
        Case "cyp2c9_substrate"
            bg = GetRangeCol(v, 0.2, 0.6, HexToRGB("#9FD7EF"), HexToRGB("#7FB1B3"), HexToRGB("#F39999"))
        Case "cyp2c19_substrate"
            bg = GetRangeCol(v, 0.25, 0.75, HexToRGB("#9FD7EF"), HexToRGB("#DBDBDB"), HexToRGB("#EDAB94"))
        Case "cyp2d6_substrate"
            bg = GetRangeCol(v, 0.2, 0.75, HexToRGB("#9FD7EF"), HexToRGB("#DBDBDB"), HexToRGB("#C777DB"))
            
        Case "hlm", "rlm", "clp_c", "dili", "nephrotoxicity", "ames", "skin_irritation", "hse"
            bg = GetRangeCol(v, 0.3, 0.7, g, Y, r)
        Case "clr"
            If v < 0.5 Then bg = HexToRGB("#FFE24C") Else bg = HexToRGB("#7DA7CA")
            
        Case "t50"
            bg = GetRangeCol(v, -1, 0, HexToRGB("#C96464"), HexToRGB("#76C99B"), HexToRGB("#7DA7CA"))
        Case "mrt"
            bg = GetRangeCol(v, -1.2, 0, HexToRGB("#C96464"), HexToRGB("#76C99B"), HexToRGB("#7DA7CA"))
            
        Case "neurotoxicity"
            bg = GetRangeCol(v, -2, -1.5, g, Y, r)
            
        ' ====== AÑADIDAS TODAS LAS VARIANTES POSIBLES DE hERG ======
        Case "herg_1um", "herg 1um"
            bg = GetRangeCol(v, 0.15, 0.4, g, Y, r)
        Case "herg_10um", "herg 10um"
            bg = GetRangeCol(v, 0.25, 0.75, g, Y, r)
        Case "herg_30um", "herg 30um", "eye_corrosion"
            bg = GetRangeCol(v, 0.25, 0.8, g, Y, r)
        Case "herg_1-10um", "herg_10-30um", "herg 1-10um", "herg 10-30um", "herg_1_10um", "herg_10_30um"
            bg = GetRangeCol(v, 0.3, 0.7, g, Y, r)
            
        Case "respiratory_toxicity"
            bg = GetRangeCol(v, 0.4, 0.8, HexToRGB("#00FF7F"), HexToRGB("#F0E68C"), HexToRGB("#CD853F"))
            
        Case "adt", "mouse_carcinogenicity_c", "rodents_carcinogenicity", "micronucleus", _
             "reproductive_toxicity", "mitochondrial_toxicity", "hemolytic_toxicity", "repeated_dose_toxicity", _
             "aot_c", "fdamdd_c", "ar", "er", "ar_lbd", "er_lbd", "aromatase", "ahr", "are", "atad5", _
             "p53", "ppar", "mmp", "tr", "gr", "subcapitata_toxicity", "crustaceans_toxicity", _
             "magna_toxicity", "fish_toxicity", "fathead_minnow_toxicity", "bluegill_sunfish_toxicity", _
             "rainbow_trout_toxicity", "sheepshead_minnow_toxicity", "pyriformis_toxicity_c", _
             "honey_bee_toxicity", "colinus_virginanus_toxicity", "anas_platyrhynchos_toxicity", _
             "bcf_c", "biodegradability", "photoinduced_toxicity", "phototoxicity_photoirritation", "photoallergy"
            bg = GetRangeCol(v, 0.4, 0.7, g, Y, r)
            
        Case "rat_carcinogenicity_c"
            bg = GetRangeCol(v, 0.5, 0.8, g, Y, r)
        Case "mouse_carcinogenicity", "rat_carcinogenicity", "fdamdd"
            bg = GetRangeCol(v, 1, 3, g, Y, r)
        Case "aot"
            bg = GetRangeCol(v, -2.7, -1.7, g, Y, r)
        Case "pyriformis_toxicity"
            bg = GetRangeCol(v, -0.5, 1, g, Y, r)
        Case "bcf"
            bg = GetRangeCol(v, 2, 3, g, Y, r)
            
    End Select

FinishColor:
    If bg <> -1 Then
        If bg = r Or bg = HexToRGB("#C14E4E") Or bg = HexToRGB("#C96464") _
           Or bg = HexToRGB("#845CAD") Or bg = HexToRGB("#6787E7") _
           Or bg = HexToRGB("#CD853F") Then
            fontCol = RGB(255, 255, 255) ' Blanco
        End If
    End If
    
    ObtenerColorADMET = bg
End Function

' =========================================================================
' FUNCIONES AUXILIARES
' =========================================================================
Function GetRangeCol(ByVal v As Double, ByVal t1 As Double, ByVal t2 As Double, ByVal cLow As Long, ByVal cMid As Long, ByVal cHigh As Long) As Long
    If v < t1 Then
        GetRangeCol = cLow
    ElseIf v <= t2 Then
        GetRangeCol = cMid
    Else
        GetRangeCol = cHigh
    End If
End Function

Function HexToRGB(hexColor As String) As Long
    Dim r As String, g As String, b As String
    hexColor = Replace(hexColor, "#", "")
    r = Mid(hexColor, 1, 2)
    g = Mid(hexColor, 3, 2)
    b = Mid(hexColor, 5, 2)
    HexToRGB = RGB(Val("&H" & r), Val("&H" & g), Val("&H" & b))
End Function

'bot' de Python...


"""
Robot para ADMETsar 3.0 con trazabilidad molécula <-> resultado.

Idea clave: la web solo acepta SMILES (sin nombres) y, si una molécula falla,
devuelve menos filas sin decir cuál falló. Para no perder el rastro:

1. Se leen los SMILES (opcionalmente con nombre) y se canonizan con RDKit.
   Los SMILES inválidos se detectan antes de enviar nada.
2. Se envían bloques de SMILES canónicos. Cada bloque guarda su fichero de
   entrada y su fichero de resultado, con el mismo nombre de etiqueta.
3. Al leer el resultado se alinea por una 'clave' (InChIKey de la molécula
   neutralizada, con estereoquímica), calculada igual para lo enviado y lo
   devuelto, porque el servidor neutraliza cargas. Si la web no devolviera
   SMILES, se alinea por posición (solo si el número de filas coincide).
4. Si no se puede alinear, el bloque se divide en mitades y se reenvía
   (bisección) hasta aislar la molécula problemática.
5. El fichero final contiene TODAS las moléculas de entrada, con una columna
   'estado': OK / SIN_RESULTADO / SMILES_INVALIDO / PENDIENTE.

Formato de entrada: un SMILES por línea, opcionalmente seguido de un nombre
separado por espacio o tabulador:
    CCO    etanol
    c1ccccc1
Requisitos: pip install pandas numpy rdkit selenium
(Selenium >= 4.6 descarga el chromedriver solo; ya no hace falta webdriver_manager.)
"""

print("Cargando librerías (pandas, RDKit, Selenium)...", flush=True)

import math
import shutil
import sys
import time
from functools import lru_cache
from pathlib import Path

import numpy as np
import pandas as pd
from rdkit import Chem, RDLogger
from rdkit.Chem.MolStandardize import rdMolStandardize
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

RDLogger.DisableLog('rdApp.*')

# --- CONFIGURACIÓN DE RUTAS ---
INPUT_FILE = Path(r'C:\Users\jant\Downloads\274library.txt')
WORK_DIR = Path(r'C:\Users\jant\Downloads\admetsar_work')
DOWNLOAD_DIR = WORK_DIR / 'descargas_tmp'  # solo descargas de Chrome (se vacía al inicio)
BLOQUES_DIR = WORK_DIR / 'bloques'  # NO se vacía: permite reanudar
FINAL_OUTPUT = INPUT_FILE.parent / 'resultados_admetsar3.tsv'
SIN_RESULTADO_OUTPUT = INPUT_FILE.parent / 'moleculas_sin_resultado.tsv'

# --- PARÁMETROS ---
TAMANO_BLOQUE = 1000  # máximo que admite ADMETsar 3.0 por envío
MAX_ENVIOS_POR_IP = 100  # límite de la web por IP y día
ENVIOS_USADOS_HOY = 0  # envíos ya gastados hoy con la IP actual (editar al reanudar)
MAX_PROFUNDIDAD_BISECCION = 3  # cada nivel gasta envíos de la cuota (0 = sin bisección)
REINTENTOS_WEB = 2  # reintentos ante fallos de la web (no ante moléculas malas)
MAX_RECARGAS_BOTON = 10
TIMEOUT_ELEMENTO = 20
TIMEOUT_JOB = 60
TIMEOUT_BOTON = 60
TIMEOUT_DESCARGA = 180
PAUSA_UI = 1
PAUSA_ENTRE_ENVIOS = 3

# --- WEB ---
URL_WEB = 'https://lmmd.ecust.edu.cn/admetsar3/predict.php'
PESTANA_ADMET_XPATH = '//*[@id="myTab"]/li[2]/a'
INPUT_FILE_XPATH = '//*[@id="smiles_file"]'
BOTON_SUBMIT_XPATH = '//*[@id="ios"]/div/div[2]/div[2]/a/button'
ENLACE_JOB_XPATH = '/html/body/div/div[1]/div[2]/ul/li[1]/a'
BOTON_TXT_XPATH = '/html/body/div/div/div[3]/div[2]/div[1]/a/button'

VACIO = pd.DataFrame({'clave': pd.Series([], dtype='object')})
_UNCHARGER = rdMolStandardize.Uncharger()


class Cuota:
    """Cuenta los envíos hechos con la IP actual (límite diario de la web)."""

    def __init__(self):
        self.usados = 0


CUOTA = Cuota()


def leer_input(texto, defecto='q'):
    print(
        '\n>>> El script espera una respuesta. En VS Code aparece en un cuadro de '
        'texto en la parte SUPERIOR de la ventana.'
    )
    try:
        return input(texto).strip().lower()
    except EOFError:
        return defecto


def pausa_cambio_ip():
    print(f'\n*** Alcanzados {MAX_ENVIOS_POR_IP} envíos con esta IP. ***')
    if leer_input('Cambia de IP (VPN) y pulsa Enter para continuar (q = terminar): ', 'q') == 'q':
        raise KeyboardInterrupt
    CUOTA.usados = 0


class ErrorWeb(Exception):
    """Fallo de infraestructura: la página no carga, falta un elemento, no llega la descarga."""


class JobSinResultado(Exception):
    """El job se creó pero el botón de descarga nunca apareció (posible molécula problemática)."""


# ----------------------------------------------------------------------------
# Entrada y utilidades
# ----------------------------------------------------------------------------
def canonizar(smiles):
    """SMILES canónico de RDKit, o None si es inválido."""
    if not isinstance(smiles, str) or not smiles.strip():
        return None
    mol = Chem.MolFromSmiles(smiles.strip())
    return Chem.MolToSmiles(mol) if mol is not None else None


def _clave_de_mol(mol):
    """InChIKey de la molécula neutralizada (o SMILES canónico si InChI falla)."""
    try:
        mol = _UNCHARGER.uncharge(mol)
    except Exception:
        pass
    try:
        key = Chem.MolToInchiKey(mol)
        if key:
            return key
    except Exception:
        pass
    return Chem.MolToSmiles(mol)


@lru_cache(maxsize=None)
def clave(smiles):
    """
    Clave de emparejamiento entre lo enviado y lo devuelto por el servidor.
    Neutraliza cargas (el servidor devuelve la forma neutra), conserva la
    estereoquímica y usa el InChIKey, que además absorbe diferencias de
    representación del SMILES y de hidrógenos móviles.
    """
    if not isinstance(smiles, str) or not smiles.strip():
        return None
    mol = Chem.MolFromSmiles(smiles.strip())
    return _clave_de_mol(mol) if mol is not None else None


def normalizar(smiles):
    """(SMILES canónico, clave) parseando la molécula una sola vez."""
    if not isinstance(smiles, str) or not smiles.strip():
        return None, None
    mol = Chem.MolFromSmiles(smiles.strip())
    if mol is None:
        return None, None
    return Chem.MolToSmiles(mol), _clave_de_mol(mol)


def cargar_entrada(ruta):
    """Lee el fichero de entrada y devuelve un DataFrame con una fila por molécula."""
    print(f'Leyendo y normalizando {ruta} ...', flush=True)
    filas = []
    with open(ruta, encoding='utf-8-sig') as f:
        for n_linea, linea in enumerate(f, start=1):
            linea = linea.strip()
            if not linea:
                continue
            partes = linea.split(None, 1)
            smiles = partes[0]
            if len(partes) > 1:
                nombre = partes[1].strip()
            else:
                nombre = f'mol_{len(filas) + 1:05d}'
            canon, k = normalizar(smiles)
            filas.append({
                'id': len(filas) + 1,
                'linea': n_linea,
                'nombre': nombre,
                'smiles_original': smiles,
                'smiles_canon': canon,
                'clave': k,
            })
            if len(filas) % 10000 == 0:
                print(f'  ...{len(filas)} moléculas normalizadas', flush=True)
    return pd.DataFrame(filas)


def dividir(lista, n):
    for i in range(0, len(lista), n):
        yield lista[i:i + n]


def preparar_carpetas():
    BLOQUES_DIR.mkdir(parents=True, exist_ok=True)
    DOWNLOAD_DIR.mkdir(parents=True, exist_ok=True)
    # Solo se limpia la subcarpeta de descargas temporales de Chrome
    for f in DOWNLOAD_DIR.iterdir():
        if f.is_file():
            try:
                f.unlink()
            except OSError as e:
                print(f'No se pudo borrar {f.name}: {e}')


def leer_resultado(ruta):
    """Lee un TXT de resultados (tabulador o coma). Devuelve None si no es legible."""
    for sep in ('\t', ','):
        try:
            df = pd.read_csv(ruta, sep=sep)
            if df.shape[1] > 1:
                return df
        except Exception:
            continue
    return None


def buscar_columna_smiles(df):
    for col in df.columns:
        if 'smiles' in str(col).lower():
            return col
    return None


def alinear(df, lote):
    """
    Asocia cada fila del resultado con las moléculas enviadas mediante 'clave'.
    Devuelve un DataFrame con la columna 'clave', o None si no es posible
    alinear con certeza.
    """
    claves_lote = {clave(s) for s in lote}
    col = buscar_columna_smiles(df)
    if col is not None:
        claves = df[col].map(clave)
        emparejadas = claves.isin(claves_lote)
        if emparejadas.mean() >= 0.5:
            sin_pareja = df.loc[~emparejadas, col]
            if len(sin_pareja):
                print(
                    f'    Aviso: {len(sin_pareja)} filas devueltas no coinciden con lo '
                    f'enviado. Ejemplos: {sin_pareja.head(3).tolist()}'
                )
            falta = len(claves_lote - set(claves.dropna()))
            if falta:
                print(f'    {falta} moléculas enviadas sin resultado.')
            return df.assign(clave=claves).loc[emparejadas].reset_index(drop=True)

    # Sin columna SMILES utilizable: solo es seguro alinear por posición
    # si no ha desaparecido ninguna fila.
    if len(df) == len(lote):
        print('    Aviso: alineado por posición (el resultado no trae SMILES utilizable).')
        return df.assign(clave=[clave(s) for s in lote])

    return None


# ----------------------------------------------------------------------------
# Selenium
# ----------------------------------------------------------------------------
def configurar_navegador():
    opciones = webdriver.ChromeOptions()
    opciones.add_argument('--ignore-certificate-errors')
    prefs = {
        'download.default_directory': str(DOWNLOAD_DIR),
        'download.prompt_for_download': False,
        'directory_upgrade': True,
        'safebrowsing.enabled': True,
    }
    opciones.add_experimental_option('prefs', prefs)
    return webdriver.Chrome(options=opciones)


def esperar_boton_txt(driver):
    for intento in range(1, MAX_RECARGAS_BOTON + 1):
        try:
            return WebDriverWait(driver, TIMEOUT_BOTON).until(
                EC.element_to_be_clickable((By.XPATH, BOTON_TXT_XPATH))
            )
        except TimeoutException:
            print(f'    Botón TXT no aparece. Recargando ({intento}/{MAX_RECARGAS_BOTON})...')
            driver.refresh()
            time.sleep(3)
    return None


def esperar_descarga(antes):
    """Espera a que aparezca un .txt nuevo y no queden .crdownload. Devuelve su ruta o None."""
    limite = time.time() + TIMEOUT_DESCARGA
    while time.time() < limite:
        nuevos = set(DOWNLOAD_DIR.glob('*.txt')) - antes
        if nuevos and not list(DOWNLOAD_DIR.glob('*.crdownload')):
            time.sleep(0.5)
            return max(nuevos, key=lambda p: p.stat().st_mtime)
        time.sleep(0.5)
    return None


def enviar_y_descargar(driver, ruta_in, ruta_out):
    """Sube ruta_in a ADMETsar, espera el cálculo y deja el resultado en ruta_out."""
    if CUOTA.usados >= MAX_ENVIOS_POR_IP:
        pausa_cambio_ip()
    driver.get(URL_WEB)

    pestana = WebDriverWait(driver, TIMEOUT_ELEMENTO).until(
        EC.element_to_be_clickable((By.XPATH, PESTANA_ADMET_XPATH))
    )
    driver.execute_script('arguments[0].click();', pestana)
    time.sleep(PAUSA_UI)

    campo = WebDriverWait(driver, TIMEOUT_ELEMENTO).until(
        EC.presence_of_element_located((By.XPATH, INPUT_FILE_XPATH))
    )
    campo.send_keys(str(ruta_in.resolve()))
    time.sleep(PAUSA_UI)

    boton = WebDriverWait(driver, TIMEOUT_ELEMENTO).until(
        EC.element_to_be_clickable((By.XPATH, BOTON_SUBMIT_XPATH))
    )
    driver.execute_script('arguments[0].click();', boton)
    CUOTA.usados += 1
    print(f'    Envío {CUOTA.usados}/{MAX_ENVIOS_POR_IP} con esta IP.')

    enlace = WebDriverWait(driver, TIMEOUT_JOB).until(
        EC.presence_of_element_located((By.XPATH, ENLACE_JOB_XPATH))
    )
    url_resultado = enlace.get_attribute('href')
    print(f'    Job generado: {url_resultado}')
    driver.get(url_resultado)

    boton_txt = esperar_boton_txt(driver)
    if boton_txt is None:
        raise JobSinResultado('El botón TXT no apareció.')

    antes = set(DOWNLOAD_DIR.glob('*.txt'))
    driver.execute_script('arguments[0].click();', boton_txt)
    descargado = esperar_descarga(antes)
    if descargado is None:
        raise ErrorWeb('No se detectó la descarga del TXT.')

    shutil.move(str(descargado), str(ruta_out))
    time.sleep(PAUSA_ENTRE_ENVIOS)


# ----------------------------------------------------------------------------
# Lógica por bloque
# ----------------------------------------------------------------------------
def en_cache(lote, etiqueta):
    """True si el bloque ya se descargó con exactamente esta entrada."""
    ruta_in = BLOQUES_DIR / f'{etiqueta}_input.txt'
    ruta_out = BLOQUES_DIR / f'{etiqueta}_result.txt'
    return (
        ruta_in.exists()
        and ruta_out.exists()
        and ruta_in.read_text(encoding='utf-8') == '\n'.join(lote) + '\n'
    )


def obtener_resultado(driver, lote, etiqueta):
    """Devuelve el DataFrame crudo del resultado (o None si no es legible)."""
    ruta_in = BLOQUES_DIR / f'{etiqueta}_input.txt'
    ruta_out = BLOQUES_DIR / f'{etiqueta}_result.txt'
    contenido = '\n'.join(lote) + '\n'

    # Reanudación: solo se reutiliza si la entrada guardada es idéntica
    if en_cache(lote, etiqueta):
        print(f'  {etiqueta}: usando resultado ya descargado.')
        return leer_resultado(ruta_out)

    ruta_out.unlink(missing_ok=True)
    ruta_in.write_text(contenido, encoding='utf-8')

    ultimo_error = None
    for intento in range(1, REINTENTOS_WEB + 1):
        try:
            enviar_y_descargar(driver, ruta_in, ruta_out)
            return leer_resultado(ruta_out)
        except (TimeoutException, WebDriverException, ErrorWeb) as e:
            ultimo_error = e
            print(f'    Fallo web ({type(e).__name__}) intento {intento}/{REINTENTOS_WEB}.')
    raise ErrorWeb(f'{etiqueta}: {type(ultimo_error).__name__}')


def procesar_lote(driver, lote, etiqueta, profundidad=0):
    """
    Procesa un lote y devuelve un DataFrame con 'clave' + parámetros.
    Si el resultado no se puede alinear con las moléculas enviadas, divide el
    lote en dos mitades y repite hasta aislar la molécula problemática.
    Lanza ErrorWeb si la web falla de forma persistente.
    """
    print(f'  {etiqueta}: {len(lote)} moléculas')
    alineado = None
    try:
        df = obtener_resultado(driver, lote, etiqueta)
        if df is not None:
            alineado = alinear(df, lote)
    except JobSinResultado as e:
        print(f'    {e}')

    if alineado is not None:
        return alineado

    if len(lote) == 1:
        print(f'    ✗ Sin resultado para: {lote[0]}')
        return VACIO

    if profundidad >= MAX_PROFUNDIDAD_BISECCION:
        print(
            f'    ✗ {len(lote)} moléculas sin resultado (límite de bisección alcanzado '
            'para no gastar cuota). Quedan como SIN_RESULTADO.'
        )
        return VACIO

    mitad = len(lote) // 2
    print(f'    Resultado no alineable: dividiendo {len(lote)} en {mitad} + {len(lote) - mitad}')
    partes = [
        procesar_lote(driver, lote[:mitad], etiqueta + 'a', profundidad + 1),
        procesar_lote(driver, lote[mitad:], etiqueta + 'b', profundidad + 1),
    ]
    partes = [p for p in partes if not p.empty]
    return pd.concat(partes, ignore_index=True) if partes else VACIO


# ----------------------------------------------------------------------------
# Salida
# ----------------------------------------------------------------------------
def guardar_resultados(entrada, resultados, intentados):
    resultados = [r for r in resultados if not r.empty]
    if resultados:
        res = (
            pd.concat(resultados, ignore_index=True)
            .dropna(subset=['clave'])
            .drop_duplicates('clave')
        )
    else:
        res = VACIO.copy()
    res = res.assign(_tiene_resultado=True)

    final = entrada.merge(
        res, on='clave', how='left', suffixes=('', '_admetsar')
    )

    invalido = final['clave'].isna()
    tiene = final['_tiene_resultado'].notna()
    intentado = final['clave'].isin(intentados)
    final['estado'] = np.select(
        [invalido, tiene, intentado],
        ['SMILES_INVALIDO', 'OK', 'SIN_RESULTADO'],
        default='PENDIENTE',
    )

    base = ['id', 'linea', 'nombre', 'smiles_original', 'smiles_canon', 'clave', 'estado']
    resto = [c for c in final.columns if c not in base and c != '_tiene_resultado']
    final = final[base + resto]

    final.to_csv(FINAL_OUTPUT, index=False, sep='\t')
    sin_res = final[final['estado'] != 'OK'][base]
    sin_res.to_csv(SIN_RESULTADO_OUTPUT, index=False, sep='\t')

    print('=' * 60)
    print(f'Resultados:       {FINAL_OUTPUT}')
    print(f'Sin resultado:    {SIN_RESULTADO_OUTPUT}')
    print(final['estado'].value_counts().to_string())
    print('=' * 60)


# ----------------------------------------------------------------------------
def main():
    print(f'Python: {sys.executable}', flush=True)
    if not INPUT_FILE.exists():
        print(f'Error: no se encontró el archivo {INPUT_FILE}')
        sys.exit(1)

    entrada = cargar_entrada(INPUT_FILE)
    n_invalidos = int(entrada['smiles_canon'].isna().sum())
    unicos = entrada['smiles_canon'].dropna().drop_duplicates().tolist()
    bloques = list(dividir(unicos, TAMANO_BLOQUE))

    print(
        f'{len(entrada)} moléculas leídas: {n_invalidos} SMILES inválidos, '
        f'{len(unicos)} únicos a enviar en {len(bloques)} bloques de {TAMANO_BLOQUE}.'
    )

    preparar_carpetas()
    pendientes = sum(
        not en_cache(b, f'bloque_{i:04d}') for i, b in enumerate(bloques, start=1)
    )
    print(
        f'Envíos necesarios (mínimo): {pendientes} de {len(bloques)} bloques '
        f'(el resto ya está descargado). Con {MAX_ENVIOS_POR_IP} envíos por IP: '
        f'~{math.ceil(pendientes / MAX_ENVIOS_POR_IP)} IP(s).'
    )
    CUOTA.usados = ENVIOS_USADOS_HOY
    print('Abriendo Chrome (la primera vez Selenium descarga el driver: puede tardar)...', flush=True)
    driver = configurar_navegador()
    print('Chrome abierto.', flush=True)

    resultados, intentados, bloques_fallidos = [], set(), []
    try:
        for i, bloque in enumerate(bloques, start=1):
            etiqueta = f'bloque_{i:04d}'
            print(f'\n--- Bloque {i} de {len(bloques)} ---')
            df = None
            while True:
                try:
                    df = procesar_lote(driver, bloque, etiqueta)
                    break
                except ErrorWeb as e:
                    print(f'  ✗ Fallo de la web: {e} (¿límite diario o caída del servidor?)')
                    accion = leer_input(
                        'Enter = cambié de IP, reintentar | r = reintentar sin cambiar '
                        '| s = saltar bloque | q = terminar: '
                    )
                    if accion == 'q':
                        raise KeyboardInterrupt
                    if accion == 's':
                        break
                    if accion != 'r':
                        CUOTA.usados = 0
            if df is None:
                bloques_fallidos.append(etiqueta)
                continue
            resultados.append(df)
            intentados.update(clave(s) for s in bloque)
            print(f'  -> {len(df)}/{len(bloque)} moléculas con resultado.')
    except KeyboardInterrupt:
        print('\nInterrumpido por el usuario.')
    finally:
        driver.quit()
        print('\nNavegador cerrado.')

    guardar_resultados(entrada, resultados, intentados)
    if bloques_fallidos:
        print(
            f'Bloques pendientes por fallo de la web: {", ".join(bloques_fallidos)}.\n'
            'Vuelve a ejecutar el script: se reanudará sin repetir los ya descargados.'
        )


if __name__ == '__main__':
    main()