"""Local Evolla example for Transformers 5.20.2.

Usage: python evolla_example.py protein.json
Input JSON keys: aa_seq, foldseek, question.
Requires PyTorch, Accelerate, model weights, and sufficient memory.
The bfloat16 configuration below is intended for a compatible GPU.
API references: https://huggingface.co/docs/transformers/model_doc/evolla
"""

import json
import sys
from pathlib import Path


def load_input(path):
    data = json.loads(Path(path).read_text(encoding="utf-8"))
    if not isinstance(data, dict):
        raise ValueError("Input must be a JSON object.")
    for key in ("aa_seq", "foldseek", "question"):
        if not isinstance(data.get(key), str) or not data[key].strip():
            raise ValueError(f"Provide a non-empty string for {key}.")
    aa_seq = data["aa_seq"].strip().upper()
    foldseek = data["foldseek"].strip().lower()
    if len(aa_seq) != len(foldseek):
        raise ValueError("aa_seq and foldseek must have the same length.")
    if not set(aa_seq) <= set("ACDEFGHIKLMNPQRSTVWY"):
        raise ValueError("Use the 20 standard amino acids in aa_seq, without gaps or placeholders.")
    if not set(foldseek) <= set("acdefghiklmnpqrstvwy#"):
        raise ValueError("Replace foldseek with an aligned Foldseek 3Di string (or # for masked positions).")
    return {"aa_seq": aa_seq, "foldseek": foldseek}, data["question"].strip()


def main(path):
    protein, question = load_input(path)

    import torch
    from transformers import EvollaForProteinText2Text, EvollaProcessor

    model_id = "westlake-repl/Evolla-10B-DPO-hf"
    # A directory containing a downloaded -hf checkpoint also works here.
    processor = EvollaProcessor.from_pretrained(model_id)
    model = EvollaForProteinText2Text.from_pretrained(
        model_id, device_map="auto", dtype=torch.bfloat16
    ).eval()

    messages = [[
        {"role": "system", "content": "You are an AI expert that can answer any questions about protein."},
        {"role": "user", "content": question},
    ]]
    inputs = processor(
        proteins=[protein],
        messages_list=messages,
        protein_max_length=1024,
        text_max_length=512,
        return_tensors="pt",
    ).to(model.device)

    with torch.inference_mode():
        output_ids = model.generate(
            **inputs, max_new_tokens=256, do_sample=False, use_cache=False
        )
    answer_ids = output_ids[:, inputs["input_ids"].shape[1]:]
    print(processor.batch_decode(answer_ids, skip_special_tokens=True)[0])


if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python evolla_example.py protein.json")
    main(sys.argv[1])
