import streamlit as st # Must be the first Streamlit command st.set_page_config(page_title="Medical Research AI Assistant", layout="wide") import pandas as pd import numpy as np #import matplotlib.pyplot as plt import requests import os import groq import json import torch import torch.nn as nn from rdkit import Chem from rdkit.Chem import Draw import google.generativeai as genai # type: ignore from rdkit.Chem import Descriptors, AllChem #from drug_dicovery_pipeline_a import JTVAE, PropertyPredictor, IntegratedMoleculeGenerator, PropertyOptimizationExperiment, optimize_antibiotic, optimize_cns_drug # type: ignore #from drug_dicovery_pipeline_a import MoleculeParser, mol_to_tensor, run_optimization_from_initial_points # type: ignore from drug_dicovery_pipeline_aa import JTVAE, PropertyPredictor, IntegratedMoleculeGenerator, PropertyOptimizationExperiment, optimize_antibiotic, optimize_cns_drug # type: ignore from drug_dicovery_pipeline_aa import MoleculeParser, mol_to_tensor, run_optimization_from_initial_points # type: ignore # # Configure Gemini API GOOGLE_API_KEY = "AIzaSyCg-nx7szAFMMPfCkBEyP2GHfq74ZJSBd4" # Replace with your API key genai.configure(api_key=GOOGLE_API_KEY) # # Configure Groq API # GROQ_API_KEY = "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" # Replace with your actual API key # client = groq.Client(api_key=GROQ_API_KEY # Hardcoded user credentials VALID_CREDENTIALS = { "admin": "admin2025", "researcher1": "pass123", "researcher2": "pass456" } def check_password(): """Returns `True` if the user had a correct password.""" def password_entered(): """Checks whether a password entered by the user is correct.""" if ( st.session_state["username"] in VALID_CREDENTIALS and st.session_state["password"] == VALID_CREDENTIALS[st.session_state["username"]] ): st.session_state["password_correct"] = True del st.session_state["password"] # Don't store password del st.session_state["username"] # Don't store username else: st.session_state["password_correct"] = False # First run, show inputs for username + password if "password_correct" not in st.session_state: st.text_input( "Username", key="username" ) st.text_input( "Password", type="password", key="password" ) st.button("Log In", on_click=password_entered) return False # Password incorrect, show input + error elif not st.session_state["password_correct"]: st.text_input( "Username", key="username" ) st.text_input( "Password", type="password", key="password" ) st.button("Log In", on_click=password_entered) st.error("😕 Invalid username or password") return False # Password correct return True st.title("🏥 Medical Research AI Assistant") # def get_ai_response(system_prompt, user_prompt): # """Function to handle AI responses from OpenRouter""" # try: # headers = { # "Authorization": f"Bearer {OPENROUTER_API_KEY}", # "HTTP-Referer": "https://localhost:8501", # "Content-Type": "application/json" # } # data = { # "model": "google/gemma-2-9b-it:free", # "messages": [ # {"role": "system", "content": system_prompt}, # {"role": "user", "content": user_prompt} # ], # "max_tokens": 1000 # } # response = requests.post(OPENROUTER_URL, headers=headers, json=data) # if response.status_code != 200: # return f"API Error: Status code {response.status_code}. Please try again." # response_json = response.json() # if 'error' in response_json: # return f"API Error: {response_json['error']}" # try: # if 'choices' in response_json and len(response_json['choices']) > 0: # if 'message' in response_json['choices'][0]: # return response_json['choices'][0]['message']['content'] # elif 'text' in response_json['choices'][0]: # return response_json['choices'][0]['text'] # elif 'response' in response_json: # return response_json['response'] # else: # return "Unexpected API response format. Raw response: " + str(response_json) # except Exception as e: # return f"Error parsing API response: {str(e)}\nRaw response: {str(response_json)}" # except Exception as e: # return f"Error: {str(e)}\nPlease try again or contact support." # def get_ai_response(system_prompt, user_prompt): # """Enhanced function to handle AI responses from OpenRouter with improved error handling""" # try: # headers = { # "Authorization": f"Bearer {OPENROUTER_API_KEY}", # "HTTP-Referer": "https://localhost:8501", # "Content-Type": "application/json" # } # data = { # "model": "mistralai/mistral-7b-instruct:free", # "messages": [ # {"role": "system", "content": system_prompt}, # {"role": "user", "content": user_prompt} # ], # "max_tokens": 1000 # } # # Add timeout to prevent hanging # response = requests.post(OPENROUTER_URL, headers=headers, json=data, timeout=30) # # Check for non-200 status codes # if response.status_code != 200: # error_message = f""" # API Error (Status {response.status_code}): # - Response: {response.text} # - Headers: {dict(response.headers)} # Please check your API key and try again. # """ # st.error(error_message) # return None # try: # response_json = response.json() # except json.JSONDecodeError as e: # error_message = f""" # Failed to decode API response: # - Error: {str(e)} # - Raw response: {response.text[:500]} # """ # st.error(error_message) # return None # # Check for encoding issues in the response # if '' in str(response_json): # error_message = """ # Encoding error detected in API response. # This might be due to: # 1. Character encoding mismatch # 2. API rate limiting # 3. Token validation issues # Please try: # 1. Checking your API key # 2. Reducing the input length # 3. Waiting a few minutes before retrying # """ # st.error(error_message) # return None def get_ai_response(system_prompt, user_prompt): """Function to handle AI responses from Google Gemini""" try: # Initialize the model model = genai.GenerativeModel('gemini-1.5-flash-latest') # Combine system and user prompts combined_prompt = f"{system_prompt}\n\n{user_prompt}" # Generate response response = model.generate_content(combined_prompt) return response.text except Exception as e: return f"Error: {str(e)}\nPlease try again or contact support." # Extract the response content if 'choices' in response_json and len(response_json['choices']) > 0: if 'message' in response_json['choices'][0]: return response_json['choices'][0]['message']['content'] elif 'text' in response_json['choices'][0]: return response_json['choices'][0]['text'] elif 'response' in response_json: return response_json['response'] else: st.error(f"Unexpected API response format: {str(response_json)}") return None except requests.exceptions.Timeout: st.error("Request timed out. Please try again.") return None except requests.exceptions.RequestException as e: st.error(f"Network error: {str(e)}") return None except Exception as e: st.error(f"Unexpected error: {str(e)}") return None # def get_groq_response(system_prompt, user_prompt): # """Function to handle AI responses from Groq API""" # try: # # Prepare messages in the required format for Groq API # messages = [ # {"role": "system", "content": system_prompt}, # {"role": "user", "content": user_prompt} # ] # # Call the Groq API # chat_completion = client.chat.completions.create( # messages=messages, # model="llama3-8b-8192", # Example model, replace with the appropriate one # temperature=0.7, # max_tokens=2048, # top_p=1, # stream=False # ) # # Extract and return the response content # return chat_completion.choices[0].message.content # except requests.exceptions.Timeout: # return "Error: Request timed out. Please try again." # except requests.exceptions.RequestException as e: # return f"Error: Network error occurred: {str(e)}" # except Exception as e: # return f"Error: {str(e)}. Please contact support or try again." def analyze_symptoms(symptoms, medical_history): """Analyze symptoms and medical history""" system_prompt = """You are a medical research assistant analyzing patient symptoms and medical history. Provide detailed analysis and recommendations based on the provided information.""" user_prompt = f"""Please analyze the following patient information: Symptoms: {symptoms} Medical History: {medical_history} Please provide: 1. Potential diagnoses 2. Recommended treatments 3. Additional tests or consultations needed 4. Precautions and warnings """ return get_ai_response(system_prompt, user_prompt) def analyze_research_paper(paper_text): """Analyze research papers""" system_prompt = """You are a medical research assistant analyzing scientific papers. Provide a comprehensive analysis of the research paper including methodology, findings, and implications.""" user_prompt = f"""Please analyze the following research paper: {paper_text} Please provide: 1. Key findings and conclusions 2. Methodology assessment 3. Clinical implications 4. Research gaps and future directions """ return get_ai_response(system_prompt, user_prompt) def analyze_clinical_trials(condition, trial_data): """Analyze clinical trials data""" system_prompt = """You are a medical research assistant analyzing clinical trials data. Provide insights and analysis of the trial results.""" user_prompt = f"""Please analyze the following clinical trial data for {condition}: {trial_data} Please provide: 1. Trial effectiveness analysis 2. Safety considerations 3. Statistical significance 4. Recommendations for future trials """ return get_ai_response(system_prompt, user_prompt) # def generate_drug_research(target_condition, existing_treatments): # """Generate drug research directions""" # system_prompt = """You are a drug discovery assistant helping researchers identify new treatment approaches. # Provide comprehensive research directions based on current scientific understanding.""" # user_prompt = f"""Please generate research directions for treating {target_condition}. # Existing treatments: # {existing_treatments} # Please provide: # 1. Potential novel approaches # 2. Research priorities # 3. Possible mechanisms of action # 4. Development considerations # """ # return get_groq_response(system_prompt, user_prompt) def enhanced_generate_drug_research(target_condition, existing_treatments): """Enhanced version that specifically looks for chemical structures in the response""" system_prompt = """You are a drug discovery assistant helping researchers identify new treatment approaches. When suggesting novel compounds, please include their SMILES notation. Format SMILES strings on their own line prefixed with 'SMILES: '.""" user_prompt = f"""Please generate research directions for treating {target_condition}, including specific chemical structures where relevant. Existing treatments: {existing_treatments} Please provide: 1. Potential novel approaches with SMILES notations for suggested compounds 2. Research priorities 3. Possible mechanisms of action 4. Development considerations For any suggested compounds, please include their SMILES notation on a new line prefixed with 'SMILES: ' """ response = get_ai_response(system_prompt, user_prompt) return response def molecule_optimization_interface(molecules_data): """ Creates an interface for molecular optimization using Streamlit Args: molecules_data (list): List of dictionaries containing molecule information Returns: list: Selected optimized molecules """ try: # Debug print to verify data input st.write("Received molecules data:", len(molecules_data), "molecules") # Convert list of dictionaries to DataFrame for easier handling df = pd.DataFrame(molecules_data) # Create SMILES to RDKit molecule objects df['mol'] = df['smiles'].apply(lambda x: Chem.MolFromSmiles(x)) # Display molecular properties in a table st.write("#### Molecular Properties") property_df = df[['smiles', 'mol_weight', 'logP']].copy() property_df.columns = ['SMILES', 'Molecular Weight', 'LogP'] st.dataframe(property_df) # Create molecular visualization st.write("#### Molecule Structures") cols = st.columns(2) for idx, row in df.iterrows(): with cols[idx % 2]: img = Draw.MolToImage(row['mol']) st.image(img, caption=f"Molecule {idx + 1}\nMW: {row['mol_weight']:.2f}, LogP: {row['logP']:.2f}") # Add optimization parameters st.write("#### Optimization Parameters") # Allow users to set target ranges for properties col1, col2 = st.columns(2) with col1: target_mw_min = st.number_input("Target MW Min", value=float(df['mol_weight'].min()), step=10.0) target_logp_min = st.number_input("Target LogP Min", value=float(df['logP'].min()), step=0.1) with col2: target_mw_max = st.number_input("Target MW Max", value=float(df['mol_weight'].max()), step=10.0) target_logp_max = st.number_input("Target LogP Max", value=float(df['logP'].max()), step=0.1) # Filter molecules based on criteria filtered_molecules = df[ (df['mol_weight'] >= target_mw_min) & (df['mol_weight'] <= target_mw_max) & (df['logP'] >= target_logp_min) & (df['logP'] <= target_logp_max) ] if len(filtered_molecules) > 0: st.success(f"Found {len(filtered_molecules)} molecules matching the criteria") # Display filtered molecules st.write("#### Filtered Molecules") cols = st.columns(2) for idx, row in filtered_molecules.iterrows(): with cols[idx % 2]: img = Draw.MolToImage(row['mol']) st.image(img, caption=f"Molecule {idx + 1}\nMW: {row['mol_weight']:.2f}, LogP: {row['logP']:.2f}") # Allow selection of molecules selected_indices = st.multiselect( "Select molecules to optimize", options=filtered_molecules.index, format_func=lambda x: f"Molecule {x+1}" ) if selected_indices: selected_molecules = filtered_molecules.loc[selected_indices].to_dict('records') return selected_molecules else: st.warning("No molecules match the current criteria. Please adjust the parameters.") return [] except Exception as e: st.error(f"Error in molecule optimization interface: {str(e)}") return [] # Sidebar navigation page = st.sidebar.selectbox( "Choose a Function", ["Symptom Analysis", "Research Paper Analysis", "Drug Discovery Assistant", "Clinical Trials Analysis"] ) def main(): """Main application logic""" # Your existing main app code here #st.title("🏥 Hussain's Medical Research AI Assistant") # Sidebar navigation page = st.sidebar.selectbox( "Choose a Function", ["Symptom Analysis", "Research Paper Analysis", "Drug Discovery Assistant", "Clinical Trials Analysis"] ) # Main content area if page == "Symptom Analysis": st.header("Symptom Analysis") symptoms = st.text_area("Enter Patient Symptoms:", height=150) medical_history = st.text_area("Enter Medical History:", height=150) if st.button("Analyze"): if symptoms and medical_history: analysis = analyze_symptoms(symptoms, medical_history) st.write("### Analysis Results") st.write(analysis) else: st.warning("Please enter both symptoms and medical history") elif page == "Research Paper Analysis": st.header("Research Paper Analysis") paper_text = st.text_area("Paste Research Paper Text:", height=300) if st.button("Analyze Paper"): if paper_text: analysis = analyze_research_paper(paper_text) st.write("### Paper Analysis") st.write(analysis) else: st.warning("Please enter the research paper text") elif page == "Clinical Trials Analysis": st.header("Clinical Trials Analysis") condition = st.text_input("Medical Condition:") trial_data = st.text_area("Enter Clinical Trial Data:", height=300) if st.button("Analyze Trials"): if condition and trial_data: analysis = analyze_clinical_trials(condition, trial_data) st.write("### Clinical Trials Analysis") st.write(analysis) else: st.warning("Please enter both condition and trial data") # elif page == "Drug Discovery Assistant": # st.header("Drug Discovery Assistant") # if 'research_results' not in st.session_state: # st.session_state.research_results = None # if 'extracted_molecules' not in st.session_state: # st.session_state.extracted_molecules = [] # discovery_mode = st.selectbox( # "Select Discovery Mode", # ["Research Directions", "Molecule Optimization"] # ) # if discovery_mode == "Research Directions": # target_condition = st.text_input("Target Condition:") # existing_treatments = st.text_area("Current Treatment Approaches:", height=200) # if st.button("Generate Research Directions"): # if target_condition: # # Store the research results in session state # research_directions = enhanced_generate_drug_research(target_condition, existing_treatments) # #st.session_state.research_results = research_directions # st.write("### AI-Generated Research Directions") # st.write(research_directions) # # Extract SMILES strings from the research results # parser = MoleculeParser() # smiles_list = parser.extract_smiles(research_directions) # if smiles_list: # print(smiles_list) # st.session_state.extracted_molecules = parser.validate_and_process_smiles(smiles_list) # #st.session_state.extracted_molecules = parser.validate_and_process_smiles(smiles_list) # print(st.session_state.extracted_molecules) # # Add button to run optimization on extracted molecules # if st.button("Optimize Extracted Molecules"): # # Debug print # st.write("Button clicked!") # # Check if we have molecules in session state # if hasattr(st.session_state, 'extracted_molecules') and st.session_state.extracted_molecules: # st.write("### Molecular Optimization") # # Use actual session state data # molecules_data = st.session_state.extracted_molecules # else: # # Use sample data for testing # st.write("Using sample data for testing") # molecules_data = sample_data # type: ignore # # Call optimization interface # selected_mols = molecule_optimization_interface(molecules_data) # # Display results # if selected_mols: # st.write("#### Selected Molecules for Optimization") # st.json(selected_mols) # else: # st.warning("No molecules were selected for optimization") # # Initialize models # # jtvae = JTVAE(latent_dim=128, hidden_dim=256) # # property_predictor = PropertyPredictor(input_dim=128) # # generator = IntegratedMoleculeGenerator(jtvae, property_predictor) # # # Define default optimization parameters # # target_properties = { # # 'logP': 2.5, # # 'QED': 0.8, # # 'SA': 3.0, # # 'TOX': 0.1 # # } # # with st.spinner("Running optimization..."): # # try: # # # Convert molecules to tensors and run optimization # # initial_points = [mol_to_tensor(mol['mol']) for mol in selected_mols] # # results = run_optimization_from_initial_points( # # generator, # # initial_points, # # target_properties # # ) # # st.success("Optimization completed!") # # st.write("### Optimization Results") # # # Display results # # for idx, round_result in enumerate(results): # # st.write(f"#### Round {idx + 1}") # # st.write(f"Best score: {round_result['best_scores'].max():.3f}") # # # Display top molecules from each round # # for i, mol in enumerate(round_result['best_candidates'][:3]): # # props = generator.property_predictor(mol) # # st.write(f"Molecule {i+1}:") # # st.write(f"- LogP: {props[0]:.2f}") # # st.write(f"- QED: {props[1]:.2f}") # # st.write(f"- SA: {props[2]:.2f}") # # st.write(f"- Toxicity: {props[3]:.2f}") # # except Exception as e: # # st.error(f"Error during optimization: {str(e)}") # # else: # # st.warning("No valid molecules were extracted from the research directions.") # else: # st.warning("Please enter a target condition") # # else: # Molecule Optimization mode # else: # Molecule Optimization mode # # if st.session_state.extracted_molecules: # # selected_mols = molecule_optimization_interface(st.session_state.extracted_molecules) # # if selected_mols: # # st.subheader("Optimization Parameters") # # st.write("### AI-Generated Research Directions") # # st.write(selected_mols) # # else: # # st.warning("Please enter a target condition") # # # ... (existing Molecule Optimization logic) # # # else: # # # st.info("No molecules available for optimization. Please run Research Directions first to generate molecular structures.") #st.subheader("Molecule Optimization Pipeline") # # Create tabs for different optimization tasks # task_tab = st.tabs(["General Optimization", "CNS Drugs", "Antibiotics", "Custom Properties"]) # with task_tab[0]: # General Optimization # st.write("Configure general molecule optimization parameters") # col1, col2 = st.columns(2) # with col1: # target_logp = st.slider("Target LogP", -2.0, 7.0, 2.5) # target_qed = st.slider("Target QED (Drug-likeness)", 0.0, 1.0, 0.8) # with col2: # target_sa = st.slider("Target Synthetic Accessibility", 1.0, 10.0, 3.0) # target_tox = st.slider("Maximum Toxicity", 0.0, 1.0, 0.1) # n_samples = st.number_input("Number of molecules to generate", 1, 100, 10) # n_rounds = st.number_input("Number of optimization rounds", 1, 20, 5) # if st.button("Run Optimization"): # try: # # Initialize models # # jtvae = JTVAE() # # property_predictor = PropertyPredictor(input_dim=128) # # generator = IntegratedMoleculeGenerator(jtvae, property_predictor) # jtvae = JTVAE(latent_dim=128, hidden_dim=256) # Encoder only # property_predictor = PropertyPredictor(input_dim=128) # Use latent representation for property prediction # generator = IntegratedMoleculeGenerator(jtvae, property_predictor) # target_properties = { # 'logP': target_logp, # 'QED': target_qed, # 'SA': target_sa, # 'TOX': target_tox # } # with st.spinner("Running optimization pipeline..."): # experiment = PropertyOptimizationExperiment(generator) # results = experiment.run_optimization_campaign( # target_properties, # n_rounds=n_rounds # ) # st.success("Optimization completed!") # st.write("### Best Molecules") # # Display results # for idx, round_result in enumerate(results): # st.write(f"#### Round {idx + 1}") # st.write(f"Best score: {round_result['best_scores'].max():.3f}") # # Display top 3 molecules from each round # top_mols = round_result['best_candidates'][:3] # for i, mol in enumerate(top_mols): # props = generator.property_predictor(mol) # st.write(f"Molecule {i+1}:") # st.write(f"- LogP: {props[0]:.2f}") # st.write(f"- QED: {props[1]:.2f}") # st.write(f"- SA: {props[2]:.2f}") # st.write(f"- Toxicity: {props[3]:.2f}") # except Exception as e: # st.error(f"Error during optimization: {str(e)}") # with task_tab[1]: # CNS Drugs # st.write("Optimize molecules for CNS drug properties") # if st.button("Run CNS Drug Optimization"): # with st.spinner("Optimizing CNS drug candidates..."): # try: # molecules = optimize_cns_drug() # st.success("Optimization completed!") # st.write("### Generated CNS Drug Candidates") # # Display results similar to general optimization # except Exception as e: # st.error(f"Error during CNS optimization: {str(e)}") # with task_tab[2]: # Antibiotics # st.write("Optimize molecules for antibiotic properties") # if st.button("Run Antibiotic Optimization"): # with st.spinner("Optimizing antibiotic candidates..."): # try: # results = optimize_antibiotic() # st.success("Optimization completed!") # st.write("### Generated Antibiotic Candidates") # # Display results similar to general optimization # except Exception as e: # st.error(f"Error during antibiotic optimization: {str(e)}") # with task_tab[3]: # Custom Properties # st.write("Define custom property constraints") # st.write("Add property constraints:") # custom_properties = {} # # Dynamic property addition # if 'num_properties' not in st.session_state: # st.session_state.num_properties = 1 # for i in range(st.session_state.num_properties): # col1, col2, col3 = st.columns([2, 1, 1]) # with col1: # prop_name = st.text_input(f"Property {i+1} name", key=f"prop_name_{i}") # with col2: # prop_min = st.number_input(f"Min value {i+1}", key=f"prop_min_{i}") # with col3: # prop_max = st.number_input(f"Max value {i+1}", key=f"prop_max_{i}") # if prop_name: # custom_properties[prop_name] = (prop_min, prop_max) # if st.button("Add Property"): # st.session_state.num_properties += 1 # if st.button("Run Custom Optimization"): # if custom_properties: # try: # # Initialize models with custom properties # jtvae = JTVAE() # property_predictor = PropertyPredictor(input_dim=128) # generator = IntegratedMoleculeGenerator(jtvae, property_predictor) # molecules = generator.generate_molecules_with_properties( # n_samples=10, # property_constraints=custom_properties # ) # st.success("Custom optimization completed!") # st.write("### Generated Molecules") # # Display results # except Exception as e: # st.error(f"Error during custom optimization: {str(e)}") # else: # st.warning("Please add at least one property constraint") elif page == "Drug Discovery Assistant": st.header("Drug Discovery Assistant") # Initialize session state variables if 'research_results' not in st.session_state: st.session_state.research_results = None if 'extracted_molecules' not in st.session_state: st.session_state.extracted_molecules = [] if 'show_optimization' not in st.session_state: st.session_state.show_optimization = False if 'selected_molecules' not in st.session_state: st.session_state.selected_molecules = None discovery_mode = st.selectbox( "Select Discovery Mode", ["Research Directions", "Molecule Optimization"] ) def reset_optimization(): st.session_state.show_optimization = False st.session_state.selected_molecules = None if discovery_mode == "Research Directions": target_condition = st.text_input("Target Condition:") existing_treatments = st.text_area("Current Treatment Approaches:", height=200) generate_button = st.button("Generate Research Directions") if generate_button: reset_optimization() # Reset optimization state when generating new research if target_condition: # Generate research directions research_directions = enhanced_generate_drug_research(target_condition, existing_treatments) st.session_state.research_results = research_directions st.write("### AI-Generated Research Directions") st.write(research_directions) # Extract SMILES strings parser = MoleculeParser() smiles_list = parser.extract_smiles(research_directions) if smiles_list: # Process and validate SMILES st.session_state.extracted_molecules = parser.validate_and_process_smiles(smiles_list) if st.session_state.extracted_molecules: st.write("### Extracted Molecules") st.write(f"Found {len(st.session_state.extracted_molecules)} valid molecules") st.session_state.show_optimization = True else: st.warning("Please enter a target condition") # Show optimization interface if molecules are available if st.session_state.show_optimization: st.write("### Molecular Optimization") # Use actual molecules or sample data molecules_data = (st.session_state.extracted_molecules if len(st.session_state.extracted_molecules) > 0 else sample_data) # type: ignore # Create columns for a better layout col1, col2 = st.columns([2, 1]) with col1: st.write("#### Available Molecules") # Display all available molecules in a grid molecule_grid = st.columns(2) for idx, mol_data in enumerate(molecules_data): with molecule_grid[idx % 2]: mol_obj = Chem.MolFromSmiles(mol_data['smiles']) if mol_obj: img = Draw.MolToImage(mol_obj) st.image(img, caption=f"Molecule {idx + 1}") st.write(f"MW: {mol_data['mol_weight']:.2f}") st.write(f"LogP: {mol_data['logP']:.2f}") st.write(f"SMILES: `{mol_data['smiles']}`") with col2: st.write("#### Selection Controls") # Add multiselect for molecule selection selected_indices = st.multiselect( "Select molecules to optimize", options=list(range(len(molecules_data))), format_func=lambda x: f"Molecule {x+1}" ) # Add optimize button if st.button("Run Optimization", key="run_opt"): if selected_indices: st.session_state.selected_molecules = [molecules_data[i] for i in selected_indices] st.write("#### Selected Molecules for Optimization") # Display selected molecules for idx, mol in enumerate(st.session_state.selected_molecules): st.write(f"**Molecule {idx + 1}**") mol_obj = Chem.MolFromSmiles(mol['smiles']) if mol_obj: img = Draw.MolToImage(mol_obj) st.image(img, caption=f"Structure of Molecule {idx + 1}") st.write(f"Molecular Weight: {mol['mol_weight']:.2f}") st.write(f"LogP: {mol['logP']:.2f}") st.write(f"SMILES: `{mol['smiles']}`") # Run optimization with st.spinner("Running optimization..."): try: # Initialize models jtvae = JTVAE(latent_dim=128, hidden_dim=256) property_predictor = PropertyPredictor(input_dim=128) generator = IntegratedMoleculeGenerator(jtvae, property_predictor) # Define default optimization parameters target_properties = { 'logP': 2.5, 'QED': 0.8, 'SA': 3.0, 'TOX': 0.1 } # Convert molecules to tensors and run optimization initial_points = [mol_to_tensor(mol['mol']) for mol in st.session_state.selected_molecules] print("ip:", initial_points) print(generator) experiment = PropertyOptimizationExperiment(generator) results = experiment.run_optimization_campaign( target_properties, initial_points=initial_points, n_rounds=5 ) st.success("Optimization completed!") st.write("### Optimization Results") # Display results for idx, round_result in enumerate(results): st.write(f"#### Round {idx + 1}") st.write(f"Best score: {round_result['best_scores'].max():.3f}") # Display top molecules from each round for i, mol in enumerate(round_result['best_candidates'][:3]): props = generator.property_predictor(mol) st.write(f"Molecule {i+1}:") st.write(f"- LogP: {props[0]:.2f}") st.write(f"- QED: {props[1]:.2f}") st.write(f"- SA: {props[2]:.2f}") st.write(f"- Toxicity: {props[3]:.2f}") except Exception as e: st.error(f"Error during optimization: {str(e)}") else: st.warning("Please select at least one molecule to optimize") # Display optimization results if molecules were selected if st.session_state.selected_molecules: st.write("### Optimization Results") st.write("Selected molecules for optimization:") # Create a grid layout for the results result_cols = st.columns(2) for idx, mol in enumerate(st.session_state.selected_molecules): with result_cols[idx % 2]: st.write(f"**Molecule {idx + 1}**") mol_obj = Chem.MolFromSmiles(mol['smiles']) if mol_obj: img = Draw.MolToImage(mol_obj) st.image(img, caption=f"Structure of Molecule {idx + 1}") st.write(f"Properties:") st.write(f"- Molecular Weight: {mol['mol_weight']:.2f}") st.write(f"- LogP: {mol['logP']:.2f}") st.write(f"- SMILES: `{mol['smiles']}`") sample_data = [ {'smiles': 'C1CC2=C(C=CC(=C2C1)N(C)C)C3=CC=CC=C3', 'mol_weight': 237.151749608, 'logP': 3.9083000000000023}, {'smiles': 'C1=CC=C(C=C1)C2CCN(CC2)C3=CC=CC=C3', 'mol_weight': 237.151749608, 'logP': 4.070600000000003}, {'smiles': 'C1CCN(CC1)C2=CC=C(C=C2)N3CCN(CC3)C4=CC=CC=C4', 'mol_weight': 321.22049786400004, 'logP': 4.003500000000003}, {'smiles': 'C1=CC=C(C=C1)C2=CC=C(C=C2)N3C(C4=CC=CC=C4)CCN(C3)CC(=O)N5CCN(CC5)C6=CC=CC=C6', 'mol_weight': 516.288911772, 'logP': 5.9133000000000076} ] # Footer st.sidebar.markdown("---") st.sidebar.markdown("### About") st.sidebar.info( """ This is a medical research assistant powered by AI developed by Hussain. It helps analyze medical data, research papers, accelerate drug discovery and generate insights. Strictly for research purposes only - not for medical diagnosis. """ ) # Add logout functionality def logout(): st.session_state["password_correct"] = False # Run the application with authentication if __name__ == "__main__": if check_password(): # Add logout button to sidebar st.sidebar.button("Logout", on_click=logout) main()