|
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
MODEL_NAME = "google/txgemma-2b-predict" |
|
|
|
PROMPT_FILENAME = "tdc_prompts.json" |
|
MODEL_CACHE = "model_cache" |
|
|
|
MAX_EXAMPLES = 600 |
|
EXAMPLE_SMILES = "C1=CC=CC=C1" |
|
DATAFRAME_HEADERS = ["Task Name", "Prompt Template"] |
|
DATAFRAME_ROW_COUNT = 8 |
|
|
|
hf_token = os.getenv("HF_TOKEN") |
|
login(token=hf_token) |
|
|
|
|
|
|
|
print(f"Loading model: {MODEL_NAME}...") |
|
tdc_prompts_data = None |
|
dataframe_data = [] |
|
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 for DataFrame...") |
|
for task_name, prompt_template in tdc_prompts_data.items(): |
|
if isinstance(prompt_template, str) and isinstance(task_name, str): |
|
|
|
dataframe_data.append([task_name, prompt_template]) |
|
else: |
|
print(f"Warning: Skipping invalid item in prompts dictionary: key={task_name}, value_type={type(prompt_template)}") |
|
print(f"Prepared {len(dataframe_data)} rows for DataFrame.") |
|
|
|
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}") |
|
|
|
dataframe_data = [] |
|
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. |
|
(Function remains the same as before) |
|
""" |
|
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}" |
|
|
|
|
|
def select_prompt_from_df(evt: gr.SelectData): |
|
""" |
|
Triggered when a row is selected in the DataFrame. |
|
Updates the main prompt input with the selected template, replacing the placeholder. |
|
""" |
|
if evt.index is None or evt.index[0] >= len(dataframe_data): |
|
print("Invalid selection event or index out of bounds.") |
|
return gr.update() |
|
|
|
selected_row_index = evt.index[0] |
|
|
|
prompt_template = dataframe_data[selected_row_index][1] |
|
|
|
|
|
selected_prompt = prompt_template.replace("{Drug SMILES}", EXAMPLE_SMILES) |
|
print(f"Selected prompt template from row {selected_row_index}, updated input.") |
|
|
|
|
|
return selected_prompt |
|
|
|
|
|
|
|
print("Creating Gradio interface...") |
|
with gr.Blocks(theme=gr.themes.Soft()) as demo: |
|
gr.Markdown( |
|
f""" |
|
# 🤖 TXGemma-2B-Predict Property Prediction |
|
|
|
Enter a prompt below, or select a task from the table to load its template, and the model ({MODEL_NAME}) will generate text. |
|
Adjust the parameters for different results. Prompt templates loaded from `{PROMPT_FILENAME}`. |
|
Selected templates will 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, or select a template from the table below...", |
|
lines=5, |
|
elem_id="prompt_input_box" |
|
) |
|
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 |
|
) |
|
|
|
|
|
gr.Markdown("### Select a Prompt Template") |
|
prompt_df = gr.DataFrame( |
|
value=dataframe_data, |
|
headers=DATAFRAME_HEADERS, |
|
row_count=(DATAFRAME_ROW_COUNT, "dynamic"), |
|
col_count=(len(DATAFRAME_HEADERS), "fixed"), |
|
wrap=True, |
|
label="Prompt Templates" |
|
) |
|
|
|
|
|
|
|
submit_button.click( |
|
fn=predict, |
|
inputs=[prompt_input, max_tokens_slider, temperature_slider], |
|
outputs=output_text, |
|
api_name="predict" |
|
) |
|
|
|
|
|
|
|
|
|
|
|
prompt_df.select( |
|
fn=select_prompt_from_df, |
|
inputs=None, |
|
outputs=prompt_input, |
|
show_progress="hidden" |
|
) |
|
|
|
|
|
|
|
print("Launching Gradio app...") |
|
demo.queue().launch(debug=True) |
|
|