|
|
|
|
|
|
|
|
|
|
|
from huggingface_hub import login |
|
|
|
|
|
|
|
|
|
|
|
import gradio as gr |
|
import torch |
|
from transformers import AutoModelForCausalLM, AutoTokenizer |
|
from huggingface_hub import hf_hub_download |
|
import json |
|
import os |
|
|
|
hf_token = os.getenv("HF_TOKEN") |
|
login(token=hf_token) |
|
|
|
MODEL_NAME = "google/txgemma-2b-predict" |
|
PROMPT_FILENAME = "tdc_prompts.json" |
|
MODEL_CACHE = "model_cache" |
|
MAX_EXAMPLES = 100 |
|
EXAMPLE_SMILES = "C1=CC=CC=C1" |
|
|
|
|
|
print(f"Loading model: {MODEL_NAME}...") |
|
tdc_prompts_data = None |
|
examples_list = [] |
|
try: |
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
print(f"Using device: {device}") |
|
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, cache_dir=MODEL_CACHE) |
|
print("Tokenizer loaded.") |
|
|
|
|
|
model = AutoModelForCausalLM.from_pretrained( |
|
MODEL_NAME, |
|
cache_dir=MODEL_CACHE, |
|
device_map="auto" |
|
) |
|
print("Model loaded.") |
|
|
|
|
|
print(f"Downloading {PROMPT_FILENAME}...") |
|
prompts_file_path = hf_hub_download( |
|
repo_id=MODEL_NAME, |
|
filename=PROMPT_FILENAME, |
|
cache_dir=MODEL_CACHE, |
|
|
|
) |
|
print(f"{PROMPT_FILENAME} downloaded to: {prompts_file_path}") |
|
|
|
|
|
with open(prompts_file_path, 'r') as f: |
|
tdc_prompts_data = json.load(f) |
|
print(f"Loaded prompts data from {PROMPT_FILENAME}.") |
|
|
|
|
|
|
|
|
|
if isinstance(tdc_prompts_data, dict): |
|
print(f"Processing {len(tdc_prompts_data)} prompts from dictionary...") |
|
count = 0 |
|
for prompt_template in tdc_prompts_data.values(): |
|
if count >= MAX_EXAMPLES: |
|
break |
|
if isinstance(prompt_template, str): |
|
|
|
example_prompt = prompt_template.replace("{Drug SMILES}", EXAMPLE_SMILES) |
|
|
|
examples_list.append([example_prompt, 100, 0.7]) |
|
count += 1 |
|
else: |
|
print(f"Warning: Skipping non-string value in prompts dictionary: {prompt_template}") |
|
print(f"Prepared {len(examples_list)} examples for Gradio.") |
|
|
|
else: |
|
print(f"Warning: Expected {PROMPT_FILENAME} to contain a dictionary, but found {type(tdc_prompts_data)}. Cannot load examples.") |
|
|
|
|
|
|
|
except Exception as e: |
|
print(f"Error loading model, tokenizer, or prompts: {e}") |
|
|
|
examples_list = [] |
|
raise gr.Error(f"Failed during setup. Check logs for details. Error: {e}") |
|
|
|
|
|
|
|
def predict(prompt, max_new_tokens=100, temperature=0.7): |
|
""" |
|
Generates text based on the input prompt using the loaded model. |
|
|
|
Args: |
|
prompt (str): The input text prompt. |
|
max_new_tokens (int): The maximum number of new tokens to generate. |
|
temperature (float): Controls the randomness of the generation. Lower is more deterministic. |
|
|
|
Returns: |
|
str: The generated text. |
|
""" |
|
print(f"Received prompt: {prompt}") |
|
print(f"Generation parameters: max_new_tokens={max_new_tokens}, temperature={temperature}") |
|
|
|
try: |
|
|
|
inputs = tokenizer(prompt, return_tensors="pt").to(model.device) |
|
|
|
|
|
with torch.no_grad(): |
|
outputs = model.generate( |
|
**inputs, |
|
max_new_tokens=int(max_new_tokens), |
|
temperature=float(temperature), |
|
do_sample=True if float(temperature) > 0 else False, |
|
pad_token_id=tokenizer.eos_token_id |
|
) |
|
|
|
|
|
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True) |
|
print(f"Generated text (raw): {generated_text}") |
|
|
|
|
|
if generated_text.startswith(prompt): |
|
prompt_length = len(prompt) |
|
result_text = generated_text[prompt_length:].lstrip() |
|
else: |
|
|
|
|
|
common_prefix = os.path.commonprefix([prompt, generated_text]) |
|
|
|
|
|
if len(prompt) > 0 and len(common_prefix) / len(prompt) > 0.8: |
|
result_text = generated_text[len(common_prefix):].lstrip() |
|
else: |
|
result_text = generated_text |
|
|
|
print(f"Generated text (processed): {result_text}") |
|
return result_text |
|
|
|
except Exception as e: |
|
print(f"Error during prediction: {e}") |
|
return f"An error occurred during generation: {e}" |
|
|
|
|
|
print("Creating Gradio interface...") |
|
with gr.Blocks(theme=gr.themes.Soft()) as demo: |
|
gr.Markdown( |
|
f""" |
|
# 🤖 TXGemma-2B-Predict Text Generation |
|
|
|
Enter a prompt below or select an example, and the model ({MODEL_NAME}) will generate text based on it. |
|
Adjust the parameters for different results. Examples loaded from `{PROMPT_FILENAME}`. |
|
Example prompts use the SMILES string `{EXAMPLE_SMILES}` (Benzene) as a placeholder. |
|
""" |
|
) |
|
with gr.Row(): |
|
with gr.Column(scale=2): |
|
prompt_input = gr.Textbox( |
|
label="Your Prompt", |
|
placeholder="Enter your text prompt here, potentially including a specific Drug SMILES string...", |
|
lines=5 |
|
) |
|
with gr.Row(): |
|
max_tokens_slider = gr.Slider( |
|
minimum=10, |
|
maximum=500, |
|
value=100, |
|
step=10, |
|
label="Max New Tokens", |
|
info="Maximum number of tokens to generate after the prompt." |
|
) |
|
temperature_slider = gr.Slider( |
|
minimum=0.0, |
|
maximum=1.5, |
|
value=0.7, |
|
step=0.05, |
|
label="Temperature", |
|
info="Controls randomness (0=deterministic, >0=random)." |
|
) |
|
submit_button = gr.Button("Generate Text", variant="primary") |
|
with gr.Column(scale=3): |
|
output_text = gr.Textbox( |
|
label="Generated Text", |
|
lines=10, |
|
interactive=False |
|
) |
|
|
|
|
|
submit_button.click( |
|
fn=predict, |
|
inputs=[prompt_input, max_tokens_slider, temperature_slider], |
|
outputs=output_text, |
|
api_name="predict" |
|
) |
|
|
|
|
|
if examples_list: |
|
gr.Examples( |
|
examples=examples_list, |
|
|
|
inputs=[prompt_input, max_tokens_slider, temperature_slider], |
|
outputs=output_text, |
|
fn=predict, |
|
cache_examples=False |
|
) |
|
else: |
|
gr.Markdown("_(Could not load examples from JSON file or file format was incorrect.)_") |
|
|
|
|
|
|
|
print("Launching Gradio app...") |
|
|
|
|
|
demo.queue().launch(debug=True) |
|
|
|
|
|
|