YichaoLiu's picture
Update app.py
72b50e7 verified
import gradio as gr
from fastapi import FastAPI, HTTPException
from starlette.staticfiles import StaticFiles
import uvicorn
import logging
from pydantic import BaseModel
import pandas as pd
import time
import requests
import json
from typing import List, Dict, Any, Optional, Tuple
from fastapi.responses import RedirectResponse
from typing import Union
import tempfile
from PIL import Image
import io
import base64
from urllib.parse import quote
# Set up logging configuration
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# API configurations
API_BASE_URL = "https://songyou-llm-fastapi.hf.space"
FRAGMENT_ENDPOINT = f"{API_BASE_URL}/fragmentize"
GENERATE_ENDPOINT = f"{API_BASE_URL}/generate"
MOLECULE_IMG_ENDPOINT = f"{API_BASE_URL}/smiles2img"
SMILES_TO_IMG_ENDPOINT = f"{API_BASE_URL}/smiles2img"
# Load parameters from configuration file
try:
with open('param.json', 'r') as f:
params = json.load(f)
logger.info("Successfully loaded parameter configuration")
except Exception as e:
logger.error(f"Error loading parameter configuration: {str(e)}")
raise
# Data models
class SmilesData(BaseModel):
"""Model for SMILES data received from frontend"""
smiles: str
class GenerateRequest(BaseModel):
"""Request model for generate endpoint with updated fields"""
constSmiles: str
varSmiles: str
mainCls: str
minorCls: str
deltaValue: str
targetName: str
num: int
# Helper functions for metric handling
def get_metrics_for_objective(objective: str) -> List[str]:
"""Get the corresponding metrics for a given objective"""
if objective == "None" or objective not in params["Metrics"]:
return ["None"]
return ["None"] + params["Metrics"].get(objective, [])
def get_metric_full_name(objective: str, metric: str) -> str:
"""
Constructs the full metric name based on objective and metric.
For general physical properties, returns just the metric name.
For others, returns the metric name as is.
"""
if objective == "general physical properties":
return metric
return f"{metric}"
def get_metric_type(metric_name: str) -> str:
"""
Determines if a metric is boolean or sequential based on the BoolOrSeq mapping.
Returns 'bool', 'seq', or '' if not found.
"""
metric_type = params["BoolOrSeq"].get(metric_name, "")
logger.debug(f"Metric type for {metric_name}: {metric_type}")
return metric_type
def get_delta_choices(metric_type: str) -> List[str]:
"""Returns the appropriate choices for delta value based on metric type."""
if metric_type == "bool":
return params["ImprovementAnticipationBool"]
elif metric_type == "seq":
return params["ImprovementAnticipationSeq"]
return []
def validate_metric_combination(objective: str, metric: str) -> bool:
"""
Validates if the objective-metric combination is valid.
Returns True if valid, False otherwise.
"""
if objective == "None" or metric == "None":
logger.debug(f"Invalid objective or metric: {objective} - {metric}")
return False
if objective not in params["Metrics"]:
logger.debug(f"Objective not found in metrics: {objective}")
return False
if metric not in params["Metrics"].get(objective, []):
logger.debug(f"Metric not found in objective: {metric}")
return False
logger.debug(f"Valid metric combination: {objective} - {metric}")
return True
def handle_generate_analogs(
main_cls: str,
minor_cls: str,
number: int,
bool_delta_val: str,
seq_delta_val: str,
const_smiles: str,
var_smiles: str,
metric_type: str,
target_name: str
) -> pd.DataFrame:
"""
Handles the generation of analogs with appropriate delta value selection and error handling.
This function serves as the bridge between the UI and the generate_analogs API call.
Args:
main_cls (str): The main objective classification
minor_cls (str): The specific metric
number (int): Number of analogs to generate
bool_delta_val (str): Selected delta value for boolean metrics
seq_delta_val (str): Selected delta value for sequential metrics
const_smiles (str): Constant fragment SMILES
var_smiles (str): Variable fragment SMILES
metric_type (str): Type of metric ('bool' or 'seq')
target_name (str): Target name for the generation
Returns:
pd.DataFrame: DataFrame containing the generated analogs and their properties
"""
try:
# Input validation
if not all([main_cls, minor_cls, const_smiles, var_smiles]):
logger.error("Missing required inputs")
return pd.DataFrame()
if not validate_metric_combination(main_cls, minor_cls):
logger.error(f"Invalid metric combination: {main_cls} - {minor_cls}")
return pd.DataFrame()
# Select appropriate delta value based on metric type
if metric_type not in ["bool", "seq"]:
logger.error(f"Invalid metric type: {metric_type}")
return pd.DataFrame()
delta_value = bool_delta_val if metric_type == "bool" else seq_delta_val
# Generate analogs using the API
analogs_data = generate_analogs(
main_cls=main_cls,
minor_cls=minor_cls,
number=number,
delta_value=delta_value,
const_smiles=const_smiles,
var_smiles=var_smiles,
target_name=target_name
)
if not analogs_data:
logger.warning("No analogs generated")
return pd.DataFrame()
return update_output_table(analogs_data)
except Exception as e:
logger.error(f"Error in handle_generate_analogs: {str(e)}")
return pd.DataFrame()
# Update the fragment_molecule function to handle the new response format
def fragment_molecule(smiles: str) -> Tuple[str, str, str]:
"""
Call the fragment API endpoint to get molecule fragments
Returns: List of fragments with their details
"""
try:
logger.info(f"Calling fragment API with SMILES: {smiles}")
response = requests.get(f"{FRAGMENT_ENDPOINT}?smiles={smiles}")
response.raise_for_status()
data = response.json()
logger.info(f"Fragment API response: {data}")
# Return empty values if no fragments found
if not data.get("fragments"):
return "", "", ""
# Return the first fragment by default
first_fragment = data["fragments"][0]
return (
first_fragment.get("constant_smiles", ""),
first_fragment.get("variable_smiles", ""),
str(first_fragment.get("attachment_order", ""))
)
except Exception as e:
logger.error(f"Fragment API call failed: {str(e)}")
return "", "", ""
def generate_analogs(
main_cls: str,
minor_cls: str,
number: int,
delta_value: str,
const_smiles: str,
var_smiles: str,
target_name: str
) -> List[Dict[str, Any]]:
"""
Generate molecule analogs using the generate API endpoint with improved error handling
and validation.
"""
try:
# Validate inputs
if not all([const_smiles, var_smiles, main_cls, minor_cls, delta_value]):
logger.error("Missing required inputs for generate_analogs")
return []
# Create API request
payload = GenerateRequest(
constSmiles=const_smiles,
varSmiles=var_smiles,
mainCls=main_cls if main_cls != "None" else "",
minorCls=minor_cls if minor_cls != "None" else "",
deltaValue=delta_value,
targetName=target_name,
num=int(number)
)
logger.info(f"Calling generate API with payload: {payload.model_dump()}") # Updated to use model_dump
# Make API request
response = requests.post(
GENERATE_ENDPOINT,
headers={'Content-Type': 'application/json'},
json=payload.model_dump(), # Updated to use model_dump
timeout=500
)
response.raise_for_status()
results = response.json()
if not isinstance(results, list):
logger.error(f"Unexpected response format: {results}")
return []
logger.info(f"Successfully generated {len(results)} analogs")
return results
except requests.exceptions.Timeout:
logger.error("Generate API request timed out")
return []
except requests.exceptions.RequestException as e:
logger.error(f"Generate API request failed: {str(e)}")
return []
except Exception as e:
logger.error(f"Unexpected error in generate_analogs: {str(e)}")
return []
def generate_molecule_html_img(smiles: str) -> str:
"""Generate HTML img tag for molecule structure"""
try:
encoded_smiles = quote(smiles)
url = f"{SMILES_TO_IMG_ENDPOINT}?smiles={encoded_smiles}"
response = requests.get(
url,
headers={'Accept': 'image/png'},
timeout=10
)
if response.status_code == 200:
img_base64 = base64.b64encode(response.content).decode('utf-8')
return f'<img src="data:image/png;base64,{img_base64}" width="200" style="display: block; margin: auto;">'
return '<span style="color: red;">Image generation failed</span>'
except Exception as e:
logger.error(f"Error generating molecule image: {str(e)}")
return '<span style="color: red;">Image generation failed</span>'
def update_output_table(data: List[Dict[str, Any]]) -> pd.DataFrame:
"""Convert API response data to pandas DataFrame with HTML images"""
try:
df = pd.DataFrame(data)
# Convert SMILES to HTML img tags for molecule structures
if 'smile' in df.columns:
df['molecule_structure'] = df['smile'].apply(generate_molecule_html_img)
return df
except Exception as e:
logger.error(f"Error creating DataFrame: {str(e)}")
return pd.DataFrame()
def save_to_csv(data: pd.DataFrame, selected_only: bool = False) -> Optional[str]:
"""Save data to CSV file for Gradio download"""
try:
# Convert list to DataFrame if needed
if isinstance(data, list):
data = pd.DataFrame(data)
# Debug log actual data
logger.debug(f"DataFrame columns: {data.columns}")
logger.debug(f"DataFrame head: {data.head()}")
# If columns are numeric indices, rename them
if isinstance(data.columns, pd.RangeIndex):
# Assuming the data is in the expected order
column_names = ["smile", "molWt", "tpsa", "slogp", "sa", "qed", "molecule_structure"]
data.columns = column_names
# Filter out molecule_structure column for CSV export
columns_to_keep = ["smile", "molWt", "tpsa", "slogp", "sa", "qed"]
export_data = data[columns_to_keep]
with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as tmp:
export_data.to_csv(tmp.name, index=False)
return tmp.name
except Exception as e:
logger.error(f"Error saving to CSV: {str(e)}")
return None
def get_molecule_image(smiles: str) -> str:
"""Get molecule image URL from API"""
try:
response = requests.get(f"{MOLECULE_IMG_ENDPOINT}?smiles={requests.utils.quote(smiles)}")
response.raise_for_status()
return response.json().get("image_url", "")
except Exception as e:
logger.error(f"Error getting molecule image: {str(e)}")
return ""
def update_molecule_image(smiles: str) -> Optional[Image.Image]:
"""
更新分子图像预览,处理SMILES字符串并防止重复编码
Args:
smiles (str): SMILES分子式字符串
Returns:
Optional[Image.Image]: PIL图像对象或None(如果处理失败)
"""
try:
if not smiles:
return None
# 直接构建请求URL,避免params参数导致的重复编码
from urllib.parse import quote
encoded_smiles = quote(smiles, safe='')
url = f"{SMILES_TO_IMG_ENDPOINT}?smiles={encoded_smiles}"
logger.debug(f"Making request to URL: {url}")
# 发送请求时指定接受图片格式
headers = {
'Accept': 'image/png',
'Content-Type': 'application/json'
}
response = requests.get(
url, # 使用完整URL
headers=headers,
timeout=10
)
# 检查响应状态
if (response.status_code != 200):
logger.error(f"API请求失败: {response.status_code}")
logger.debug(f"Error response: {response.text}")
return None
content_type = response.headers.get('content-type', '')
# 如果返回的是JSON,检查是否有错误信息
if 'application/json' in content_type:
try:
error_data = response.json()
if 'error' in error_data:
logger.error(f"API返回错误: {error_data['error']}")
return None
except:
pass
# 尝试作为图片处理响应内容
try:
# 使用BytesIO处理二进制图片数据
image = Image.open(io.BytesIO(response.content))
# 如果图片不是RGB模式,转换为RGB
if image.mode != 'RGB':
image = image.convert('RGB')
return image
except Exception as e:
logger.error(f"图像处理失败: {str(e)}")
logger.debug(f"Response content type: {content_type}")
logger.debug(f"Response content (first 100 bytes): {response.content[:100]}")
return None
except Exception as e:
logger.error(f"更新分子图像时出错: {str(e)}")
return None
# FastAPI app initialization
app = FastAPI()
# Mount Ketcher static files
app.mount("/ketcher", StaticFiles(directory="ketcher"), name="ketcher")
@app.post("/update_smiles")
async def update_smiles(data: SmilesData):
"""Endpoint to receive SMILES data from frontend"""
try:
logger.info(f"Received SMILES from front-end: {data.smiles}")
return {"status": "ok", "received_smiles": data.smiles}
except Exception as e:
logger.error(f"Error processing SMILES update: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
# Ketcher interface HTML template
KETCHER_HTML = r'''
<iframe id="ifKetcher" src="/ketcher/index.html" width="100%" height="600px" style="border: 1px solid #ccc;"></iframe>
<script>
console.log("[Front-end] Ketcher-Gradio integration script loaded.");
let ketcher = null;
let lastSmiles = '';
function findSmilesInput() {
const inputContainer = document.getElementById('combined_smiles_input');
if (!inputContainer) {
console.warn("[Front-end] combined_smiles_input element not found.");
return null;
}
const input = inputContainer.querySelector('input[type="text"]');
return input;
}
function updateGradioInput(smiles) {
const input = findSmilesInput();
if (input && input.value !== smiles) {
input.value = smiles;
input.dispatchEvent(new Event('input', { bubbles: true }));
console.log("[Front-end] Updated Gradio input with SMILES:", smiles);
}
}
async function handleKetcherChange() {
console.log("[Front-end] handleKetcherChange called, retrieving SMILES...");
try {
const smiles = await ketcher.getSmiles({ arom: false });
console.log("[Front-end] SMILES retrieved from Ketcher:", smiles);
if (smiles !== lastSmiles) {
lastSmiles = smiles;
updateGradioInput(smiles);
fetch('/update_smiles', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({smiles: smiles})
})
.then(res => res.json())
.then(data => {
console.log("[Front-end] Backend response:", data);
})
.catch(err => console.error("[Front-end] Error sending SMILES to backend:", err));
}
} catch (err) {
console.error("[Front-end] Error getting SMILES from Ketcher:", err);
}
}
function initKetcher() {
console.log("[Front-end] initKetcher started.");
const iframe = document.getElementById('ifKetcher');
if (!iframe) {
console.error("[Front-end] iframe not found.");
setTimeout(initKetcher, 500);
return;
}
const ketcherWindow = iframe.contentWindow;
if (!ketcherWindow || !ketcherWindow.ketcher) {
console.log("[Front-end] ketcher not yet available in iframe, retrying...");
setTimeout(initKetcher, 500);
return;
}
ketcher = ketcherWindow.ketcher;
console.log("[Front-end] Ketcher instance acquired:", ketcher);
ketcher.setMolecule('C').then(() => {
console.log("[Front-end] Initial molecule set to 'C'.");
});
const editor = ketcher.editor;
console.log("[Front-end] Editor object:", editor);
let eventBound = false;
if (editor && typeof editor.subscribe === 'function') {
console.log("[Front-end] Using editor.subscribe('change', ...)");
editor.subscribe('change', handleKetcherChange);
eventBound = true;
}
if (!eventBound) {
console.error("[Front-end] No suitable event binding found. Check Ketcher version and event API.");
}
}
document.getElementById('ifKetcher').addEventListener('load', () => {
console.log("[Front-end] iframe loaded. Initializing Ketcher in 1s...");
setTimeout(initKetcher, 1000);
});
</script>
'''
def create_combined_interface():
"""
Creates the main Gradio interface combining Ketcher, molecule fragmentation,
and analog generation functionalities with fragment selection.
"""
with gr.Blocks(theme=gr.themes.Default()) as demo:
# Update the title
gr.Markdown("# Single-point Chemical Language Model")
# Main layout with two columns
with gr.Column():
with gr.Row():
# Ketcher editor
gr.HTML(KETCHER_HTML)
# Controls and inputs below Ketcher
with gr.Group():
gr.Markdown("### Input SMILES (From Ketcher)")
with gr.Row():
combined_smiles_input = gr.Textbox(
label="",
value="CC(=O)Nc1cc(-c2cc(F)cc(OC3CCN(C)C3)c2)nc(-n2nc(C)cc2C)n1",
placeholder="SMILES from Ketcher will appear here",
elem_id="combined_smiles_input"
)
molecule_image = gr.Image(
label="Molecule Preview",
visible=True,
show_label=True,
type="pil", # 使用 PIL 格式
height=300, # 增加高度
width=400, # 增加宽度
scale=1, # 保持原始比例
image_mode='RGB' # 确保使用RGB模式
)
with gr.Row():
get_ketcher_smiles_btn = gr.Button("Get SMILES from Ketcher", variant="primary")
fragment_btn = gr.Button("Find Fragments", variant="secondary")
# Fragment Selection section - Add group and markdown for better organization
with gr.Group():
gr.Markdown("### Available Fragments")
fragments_table = gr.Dataframe(
headers=["Variable Fragment", "Constant Fragment", "Order", "Fragment Structure"],
datatype=["str", "str", "str", "html"], # 确保图片列类型为 html
type="array",
interactive=True,
label="Click a row to select fragmentation pattern",
wrap=True,
row_count=10,
elem_classes="fragment-table" # 添加自定义样式类
)
# Selected Fragment Display
with gr.Group():
gr.Markdown("### Selected Fragment")
with gr.Row():
constant_frag_input = gr.Textbox(
label="Constant Fragment",
placeholder="SMILES of constant fragment",
interactive=True
)
variable_frag_input = gr.Textbox(
label="Variable Fragment",
placeholder="SMILES of variable fragment",
interactive=True
)
attach_order_input = gr.Textbox(
label="Attachment Order",
placeholder="Attachment Order",
interactive=True
)
# Analog generation section
with gr.Group():
gr.Markdown("### Generate Analogs")
current_metric_type = gr.State("")
with gr.Row():
target_name = gr.Dropdown(
label="Target Name",
choices=params["targetNames"],
value=params["targetNames"][0] if params["targetNames"] else None,
info="Select or type target name", # Replace placeholder with info
allow_custom_value=True, # Allow user to enter custom values
filterable=True # Enable search functionality
)
number_input = gr.Number(
label="Number of Analogs",
value=3,
step=1,
minimum=1,
maximum=500
)
with gr.Row():
main_cls_dropdown = gr.Dropdown(
label="Objective",
choices=["None"] + params["Objective"],
value="None",
interactive=True # Enable search
)
minor_cls_dropdown = gr.Dropdown(
label="Metrics",
choices=["None"],
value="None",
interactive=True # Enable search
)
with gr.Row():
bool_delta = gr.Dropdown(
choices=params["ImprovementAnticipationBool"],
label="Target Direction (Boolean)",
value=params["ImprovementAnticipationBool"][0], # Set default to first item
interactive=True, # Enable search
visible=True, # Ensure visibility
info="Select desired change direction"
)
seq_delta = gr.Dropdown(
choices=params["ImprovementAnticipationSeq"],
label="Target Range (Sequential)",
value=params["ImprovementAnticipationSeq"][0], # Set default to first item
interactive=True, # Enable search
visible=False,
info="Select desired value range"
)
generate_analogs_btn = gr.Button("Generate Analogs", variant="primary")
# Results section - Update the Dataframe configuration for HTML display
with gr.Group():
gr.Markdown("### Generated Analogs")
gr.Markdown(
"Note: Generating analogs can take a while (up to 500 seconds). "
"Please do not close this window while waiting."
)
output_table = gr.Dataframe(
headers=["smile", "molWt", "tpsa", "slogp", "sa", "qed", "molecule_structure"],
label="Generated Analogs",
datatype=["str", "number", "number", "number", "number", "number", "html"], # Changed 'image' back to 'html'
type="array",
interactive=False,
wrap=True,
row_count=15
)
with gr.Row():
download_all_btn = gr.Button("Download Results", variant="secondary")
# Helper functions for fragment handling
def process_fragments_response(response_data):
"""Process the API response into table format with molecule structure images"""
try:
fragments = response_data.get("fragments", [])
processed_fragments = []
for fragment in fragments:
variable_smiles = fragment.get("variable_smiles", "")
constant_smiles = fragment.get("constant_smiles", "")
attachment_order = str(fragment.get("attachment_order", ""))
# 生成分子结构的HTML图片标签,与 Generated Analogs 保持一致的样式
molecule_html = generate_molecule_html_img(variable_smiles) # 使用相同的函数
if not molecule_html.startswith('<span'): # 如果不是错误消息
molecule_html = f'<div style="width:200px; margin:auto;">{molecule_html}</div>'
processed_fragments.append([
variable_smiles,
constant_smiles,
attachment_order,
molecule_html
])
return processed_fragments
except Exception as e:
logger.error(f"Error processing fragments: {str(e)}")
return []
def get_fragments(smiles: str):
"""
Get and process fragments from API by calling the fragmentize endpoint.
Handles multiple fragmentation patterns returned by the API.
Args:
smiles (str): Input SMILES string to fragmentize
Returns:
list: A list of rows where each row represents a possible fragmentation pattern
"""
try:
# URL encode the SMILES string to handle special characters
encoded_smiles = requests.utils.quote(smiles)
url = f"{FRAGMENT_ENDPOINT}?smiles={encoded_smiles}"
logger.info(f"Calling fragmentize API with URL: {url}")
response = requests.get(url)
response.raise_for_status()
data = response.json()
# Process fragments from the response
fragments = data.get('fragments', [])
logger.info(f"Found {len(fragments)} possible fragmentations")
# Convert each fragment into a table row format with image
processed_fragments = process_fragments_response(data)
return processed_fragments
except Exception as e:
logger.error(f"Error processing fragments: {str(e)}")
return []
def update_selected_fragment(evt: gr.SelectData, fragments_data):
"""Update fragment fields when table row is selected"""
try:
if not fragments_data or evt.index[0] >= len(fragments_data):
logger.warning("No valid fragment selected")
return ["", "", ""]
selected = fragments_data[evt.index[0]]
logger.info(f"Selected fragment pattern {evt.index[0]}: var={selected[0]}, const={selected[1]}, order={selected[2]}")
return [selected[1], selected[0], selected[2]]
except Exception as e:
logger.error(f"Error updating selected fragment: {str(e)}")
return ["", "", ""]
def update_delta_inputs(objective: str, metric: str) -> dict:
"""
Updates the visibility and options of delta inputs based on metric type.
Shows boolean or sequential delta input based on the metric's type.
Args:
objective (str): The selected objective
metric (str): The selected metric
Returns:
dict: Updates for both delta inputs and the current metric type
"""
if not validate_metric_combination(objective, metric):
return {
bool_delta: gr.update(visible=False),
seq_delta: gr.update(visible=False),
current_metric_type: ""
}
metric_name = get_metric_full_name(objective, metric)
metric_type = get_metric_type(metric_name)
return {
bool_delta: gr.update(visible=metric_type == "bool"),
seq_delta: gr.update(visible=metric_type == "seq"),
current_metric_type: metric_type
}
def update_metrics_dropdown(objective: str) -> dict:
"""
Updates the metrics dropdown based on the selected objective.
Uses the get_metrics_for_objective helper function to get valid metrics for the chosen objective.
Args:
objective (str): The selected objective from the main dropdown
Returns:
dict: A Gradio update object containing the new dropdown configuration
"""
metrics = get_metrics_for_objective(objective)
return gr.Dropdown(choices=metrics, value="None")
# Event handlers
get_ketcher_smiles_btn.click(
fn=None,
inputs=None,
outputs=combined_smiles_input,
js="async () => { const iframe = document.getElementById('ifKetcher'); if(iframe && iframe.contentWindow && iframe.contentWindow.ketcher) { const smiles = await iframe.contentWindow.ketcher.getSmiles(); return smiles; } else { console.error('Ketcher not ready'); return ''; } }"
)
# Fragment processing handlers
fragment_btn.click(
fn=get_fragments,
inputs=[combined_smiles_input],
outputs=[fragments_table]
)
fragments_table.select(
fn=update_selected_fragment,
inputs=[fragments_table],
outputs=[constant_frag_input, variable_frag_input, attach_order_input]
)
# Metric selection handlers
main_cls_dropdown.change(
fn=update_metrics_dropdown,
inputs=[main_cls_dropdown],
outputs=[minor_cls_dropdown]
)
main_cls_dropdown.change(
fn=update_delta_inputs,
inputs=[main_cls_dropdown, minor_cls_dropdown],
outputs=[bool_delta, seq_delta, current_metric_type]
)
minor_cls_dropdown.change(
fn=update_delta_inputs,
inputs=[main_cls_dropdown, minor_cls_dropdown],
outputs=[bool_delta, seq_delta, current_metric_type]
)
# Analog generation handler
generate_analogs_btn.click(
fn=handle_generate_analogs,
inputs=[
main_cls_dropdown,
minor_cls_dropdown,
number_input,
bool_delta,
seq_delta,
constant_frag_input,
variable_frag_input,
current_metric_type,
target_name
],
outputs=[output_table]
)
# Download handlers
download_all_btn.click(
lambda df: save_to_csv(df, False),
inputs=[output_table],
outputs=[gr.File(label="Download CSV")]
)
# Add SMILES change handler for molecule image
combined_smiles_input.change(
fn=update_molecule_image,
inputs=[combined_smiles_input],
outputs=[molecule_image],
show_progress=True # 添加加载提示
)
# 添加 Ketcher SMILES 获取时的图片更新
get_ketcher_smiles_btn.click(
fn=update_molecule_image,
inputs=[combined_smiles_input],
outputs=[molecule_image],
show_progress=True
)
# Add this call to update molecule image on page load:
demo.load(
fn=update_molecule_image,
inputs=[combined_smiles_input],
outputs=[molecule_image]
)
return demo
# Mount the Gradio app
combined_demo = create_combined_interface()
app = gr.mount_gradio_app(app, combined_demo, path="/")
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)
#CC(=O)Nc1cc(-c2cc(F)cc(OC3CCN(C)C3)c2)nc(-n2nc(C)cc2C)n1