EPIC-AMP / index.html
nonzeroexit's picture
Update index.html
1a49717 verified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>EPIC-AMP</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="icon" type="image/png" href="favicon.png">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.23/jspdf.plugin.autotable.min.js"></script>
<style>
:root {
--primary-color: #004d40; /* Dark Teal */
--secondary-color: #00897b; /* Teal */
--success-color: #4caf50; /* Green */
--warning-color: #ff9800; /* Orange */
--info-color: #2196f3; /* Blue */
--background-color: #f0f4c3; /* Light Lime */
--text-color: #333; /* Dark Gray */
--container-bg-color: #ffffff; /* White */
--border-color: #bdbdbd; /* Light Gray */
--button-hover-bg: #00695c; /* Darker Teal */
--clear-button-bg: #f44336; /* Red */
--clear-button-hover-bg: #d32f2f; /* Darker Red */
--analyze-button-bg: #00897b; /* Teal */
--analyze-button-hover-bg: #00695c; /* Darker Teal */
}
/* Optional Dark Mode */
.dark-mode {
--primary-color: #b2dfdb; /* Light Teal */
--secondary-color: #4db6ac; /* Medium Teal */
--success-color: #81c784; /* Light Green */
--warning-color: #ffcc80; /* Light Orange */
--info-color: #90caf9; /* Light Blue */
--background-color: #212121; /* Dark Gray */
--text-color: #eee; /* Light Gray */
--container-bg-color: #424242;/* Darker Gray */
--border-color: #616161; /* Medium Gray */
--button-hover-bg: #004d40; /* Dark Teal */
--clear-button-bg: #e57373; /* Light Red */
--clear-button-hover-bg: #f44336; /* Red */
--analyze-button-bg: #4db6ac; /* Medium Teal */
--analyze-button-hover-bg: #009688; /* Teal */
}
body {
font-family: 'Arial', sans-serif;
line-height: 1.6;
margin: 0;
padding: 20px;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
background-color: var(--background-color);
color: var(--text-color);
transition: background-color 0.3s ease, color 0.3s ease;
}
.container {
max-width: 800px;
width: 100%;
padding: 2rem;
background: var(--container-bg-color);
border-radius: 10px;
box-shadow: 0 2px 15px rgba(0,0,0,0.1);
text-align: center;
transition: background-color 0.3s ease;
display: flex;
flex-direction: column;
margin-bottom: 20px;
}
.input-group {
margin-bottom: 1.5rem;
position: relative;
}
#sequence {
width: 100%;
height: 150px;
padding: 1rem;
border: 2px solid var(--border-color);
border-radius: 8px;
font-family: monospace;
font-size: 1rem;
resize: vertical;
transition: border-color 0.3s ease, background-color 0.3s ease;
background-color: var(--container-bg-color);
color: var(--text-color);
box-sizing: border-box;
}
#file-input {
margin-bottom: 1rem;
}
#sequence:focus {
outline: none;
border-color: var(--secondary-color);
}
button {
color: white;
border: none;
padding: 0.8rem 2rem;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
transition: transform 0.2s ease, background-color 0.3s ease;
/* margin-top: 1rem; Removed individual margin-top for buttons */
}
.button-group button{
margin: 0 0.2rem;
}
button:hover {
transform: translateY(-1px);
}
#clear-btn {
background-color: var(--clear-button-bg);
}
#clear-btn:hover {
background-color: var(--clear-button-hover-bg);
}
#predict-btn {
background-color: var(--analyze-button-bg);
min-width: 230px; /* To accommodate count-up text better */
}
#predict-btn:hover {
background-color: var(--analyze-button-hover-bg);
}
.character-count {
text-align: right;
color: var(--text-color);
font-size: 0.9rem;
margin-top: 0.5rem;
}
.error-message {
color: var(--warning-color);
text-align: center;
margin-top: 1rem;
display: none;
}
.result {
margin-top: 1.5rem;
font-size: 1.2rem;
font-weight: bold;
color: var(--primary-color);
text-align: center;
}
.info-icon {
position: absolute;
top: 1rem;
right: 1rem;
font-size: 1.2rem;
color: var(--info-color);
cursor: pointer;
}
.tooltip {
position: absolute;
top: 100%;
right: 0;
background-color: rgba(0, 0, 0, 0.8);
color: white;
padding: 0.5rem;
border-radius: 5px;
display: none;
z-index: 10;
width: 250px;
text-align: left;
font-size: 0.9rem;
line-height: 1.4;
}
.info-icon:hover + .tooltip,
.tooltip:hover {
display: block;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); }
}
.result.show {
animation: fadeIn 0.5s ease forwards;
}
.tabs {
display: flex;
justify-content: center;
margin-bottom: 1rem;
border-bottom: 2px solid var(--border-color);
}
.tab {
padding: 0.5rem 1rem;
margin: 0 0.5rem;
cursor: pointer;
border: 2px solid transparent;
border-radius: 5px 5px 0 0;
background-color: transparent;
color: var(--text-color);
transition: border-color 0.3s ease, background-color 0.3s ease;
display: flex;
align-items: center;
gap: 0.5rem;
}
.tab.active {
border-color: var(--primary-color);
background-color: var(--primary-color);
color: white;
}
.tab-content {
display: none;
padding: 1rem;
text-align: left;
}
.tab-content.active {
display: block;
}
.metrics-table {
width: 100%;
border-collapse: collapse;
margin-top: 1rem;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.metrics-table th, .metrics-table td {
padding: 0.5rem;
border: 1px solid var(--border-color);
text-align: center;
}
.metrics-table th {
background-color: var(--primary-color);
color: white;
font-weight: bold;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.metrics-table td {
padding: 0.8rem 0.5rem;
}
.metrics-table tr:nth-child(even) {
background-color: #f9f9f9;
}
.dark-mode .metrics-table tr:nth-child(even) {
background-color: #555;
}
.logos-container {
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 1rem;
width: 100%;
}
.logos-container img {
transform: scale(1.083);
max-width: 100%;
height: auto;
}
footer {
width: 100%;
padding: 20px;
background-color: var(--container-bg-color);
border-top: 1px solid var(--border-color);
font-size: 0.9rem;
color: var(--text-color);
text-align: center;
box-sizing: border-box;
position: relative;
left: 0;
right: 0;
margin: 0;
width: 100vw;
margin-left: calc(-100vw / 2 + 50%);
margin-right: calc(-100vw / 2 + 50%);
white-space: normal;
overflow-wrap: break-word;
}
footer p, footer address {
margin: 0.5rem 0;
white-space: normal;
overflow-wrap: break-word;
}
.button-group-wrapper { /* New wrapper for buttons and the time info */
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
margin-top: 1rem; /* Spacing for the wrapper itself */
}
#processing-time-info {
font-size: 0.9em;
color: var(--text-color);
margin-bottom: 0.75rem; /* Space between this info and the buttons */
}
.dark-mode #processing-time-info {
color: var(--text-color); /* Ensure dark mode text color is applied */
}
.button-group {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
}
#download-link {
color: var(--secondary-color);
text-decoration: none;
font-weight: bold;
display: block;
margin: 10px auto;
text-align: center;
}
#download-link:hover{
text-decoration: underline;
}
.tab-content h2 {
color: var(--primary-color);
margin-bottom: 0.5rem;
border-bottom: 2px solid var(--secondary-color);
padding-bottom: 0.25rem;
display: inline-block;
}
.tab-content h3 {
color: var(--secondary-color);
margin-top: 1.5rem;
margin-bottom: 0.5rem;
}
.tab-content ul {
list-style: disc;
margin-left: 20px;
padding-left: 0;
}
.tab-content li {
margin-bottom: 0.25rem;
}
.tab-content p {
margin-bottom: 1rem;
line-height: 1.7;
}
#shap-plot-container {
width: 100%;
min-height: 300px;
border: 1px solid var(--border-color);
border-radius: 5px;
margin-top: 1rem;
display: flex;
justify-content: center;
align-items: center;
overflow-x: auto;
}
#shap-plot-container img{
max-width: 100%;
height: auto;
display: block;
}
.results-display-group {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
margin-top: 2rem;
}
.result-box {
border: 1px solid var(--border-color);
border-radius: 8px;
background-color: var(--container-bg-color);
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
overflow: hidden;
color: var(--text-color);
}
.dark-mode .result-box {
background-color: #424242;
border-color: #616161;
}
.result-header {
background-color: var(--primary-color);
color: white;
padding: 0.7rem 1rem;
font-weight: bold;
font-size: 1.1rem;
display: flex;
align-items: center;
gap: 0.8rem;
}
.result-content {
padding: 1rem;
min-height: 50px;
display: flex;
flex-direction: column;
justify-content: center;
text-align: left;
}
.result-content p.info-message {
text-align: center;
margin-bottom: 0;
margin-top: 0;
}
.result-content ul {
margin: 0.5rem 0 0 1.5rem;
padding: 0;
list-style: disc;
}
.result-content ul li {
margin-bottom: 0.25rem;
}
.result-content h4 {
color: var(--secondary-color);
margin-top: 0.5rem;
margin-bottom: 0.5rem;
}
.scrollable-content {
max-height: 400px;
overflow-y: auto;
padding: 1rem;
border: 1px solid var(--border-color);
border-radius: 8px;
margin-top: 1rem;
background-color: var(--background-color);
}
.dark-mode .scrollable-content {
background-color: #333;
border-color: #616161;
}
.scrollable-content h4 {
color: var(--secondary-color);
margin-top: 1rem;
margin-bottom: 0.5rem;
}
.mic-checkbox-group {
margin-top: 1.5rem;
padding: 1rem;
border: 1px solid var(--border-color);
border-radius: 8px;
background-color: var(--container-bg-color);
box-shadow: 0 1px 5px rgba(0,0,0,0.05);
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 15px;
margin-bottom: 1.5rem;
}
.dark-mode .mic-checkbox-group {
background-color: #424242;
border-color: #616161;
}
.mic-checkbox-container {
display: flex;
align-items: center;
cursor: pointer;
font-size: 1rem;
color: var(--text-color);
user-select: none;
}
.mic-checkbox-container input[type="checkbox"] {
appearance: none;
-webkit-appearance: none;
width: 20px;
height: 20px;
border: 2px solid var(--primary-color);
border-radius: 4px;
margin-right: 8px;
cursor: pointer;
position: relative;
outline: none;
transition: all 0.2s ease-in-out;
}
.mic-checkbox-container input[type="checkbox"]:checked {
background-color: var(--primary-color);
border-color: var(--primary-color);
}
.mic-checkbox-container input[type="checkbox"]:checked::before {
content: '\2713';
display: block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 14px;
color: white;
}
.mic-checkbox-container .mic-label {
margin-left: 5px;
font-weight: normal;
}
/* Email-related CSS */
#user-email-input-group {
margin-top: 1.5rem;
margin-bottom: 1rem;
}
#user-email {
width: 100%;
padding: 0.7rem;
border: 1px solid var(--border-color);
border-radius: 5px;
box-sizing: border-box;
font-size: 1rem;
color: var(--text-color);
background-color: var(--container-bg-color);
}
#user-email:focus {
outline: none;
border-color: var(--secondary-color);
}
#email-status {
text-align: left;
font-size: 0.9rem;
margin-top: 0.3rem;
min-height: 1.2em;
}
#email-error { /* CSS for the email error div */
color: var(--clear-button-bg); /* Red for errors */
text-align: left;
font-size: 0.9rem;
margin-top: 0.3rem;
display: none; /* Initially hidden */
}
@media (max-width: 768px) {
body {
padding: 10px;
}
.results-display-group {
grid-template-columns: 1fr;
}
footer {
padding-left: 10px;
padding-right: 10px;
margin-left: calc(-50vw + 50%);
margin-right: calc(-50vw / 2 + 50%);
}
}
.team-member-list {
list-style: none;
padding: 0;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 15px;
}
.team-member-list li {
display: flex;
align-items: center;
gap: 15px;
font-size: 1.1rem;
color: var(--text-color);
background-color: var(--background-color);
padding: 10px 15px;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0,0,0,0.08);
width: 100%;
box-sizing: border-box;
}
.dark-mode .team-member-list li {
background-color: #333;
box-shadow: 0 1px 3px rgba(255,255,255,0.08);
}
.team-member-list img {
width: 60px;
height: 60px;
border-radius: 50%;
object-fit: cover;
border: 2px solid var(--secondary-color);
flex-shrink: 0;
}
</style>
</head>
<body>
<div class="container">
<div class="logos-container">
<img src="image2.png" alt="Tool Logo">
</div>
<div class="tabs">
<div class="tab active" data-tab="prediction">
<i class="fas fa-search"></i> Prediction
</div>
<div class="tab" data-tab="model">
<i class="fas fa-chart-line"></i> Models' Metrics & Sample run
</div>
<div class="tab" data-tab="about">
<i class="fas fa-info-circle"></i> About
</div>
<div class="tab" data-tab="usage">
<i class="fas fa-book"></i> Usage Guide
</div>
</div>
<div class="tab-content active" id="prediction">
<h2>AMP & MIC Predictor</h2>
<p>Enter an amino acid sequence (between 10 and 100 valid amino acids) or upload a FASTA file to predict AMP class and MIC values.</p>
<div class="input-group">
<input type="file" id="file-input" accept=".fasta,.fa,.fna">
<textarea id="sequence" placeholder="Enter amino acid sequence (10-100 Valid AAs) or upload a FASTA file..." maxlength="100"></textarea>
<div class="character-count">
<span id="char-count">0</span>/100
</div>
<i class="info-icon" id="info-icon"></i>
<div class="tooltip">
Enter the amino acid sequence you want to classify or upload a FASTA file. The sequence must be between 10 and 100 characters long and contain only standard amino acid characters (ACDEFGHIKLMNPQRSTVWY).
</div>
</div>
<h3 style="margin-top: 0rem; margin-bottom: 0.5rem;">Select Bacteria for MIC Prediction</h3>
<p style="margin-top: 0; margin-bottom: 1rem;">Choose one or more bacteria for which you'd like to predict the Minimum Inhibitory Concentration (MIC) of the peptide. MIC prediction is only performed if the sequence is classified as an Antimicrobial Peptide (AMP).</p>
<div class="mic-checkbox-group">
<label class="mic-checkbox-container">
<input type="checkbox" id="mic-ecoli" value="e_coli" disabled>
<span class="mic-label">E.coli</span>
</label>
<label class="mic-checkbox-container">
<input type="checkbox" id="mic-paeruginosa" value="p_aeruginosa" disabled>
<span class="mic-label">P. aeruginosa</span>
</label>
<label class="mic-checkbox-container">
<input type="checkbox" id="mic-saureus" value="s_aureus" disabled>
<span class="mic-label">S. aureus</span>
</label>
<label class="mic-checkbox-container">
<input type="checkbox" id="mic-kpneumoniae" value="k_pneumoniae" disabled>
<span class="mic-label">K. pneumoniae</span>
</label>
</div>
<!-- Start of Email Input Section -->
<div class="input-group" id="user-email-input-group" style="margin-top: 1.5rem; margin-bottom: 1rem;">
<label for="user-email" style="display:block; text-align:left; margin-bottom:0.5rem; font-weight:bold;">Please enter your Email Address for detailed results:<span style="color:red;">*</span></label>
<input type="email" id="user-email" placeholder="Enter your email to receive the PDF report" required>
<div id="email-error" class="error-message" style="text-align:left; font-size:0.9rem; margin-top:0.3rem; display:none;"></div>
<div id="email-status" style="text-align:left; font-size:0.9rem; margin-top:0.3rem; min-height: 1.2em;"></div>
</div>
<!-- End of Email Input Section -->
<!-- Wrapper for estimated time and buttons -->
<div class="button-group-wrapper">
<div id="processing-time-info">Estimated processing time: around 30 seconds.</div>
<div class="button-group">
<button id="clear-btn">Clear Input</button> <!-- NO onclick attribute here -->
<button id="predict-btn">Submit</button> <!-- NO onclick attribute here -->
</div>
</div>
<div class="error-message" id="error"></div>
<div class="results-display-group">
<div class="result-box">
<div class="result-header"><i class="fas fa-file-alt"></i>Classification</div>
<div class="result-content" id="amp-classification-output">
<p class="info-message">The prediction will appear here.</p>
</div>
</div>
<div class="result-box">
<div class="result-header"><i class="fas fa-info-circle"></i> Additional Details</div>
<div class="result-content" id="additional-details-output">
<p class="info-message">The detailed report will appear here.</p>
<a id="download-link" style="display: none;">Download Detailed Report (PDF)</a>
</div>
</div>
</div>
</div>
<div class="tab-content" id="model">
<h2>Classifier Metrics</h2>
<p>The following table presents the performance metrics of our antimicrobial peptide classification model. These metrics were obtained on a held-out test set, separate from the training data.</p>
<table class="metrics-table">
<thead>
<tr>
<th>Metric</th>
<th>Value</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Accuracy</td>
<td>0.963</td>
<td>The overall correctness of the model, representing the proportion of correctly classified sequences (both AMP and Non-AMP).</td>
</tr>
<tr>
<td>Precision</td>
<td>0.964</td>
<td>Out of all sequences predicted as AMPs, the proportion that are truly AMPs. A high precision indicates fewer false positives.</td>
</tr>
<tr>
<td>Recall</td>
<td>0.963</td>
<td>Out of all actual AMP sequences, the proportion that the model correctly identifies. A high recall indicates fewer false negatives.</td>
</tr>
<tr>
<td>F1-Score</td>
<td>0.963</td>
<td>The harmonic mean of precision and recall, providing a balanced measure of the model's performance.</td>
</tr>
<tr>
<td>Validation Accuracy</td>
<td>0.968</td>
<td>The accuracy of the model on a separate validation dataset, used during model development to tune hyperparameters.</td>
</tr>
</tbody>
</table>
<h2 style="margin-top: 2rem;">Regressor Metrics (MIC Prediction Models)</h2>
<p>The Minimum Inhibitory Concentration (MIC) prediction is handled by separate regressor models. Their performance metrics for each bacterium are detailed below:</p>
<table class="metrics-table">
<thead>
<tr>
<th>Bacterium</th>
<th>MSE (log)</th>
<th>MSE</th>
<th>R2</th>
<th>MAE</th>
<th>Pearson</th>
<th>Kendall</th>
</tr>
</thead>
<tbody>
<tr>
<td>E.coli</td>
<td>0.0481</td>
<td>0.4864</td>
<td>0.7023</td>
<td>0.1375</td>
<td>0.8394</td>
<td>0.6725</td>
</tr>
<tr>
<td>P. aeruginosa</td>
<td>0.0517</td>
<td>0.5227</td>
<td>0.6864</td>
<td>0.1233</td>
<td>0.8311</td>
<td>0.6922</td>
</tr>
<tr>
<td>S.aureus</td>
<td>0.0517</td>
<td>0.4988</td>
<td>0.6828</td>
<td>0.1472</td>
<td>0.8278</td>
<td>0.6536</td>
</tr>
<tr>
<td>K. pneumoniae</td>
<td>0.0538</td>
<td>0.4292</td>
<td>0.7416</td>
<td>0.1479</td>
<td>0.8693</td>
<td>0.7194</td>
</tr>
</tbody>
</table>
<h2 style="margin-top: 2rem;">Model Interpretability</h2>
<p>To understand how our model makes predictions, we use SHAP (SHapley Additive exPlanations) values globally and LIME (Local Interpretable Model-agnostic Explanations) locally. SHAP values help assess the overall contribution of each feature to model predictions across the dataset, while LIME explains the features influencing a single, specific prediction.</p>
<h3>Global SHAP Plot</h3>
<p>The SHAP plot below visualizes the features that most significantly influence the model's predictions *on average across all data*. Positive SHAP values generally contribute to the sequence being classified as AMP, while negative values contribute to Non-AMP classification.</p>
<div id="shap-plot-container">
<img src="shap.png" alt="SHAP Plot" >
</div>
<h3>Interpretation of Global SHAP Plot</h3>
<div class="scrollable-content">
<p>Based on the SHAP plot, the model's predictions for Antimicrobial Peptides (AMPs) are influenced by a combination of sequence-based, structural, and biophysical features. Here’s a breakdown of the key features and their biological implications:</p>
<h4>A. Sequence-Based Features</h4>
<h5>APAAC13 & APAAC5 (Amphiphilic Pseudo-Amino Acid Composition)</h5>
<ul>
<li><strong>Description:</strong> These features encode hydrophobicity, charge, and side-chain properties, reflecting the amphiphilic nature of the peptide.</li>
<li><strong>Interpretation:<b> Higher APAAC values have a positive SHAP impact, indicating they are predictive of AMP activity. This suggests that the model values amphiphilic sequences, which are crucial for disrupting bacterial membranes.</b></strong></li>
</ul>
<h5>Amino Acid Composition (M, C)</h5>
<ul>
<li><strong>M (Methionine):</strong>
<ul>
<li><strong>Description:</strong> Methionine is often associated with structural stability in peptides.</li>
<li><strong>Interpretation:</strong> The plot suggests Methionine content has a positive influence, possibly contributing to the stability of AMP candidates.</li>
</ul>
</li>
<li><strong>C (Cysteine):</strong>
<ul>
<li><strong>Description:</strong> Cysteine is known for forming disulfide bonds, which can stabilize AMP structures like defensins.</li>
<li><strong>Interpretation:</strong> High cysteine content appears to have a positive SHAP impact. This could be because disulfide-stabilized AMPs often exhibit enhanced antimicrobial action.</li>
</ul>
</li>
</ul>
<h4>B. Structural and Biophysical Features</h4>
<ul>
<li><strong>HydrophobicityD3001:</strong>
<ul>
<li><strong>Description:<b> Represents the overall hydrophobicity of the peptide sequence.</b></strong></li>
<li><strong>Interpretation:</strong> Hydrophobicity is shown to be a critical feature. More hydrophobic peptides are strongly favored for AMP classification, aligning with the understanding that hydrophobicity is essential for membrane insertion and disruption.</li>
</ul>
</li>
<li><strong>PolarityD1001:</strong>
<ul>
<li><strong>Description:<b> Measures the polarity of the peptide sequence.</b></strong></li>
<li><strong>Interpretation:</b> The model considers polarity, likely in balance with hydrophobicity. An optimal AMP efficacy is often linked to having both hydrophobic and polar residues to facilitate membrane interaction and solubility.</li>
</ul>
</li>
<li><strong>Solvent Accessibility (SolventAccessibilityD3001):</strong>
<ul>
<li><strong>Description:</b> Reflects how exposed the residues are to the solvent (water).</li>
<li><strong>Interpretation:</b> Solvent-accessible residues positively contribute to AMP prediction. This might indicate that exposed residues facilitate interaction with bacterial membranes or the surrounding environment.</li>
</ul>
</li>
<li><strong>Charge (ChargeD2001):</strong>
<ul>
<li><strong>Description:<b> Represents the net charge of the peptide.</b></strong></li>
<li><strong>Interpretation:</b> Charge is a significant positive predictor. Most AMPs are cationic, enabling them to interact with negatively charged bacterial membranes. Higher charge, as indicated by positive SHAP values, typically enhances antimicrobial potency.</li>
</ul>
</li>
<li><strong>PolarizabilityD3001 & NormalizedVDWVD3001:<b>
<ul>
<li><strong>Description:<b> These features relate to electronic distribution (Polarizability) and steric effects (NormalizedVDWVD) of the peptide.</b></strong></li>
<li><strong>Interpretation:</b> These properties impact membrane penetration and peptide-membrane interactions. Their positive SHAP values suggest they are important for AMP activity, possibly by influencing how the peptide inserts into and destabilizes membranes.</li>
</ul>
</li>
</ul>
<h4>C. Geary Autocorrelation Features</h4>
<p>Geary autocorrelation descriptors reflect spatial properties of peptides, encoding information about the adhesion and distribution of physicochemical properties along the sequence.</p>
<ul>
<li><strong>GearyAuto_Hydrophobicity30:</strong>
<ul>
<li><strong>Description:</strong> Encodes the clustering of hydrophobic residues within a spatial lag of 30.</li>
<li><strong>Interpretation:<b> Higher values of hydrophobicity autocorrelation are positively associated with AMP prediction. This likely reflects the importance of hydrophobic clustering in forming amphipathic structures, such as α-helices, which are common and effective in AMPs.</b></b></li>
</ul>
</li>
<li><strong>GearyAuto_Steric30 & GearyAuto_Steric29:</strong>
<ul>
<li><strong>Description:</b> Reflect peptide backbone flexibility and steric properties at spatial lags of 30 and 29.</li>
<li><strong>Interpretation:</b> These features have a positive SHAP impact, suggesting that a certain degree of peptide backbone flexibility may be beneficial for AMP action. Flexibility could enhance the peptide's ability to interact with and adapt to diverse bacterial membrane structures.</li>
</ul>
</li>
<li><strong>GearyAuto_ResidueASA30:<b>
<ul>
<li><strong>Description:</strong> Indicates the autocorrelation of accessible surface area of residues at a spatial lag of 30.</li>
<li><strong>Interpretation:<b> Higher autocorrelation of residue accessible surface area is favored. This could mean that a consistent pattern of residue exposure, possibly with higher exposure of charged or polar residues, improves bacterial targeting or membrane interaction.</b></b></li>
</ul>
</li>
</ul>
</div>
<h3>Sample Run</h3>
<p>You can test the model with various sequences to understand its behavior. Here are a few examples:</p>
<ul>
<li><strong>Test 1:</strong> Long Sequence of 99 AAs (P-AMP) - MEKAALIFIGLLLFSTCTQILAQSCNNDSDCTNLKCATKNIKCEQNKCQCLDERYIRA
ISLNTRSPRCNVQSCIDHCKAIGEVIYVCFTYHCYCRKPPM</li>
<li><strong>Test 2:</strong> Long Sequence of 99 AAs (Non-AMP) - MKSLLPLAILAALAVAALCYESHESMESYEVSPFTTRRNANTFISPQQRWHAK
AQERVRELNKPAQEINREACDDYKLCERYALIYGYNAAYNRYFRQR</li>
<li><strong>Test 3:</strong> Short Sequence of 51 AAs (P-AMP) - SLQGGAPNFPQPSQQNGGWQVSPDLGRDDKGNTRGQIEIQNKGKDHDFNAG</li>
<li><strong>Test 4:<b> Short Sequence of 50 AAs (Non-AMP) - MKPLKQKVSITLDEDVIKNLKTLAEECDRSLSQYINLILKEHLKNLDQQ</b></b></li>
<li><strong>Test 5:</strong> Invalid Characters (eg. X) -
MEKAALIFIGLLLFSTCTQILAQSC(XX).</li>
</ul>
</div>
<div class="tab-content" id="about">
<h2>About This Tool</h2>
<p>This web application provides a user-friendly interface for classifying amino acid sequences as either Antimicrobial Peptides (AMPs) or Non-Antimicrobial Peptides (Non-AMPs). AMPs are crucial components of the innate immune system, offering defense against a wide range of pathogens.</p>
<h3>Model Selection Criteria</h3>
<p>To identify the most effective model, our team rigorously evaluated over 225 combinations of feature extraction and selection methods across four different machine learning models for each target organism. The evaluation included both classification and regression tasks, with a focus on predicting antimicrobial activity and estimating minimum inhibitory concentration (MIC) values. The final model was selected based on the following criteria:</p>
<ul>
<li><strong>High Accuracy, F1-score, and Validation Accuracy:</strong> The model achieved excellent performance metrics on a held-out test set, demonstrating its ability to generalize to unseen data.</li>
<li><strong>Robustness to Sequence Length Variations:<b> The model performs consistently well on sequences of varying lengths, within the specified range (10-100 amino acids).</b></strong></li>
<li><strong>Generalization Ability:</strong> The model was trained and evaluated on diverse datasets to ensure its ability to classify a broad range of AMP sequences.</li>
<li><strong>Robust regression capability:<b> Assessed using Mean Squared Error (MSE), R-squared (R²), Pearson correlation, and Kendall’s tau, the model demonstrated strong agreement between predicted and true MIC values.</b></b></li>
</ul>
<h3>Intended Use</h3>
<p>This tool is intended for research and educational purposes. It can be a valuable resource for researchers studying antimicrobial peptides and developing new therapeutic strategies. However, it is not a replacement for laboratory-based experimental validation.</p>
<h3>Our Team</h3>
<ul class="team-member-list">
<li><img src="team-member-1.jpg" alt="Ali Magdi"> Ali Magdi - Computational Biologist</li>
<li><img src="team-member-2.jpg" alt="Ahmed Amr"> Ahmed Amr - Computational Biologist</li>
<li><img src="team-member-3.jpg" alt="Omar Loay"> Omar Loay - Molecular Biologist</li>
<li><img src="team-member-4.jpg" alt="Prof. Eman Badr"> Prof. Eman Badr - Full Professor and Director of BCBU</li>
</ul>
<h3>Acknowledgements</h3>
<p>We extend our gratitude to the following organizations for their support:</p>
<ul>
<li>Bioinformatics and Computational Biology Unit at Zewail City.</li>
<li>The Centre for Genomics at Zewail City.</li>
</ul>
<h3>Contact</h3>
<p>For questions, inquiries, or feedback, please reach out to us at: <a href="mailto:[email protected]">[email protected]</a></p>
</div>
<div class="tab-content" id="usage">
<h2>Usage Guide</h2>
<p>Follow these steps to use the AMP Classifier and Regressors:</p>
<h3>Step 1: Prepare Your Sequence</h3>
<ul>
<li>You can either enter the amino acid sequence directly or upload a FASTA file.</li>
<li>Ensure your sequence contains only standard amino acid characters (ACDEFGHIKLMNPQRSTVWY).</li>
<li>The sequence length must be between 10 and 100 amino acids.</li>
</ul>
<h3>Step 2: Input the Sequence</h3>
<ul>
<li><strong>Direct Input:</strong> Type or paste your sequence into the text area provided.</li>
<li><strong>FASTA File Upload:<b> Click the "Choose File" button and select your .fasta, .fa, or .fna file.</b></b></li>
<li>The character count will update as you type or upload a sequence.</li>
</ul>
<h3>Step 3: Analyze the Sequence</h3>
<ul>
<li>Click the "Submit" button.</li>
<li>A message indicating the estimated processing time will be visible above the buttons, and the button itself will show elapsed time.</li>
</ul>
<h3>Step 4: View the Results</h3>
<ul>
<li>Once the analysis is complete, the prediction (AMP or Non-AMP) will be displayed in the "AMP Classification" box.</li>
<li>A link to "Download Detailed Report (PDF)" will appear in the "Additional Details" box if the report was generated successfully.</li>
</ul>
<h3>Step 5: Clear the Input</h3>
<ul>
<li>To analyze another sequence, click the "Clear Input" button. This will reset the input fields and results.</li>
</ul>
<h3>Troubleshooting</h3>
<ul>
<li><strong>Invalid Characters:</b> If you see an error message about invalid characters, double-check that your sequence contains only standard amino acid characters.</li>
<li><strong>Sequence Length:</strong> Ensure your sequence is between 10 and 100 characters long.</li>
<li><strong>Invalid FASTA Format:<b> If you encounter an error with a FASTA file, make sure the file is correctly formatted.</b></b></li>
</ul>
</div>
</div>
<footer>
<p>© 2025, Bioinformatics and Computational biology Unit, BCBU</p>
<address>
Bioinformatics and Computational biology Unit at Zewail City,<br>
Ahmed Zewail Street, October Gardens, Giza,<br>
Egypt
</address>
</footer>
<script type="module">
import { Client } from "https://esm.sh/@gradio/client";
const GRADIO_HF_SPACE_RAW_URL = "https://huggingface.co/spaces/nonzeroexit/AMP-Classifier";
const GRADIO_PREDICTION_TARGET_ID = "nonzeroexit/AMP-Classifier";
// This Space ID is technically still used in initClient but won't be connected
// for email sending functionality due to being disabled.
const GRADIO_EMAIL_TARGET_ID = "nonzeroexit/amp-email-sender"; // Email backend reference (disabled)
// --- DOM Elements ---
const sequenceInput = document.getElementById('sequence');
const charCount = document.getElementById('char-count');
const errorDiv = document.getElementById('error');
const predictBtn = document.getElementById('predict-btn');
const clearBtn = document.getElementById('clear-btn');
const fileInput = document.getElementById('file-input');
const downloadLink = document.getElementById('download-link');
const ampClassificationOutput = document.getElementById('amp-classification-output');
const additionalDetailsOutput = document.getElementById('additional-details-output');
const micCheckboxes = document.querySelectorAll('.mic-checkbox-group input[type="checkbox"]');
const tabs = document.querySelectorAll('.tab');
const tabContents = document.querySelectorAll('.tab-content');
const userEmailInput = document.getElementById('user-email');
const emailErrorDiv = document.getElementById('email-error');
const emailStatusDiv = document.getElementById('email-status');
let clientInstancePrediction; // Only prediction client will be connected
let clientInstanceEmail = null; // Email client will NOT be connected (explicitly null)
let debounceTimer;
let countUpIntervalId;
// Flag to control email functionality globally
const IS_EMAIL_SENDING_ENABLED = false; // <<< SET TO false TO DISABLE EMAIL SENDING
// --- Utility Functions for Error Display (Defined at top of module scope) ---
function showError(message) {
if(errorDiv) {
errorDiv.textContent = message;
errorDiv.style.display = 'block';
}
}
function clearGeneralError() {
if(errorDiv) {
errorDiv.style.display = 'none';
errorDiv.textContent = '';
}
}
// --- Tab Switching Logic ---
tabs.forEach(tab => {
tab.addEventListener('click', () => {
tabs.forEach(t => t.classList.remove('active'));
tabContents.forEach(c => c.classList.remove('active'));
tab.classList.add('active');
document.getElementById(tab.dataset.tab).classList.add('active');
});
});
// --- Gradio Client Initialization ---
async function initClient() {
try {
// Attempt to connect to the prediction space
clientInstancePrediction = await Client.connect(GRADIO_PREDICTION_TARGET_ID);
console.log("Gradio client for prediction initialized successfully directly to space ID:", GRADIO_PREDICTION_TARGET_ID);
// ONLY CONNECT EMAIL CLIENT IF FEATURE IS ENABLED
if (IS_EMAIL_SENDING_ENABLED) {
clientInstanceEmail = await Client.connect(GRADIO_EMAIL_TARGET_ID);
console.log("Gradio client for email sender initialized successfully directly to space ID:", GRADIO_EMAIL_TARGET_ID);
} else {
console.log("Email sending functionality is disabled, skipping email client connection.");
}
updatePredictButtonState();
} catch (error) {
console.error("Failed to initialize Gradio client for prediction (or email if enabled):", error);
showError(`Failed to connect to a Hugging Face Space. This might be due to incorrect Space IDs, private spaces, or network issues. Error details: ${error.message}`);
// If prediction client fails, or if email is enabled and its client fails, disable the button.
if (predictBtn) predictBtn.disabled = true;
}
}
// --- Initial Setup on Window Load ---
window.onload = function() {
initClient();
if (document.getElementById('info-icon')) {
document.getElementById('info-icon').addEventListener('mouseenter', showTooltip);
document.getElementById('info-icon').addEventListener('mouseleave', hideTooltip);
}
if (fileInput) fileInput.addEventListener('change', handleFileSelect);
if (sequenceInput) {
sequenceInput.addEventListener('input', updateAllInputsAndButtonState);
sequenceInput.addEventListener('paste', handleSequencePaste);
sequenceInput.addEventListener('keypress', handleSequenceKeyPress);
}
// Email input listeners still active for user input and local visual validation
if (userEmailInput) {
userEmailInput.addEventListener('input', updateAllInputsAndButtonState);
}
// Attach event listeners to buttons
if (clearBtn) clearBtn.addEventListener('click', clearInput);
if (predictBtn) predictBtn.addEventListener('click', classifySequenceDebounced);
clearInput();
};
// --- Tooltip Functions ---
function showTooltip() {
const tooltip = document.querySelector('.tooltip');
if (tooltip) tooltip.style.display = 'block';
}
function hideTooltip() {
const tooltip = document.querySelector('.tooltip');
if (tooltip) tooltip.style.display = 'none';
}
// --- Clear Input Function ---
function clearInput() {
if(sequenceInput) sequenceInput.value = '';
if(fileInput) fileInput.value = '';
if(charCount) charCount.textContent = '0';
clearGeneralError();
// Clear email specific fields
if(userEmailInput) userEmailInput.value = '';
if(emailErrorDiv) emailErrorDiv.style.display = 'none';
if(emailStatusDiv) {
if (IS_EMAIL_SENDING_ENABLED) {
emailStatusDiv.textContent = '';
emailStatusDiv.style.color = 'var(--text-color)';
} else {
emailStatusDiv.textContent = 'Email sending is currently disabled by the tool.';
emailStatusDiv.style.color = 'var(--info-color)'; // Neutral info color
}
}
if(downloadLink) {
downloadLink.style.display = 'none';
downloadLink.href = '#';
downloadLink.innerHTML = 'Download Detailed Report (PDF)';
}
if(ampClassificationOutput) ampClassificationOutput.innerHTML = '<p class="info-message">The prediction will appear here.</p>';
if(additionalDetailsOutput) {
additionalDetailsOutput.innerHTML = '<p class="info-message">The detailed report will appear here.</p>';
if(downloadLink && !additionalDetailsOutput.contains(downloadLink)) {
additionalDetailsOutput.appendChild(downloadLink);
}
if(downloadLink) downloadLink.style.display = 'none';
}
if(micCheckboxes) micCheckboxes.forEach(checkbox => {
checkbox.checked = false;
checkbox.disabled = true;
});
if (countUpIntervalId) {
clearInterval(countUpIntervalId);
countUpIntervalId = null;
}
updatePredictButtonState();
if(predictBtn) predictBtn.textContent = 'Submit';
}
// --- File Handling ---
function handleFileSelect(event) {
const file = event.target.files[0];
if (!file) {
if (sequenceInput && sequenceInput.dataset.source === 'file') {
clearInput();
}
return;
}
const allowedExtensions = ['.fasta', '.fa', '.fna'];
const fileName = file.name.toLowerCase();
const isValidExtension = allowedExtensions.some(ext => fileName.endsWith(ext));
if (!isValidExtension) {
showError('Invalid file type. Please upload a .fasta, .fa, or .fna file.');
if(fileInput) fileInput.value = '';
if(micCheckboxes) micCheckboxes.forEach(checkbox => checkbox.disabled = true);
updatePredictButtonState();
return;
}
clearGeneralError();
// Clear email validation error, though it won't block submission
if(emailErrorDiv) emailErrorDiv.style.display = 'none';
const reader = new FileReader();
reader.onload = function(e) {
try {
const parsedSeq = parseFASTA(e.target.result);
if (parsedSeq) {
if(sequenceInput) {
sequenceInput.value = parsedSeq;
sequenceInput.dataset.source = 'file';
}
updateCharacterCount();
updateAllInputsAndButtonState();
} else {
showError("No valid sequence found in FASTA file.");
if(fileInput) fileInput.value = '';
if(sequenceInput) sequenceInput.dataset.source = '';
if(micCheckboxes) micCheckboxes.forEach(checkbox => checkbox.disabled = true);
updatePredictButtonState();
}
} catch (error) {
console.error("Error in FASTA parsing:", error);
showError(error.message || "Error processing FASTA file.");
if(fileInput) fileInput.value = '';
if(sequenceInput) sequenceInput.dataset.source = '';
if(micCheckboxes) micCheckboxes.forEach(checkbox => checkbox.disabled = true);
updatePredictButtonState();
}
};
reader.onerror = function(error) {
console.error("FileReader error:", error);
showError("Error reading file.");
if(fileInput) fileInput.value = '';
if(sequenceInput) sequenceInput.dataset.source = '';
if(micCheckboxes) micCheckboxes.forEach(checkbox => checkbox.disabled = true);
updatePredictButtonState();
};
reader.readAsText(file);
}
function parseFASTA(text) {
const lines = text.trim().split(/[\r\n]+/);
let sequenceData = '';
let headerFound = false;
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine.startsWith('>')) {
if (headerFound && sequenceData) { return sequenceData.toUpperCase(); }
headerFound = true; sequenceData = '';
} else if (headerFound) {
sequenceData += trimmedLine.replace(/\s/g, '');
} else if (!trimmedLine.startsWith('>') && trimmedLine.length > 0) {
sequenceData += trimmedLine.replace(/\s/g, '');
}
}
if (!headerFound && sequenceData) { console.warn("No FASTA header found."); }
else if (!sequenceData && headerFound) { throw new Error("FASTA header found but no sequence.");}
else if (!sequenceData && !headerFound && lines.some(l=>l.trim().length>0) && !lines.some(l=>l.trim().startsWith('>'))){
sequenceData = lines.join('').replace(/\s/g, '');
} else if (!sequenceData && !headerFound && lines.every(l=>l.trim().length === 0)) {
throw new Error("FASTA file is empty.");
}
if (sequenceData) { return sequenceData.toUpperCase(); }
else { throw new Error("No valid sequence found in FASTA."); }
}
// --- Validation Functions ---
function validateSequence(seqToValidate) {
const currentLength = seqToValidate.length;
if (!seqToValidate) {
return { isValid: false, message: "Sequence cannot be empty." };
} else if (/[^ACDEFGHIKLMNPQRSTVWY]/i.test(seqToValidate)) {
return { isValid: false, message: 'Invalid characters in sequence. Only standard amino acid characters (ACDEFGHIKLMNPQRSTVWY) are allowed.' };
} else if (currentLength < 10 || currentLength > 100) {
return { isValid: false, message: `Sequence length (${currentLength}) must be between 10 and 100 characters.` };
}
return { isValid: true, message: "" };
}
function validateEmail(email) {
// Email validation is now only for local display, not blocking submission
if (!email) {
return { isValid: false, message: "Email address is empty." };
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return { isValid: false, message: "Please enter a valid email format." };
}
return { isValid: true, message: "" };
}
// --- Update UI Functions ---
function updateCharacterCount() {
if(!sequenceInput || !charCount) return;
const currentLength = sequenceInput.value.length;
charCount.textContent = currentLength;
charCount.style.color = currentLength > 100 ? 'var(--warning-color)' : 'var(--text-color)';
}
function updateAllInputsAndButtonState() {
updateCharacterCount();
const sequenceValidation = validateSequence(sequenceInput ? sequenceInput.value : '');
const emailValidation = validateEmail(userEmailInput ? userEmailInput.value : '');
if (!sequenceValidation.isValid) {
showError(sequenceValidation.message);
} else {
clearGeneralError();
}
// Display email format errors locally, but don't clear prediction error message
if (!emailValidation.isValid && userEmailInput && userEmailInput.value.length > 0) {
if (emailErrorDiv) {
emailErrorDiv.textContent = emailValidation.message;
emailErrorDiv.style.display = 'block';
}
} else {
if (emailErrorDiv) emailErrorDiv.style.display = 'none';
}
// If email sending is disabled, provide a default status message.
if (emailStatusDiv) {
if (!IS_EMAIL_SENDING_ENABLED) {
emailStatusDiv.textContent = 'Email sending is currently disabled by the tool.';
emailStatusDiv.style.color = 'var(--info-color)';
} else if (userEmailInput && userEmailInput.value.trim() === '') {
// Clear previous status if user input cleared.
emailStatusDiv.textContent = '';
emailStatusDiv.style.color = 'var(--text-color)';
}
}
if(micCheckboxes) micCheckboxes.forEach(checkbox => {
checkbox.disabled = !sequenceValidation.isValid;
if (!sequenceValidation.isValid) checkbox.checked = false;
});
updatePredictButtonState(sequenceValidation.isValid); // Pass only sequence validity
}
function updatePredictButtonState(sequenceIsValid = false) {
if (predictBtn) {
// Button enabled solely on valid sequence input AND successful prediction client connection
predictBtn.disabled = !sequenceIsValid || !clientInstancePrediction;
}
}
// --- Sequence Input Event Handlers ---
function handleSequencePaste(e) {
e.preventDefault();
const paste = (e.clipboardData || window.clipboardData).getData('text');
const cleanPaste = paste.replace(/[\s\r\n]+/g, '').toUpperCase();
const selectionStart = sequenceInput.selectionStart;
const selectionEnd = sequenceInput.selectionEnd;
const currentText = sequenceInput.value;
let newText = currentText.substring(0, selectionStart) + cleanPaste + currentText.substring(selectionEnd);
if (newText.length > parseInt(sequenceInput.maxLength, 10)) {
newText = newText.substring(0, parseInt(sequenceInput.maxLength, 10));
}
sequenceInput.value = newText;
sequenceInput.dataset.source = 'manual';
updateAllInputsAndButtonState();
sequenceInput.selectionStart = sequenceInput.selectionEnd = selectionStart + cleanPaste.length;
}
function handleSequenceKeyPress(e) {
if (e.key.length > 1 || e.ctrlKey || e.metaKey || e.altKey) {
return;
}
if (!/^[ACDEFGHIKLMNPQRSTVWY]$/i.test(e.key)) {
e.preventDefault();
} else {
clearGeneralError();
}
}
// --- Main Prediction Logic ---
async function classifySequenceDebounced() {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(classifySequence, 300);
}
async function classifySequence() {
if (!clientInstancePrediction) {
showError("Classifier service is not ready. Please wait a moment and try again.");
console.error("Gradio client instance for prediction is not initialized when classifySequence called.");
updatePredictButtonState();
return;
}
const currentSequence = sequenceInput ? sequenceInput.value.trim().toUpperCase() : "";
const userEmail = userEmailInput ? userEmailInput.value.trim() : ""; // Still get email, but won't be used for sending
const sequenceValidation = validateSequence(currentSequence);
// const emailValidation = validateEmail(userEmail); // Email validation is now only for local display/info
if (!sequenceValidation.isValid) {
showError(sequenceValidation.message);
updatePredictButtonState();
return;
} else {
clearGeneralError();
}
// Remove email validation check that blocked submission
// if (!emailValidation.isValid && IS_EMAIL_SENDING_ENABLED) {
// if (emailErrorDiv) {
// emailErrorDiv.textContent = emailValidation.message;
// emailErrorDiv.style.display = 'block';
// }
// updatePredictButtonState();
// return;
// } else {
// if (emailErrorDiv) emailErrorDiv.style.display = 'none';
// }
if(emailStatusDiv) {
if (IS_EMAIL_SENDING_ENABLED) {
emailStatusDiv.textContent = '';
emailStatusDiv.style.color = 'var(--text-color)';
} else {
emailStatusDiv.textContent = 'Email sending is currently disabled by the tool.';
emailStatusDiv.style.color = 'var(--info-color)';
}
}
if (predictBtn) predictBtn.disabled = true;
if (ampClassificationOutput) ampClassificationOutput.innerHTML = '<p class="info-message">Analyzing...</p>';
if (additionalDetailsOutput) {
additionalDetailsOutput.innerHTML = '<p class="info-message">Generating detailed report...</p>';
if(downloadLink && !additionalDetailsOutput.contains(downloadLink)) {
additionalDetailsOutput.appendChild(downloadLink);
}
if(downloadLink) downloadLink.style.display = 'none';
}
if (micCheckboxes) micCheckboxes.forEach(checkbox => checkbox.disabled = true);
let secondsElapsed = 0;
if(predictBtn) predictBtn.textContent = `Processing... (${secondsElapsed}s elapsed)`;
if (countUpIntervalId) clearInterval(countUpIntervalId);
countUpIntervalId = setInterval(() => {
secondsElapsed++;
if(predictBtn) predictBtn.textContent = `Processing... (${secondsElapsed}s elapsed)`;
}, 1000);
let micDataForPdfFromPrediction = {};
let ampLabelFromPrediction = 'Unknown';
let ampConfidenceFromPrediction = 0;
let limeFeaturesForPdfFromPrediction = [];
try {
// Call the prediction space client
const classificationResult = await clientInstancePrediction.predict("/predict", [currentSequence]);
console.log("Gradio Result (Prediction):", classificationResult);
if (!classificationResult || !classificationResult.data || typeof classificationResult.data[0] !== 'string') {
throw new Error("Unexpected result format from prediction server.");
}
const rawTextOutput = classificationResult.data[0];
console.log("Raw text output from Gradio (Prediction):\n", rawTextOutput);
const lines = rawTextOutput.split('\n').map(line => line.trim()).filter(Boolean);
const labelRegex = /Prediction:\s*(.+)/i;
const confidenceRegex = /Confidence:\s*([\d.]+)%/i;
const micSectionHeaderRegex = /Predicted MIC Values \(μM\):/i;
const topFeaturesSectionHeaderRegex = /Top Features Influencing Prediction/i;
const micLineRegex = /-\s*([^:]+?):\s*((?:[\d.]+)|(?:Error:.*)|(?:N\/A)|(?:Could not process)|(?:Skipped))/i;
const featureExtractorRegex = /-\s*(.+?)\s*:\s*([+-]?[\d.]+)/i;
const labelMatch = rawTextOutput.match(labelRegex);
if (labelMatch && labelMatch[1]) ampLabelFromPrediction = labelMatch[1];
else console.warn("Could not parse AMP Label from output.");
const confidenceMatch = rawTextOutput.match(confidenceRegex);
if (confidenceMatch && confidenceMatch[1]) ampConfidenceFromPrediction = parseFloat(confidenceMatch[1]) / 100;
else console.warn("Could not parse Confidence from output.");
let currentSection = null;
micDataForPdfFromPrediction = {};
limeFeaturesForPdfFromPrediction = [];
for (const line of lines) {
if (micSectionHeaderRegex.test(line)) { currentSection = 'mic'; continue; }
if (topFeaturesSectionHeaderRegex.test(line)) { currentSection = 'lime_features'; continue; }
if (currentSection === 'mic') {
const micLineMatch = line.match(micLineRegex);
if (micLineMatch && micLineMatch[1] && micLineMatch[2]) {
const bacteriumDisplayName = micLineMatch[1].trim();
const micValueOrError = micLineMatch[2].trim();
micDataForPdfFromPrediction[bacteriumDisplayName] = !isNaN(parseFloat(micValueOrError)) ? parseFloat(micValueOrError) : micValueOrError;
}
} else if (currentSection === 'lime_features') {
const featureMatch = line.match(featureExtractorRegex);
if (featureMatch) {
const featureDescription = featureMatch[1].trim();
const featureValue = parseFloat(featureMatch[2]);
if (!isNaN(featureValue)) {
limeFeaturesForPdfFromPrediction.push({ feature: featureDescription, condition: '', value: featureValue });
} else { console.warn(`Could not parse LIME feature value from line: ${line}`); }
} else {
if (line.trim().length > 0 && !line.includes('---') && !line.toLowerCase().includes("influencing prediction")) {
console.warn(`Line not parsed as LIME feature: ${line}`);
}
}
}
}
// Attempt to generate PDF
let pdfDoc = null;
try {
pdfDoc = await generatePDFReportContent(currentSequence, ampLabelFromPrediction, ampConfidenceFromPrediction, micDataForPdfFromPrediction, limeFeaturesForPdfFromPrediction);
} catch (pdfGenerationError) {
console.error("Error during PDF report content generation:", pdfGenerationError);
showError(`PDF report generation failed: ${pdfGenerationError.message}`);
emailStatusDiv.textContent = 'PDF generation failed, email not sent (functionality disabled).';
emailStatusDiv.style.color = 'var(--clear-button-bg)';
pdfDoc = null; // Ensure pdfDoc is null on error
}
if(ampClassificationOutput) ampClassificationOutput.innerHTML = `<p style="font-size: 1.3rem; font-weight: bold; color: ${ampLabelFromPrediction.toLowerCase().includes('non-amp') ? 'var(--clear-button-bg)' : 'var(--success-color)'}; margin: 0; text-align: center;">${ampLabelFromPrediction}</p>`;
// Logic to handle download link based on PDF generation success
if (additionalDetailsOutput && downloadLink) {
if (pdfDoc) {
const pdfBlob = pdfDoc.output('blob');
const pdfUrl = URL.createObjectURL(pdfBlob);
const pdfFileName = `EPIC-AMP_Report_${currentSequence.substring(0, 10).replace(/[^a-zA-Z0-9]/g, '')}_${new Date().toISOString().slice(0, 10)}.pdf`;
downloadLink.href = pdfUrl;
downloadLink.download = pdfFileName;
downloadLink.innerHTML = `<i class="fas fa-download"></i> Download Report (PDF)`;
downloadLink.style.display = 'block';
additionalDetailsOutput.innerHTML = '<p class="info-message">Detailed report available:</p>';
if (!additionalDetailsOutput.contains(downloadLink)) {
additionalDetailsOutput.appendChild(downloadLink);
}
// --- Email logic based on IS_EMAIL_SENDING_ENABLED flag ---
if (IS_EMAIL_SENDING_ENABLED) {
await sendEmailWithReport(userEmail, pdfBlob, pdfFileName, currentSequence, ampLabelFromPrediction, ampConfidenceFromPrediction);
} else {
console.log("Email sending is disabled. Not attempting to send.");
if(emailStatusDiv) {
emailStatusDiv.textContent = 'Email report generation and sending are currently disabled by the tool.';
emailStatusDiv.style.color = 'var(--info-color)';
}
}
} else {
additionalDetailsOutput.innerHTML = '<p class="info-message" style="color: var(--warning-color);">Could not generate PDF report for download.</p>';
if (downloadLink.parentNode === additionalDetailsOutput) {
downloadLink.style.display = 'none';
}
emailStatusDiv.textContent = 'PDF report could not be generated, email not sent.';
emailStatusDiv.style.color = 'var(--clear-button-bg)';
}
}
if (ampLabelFromPrediction.toLowerCase().includes('amp') && !ampLabelFromPrediction.toLowerCase().includes('non-amp')) {
if(micCheckboxes) micCheckboxes.forEach(checkbox => checkbox.disabled = false);
} else {
if(micCheckboxes) micCheckboxes.forEach(checkbox => { checkbox.checked = false; checkbox.disabled = true; });
}
} catch (error) {
console.error("Error during prediction or processing:", error);
showError(`Prediction failed: ${error.message || "Unknown error."} Please check the Hugging Face Gradio Space for any issues or temporary downtime.`);
if(ampClassificationOutput) ampClassificationOutput.innerHTML = '<p style="text-align: center; color: var(--clear-button-bg);">Error in Prediction</p>';
if(additionalDetailsOutput) {
additionalDetailsOutput.innerHTML = '<p style="text-align: center; color: var(--clear-button-bg);">Detailed report not available (due to prediction error).</p>';
if(downloadLink) {
if(!additionalDetailsOutput.contains(downloadLink)) additionalDetailsOutput.appendChild(downloadLink);
downloadLink.style.display = 'none';
}
}
if (IS_EMAIL_SENDING_ENABLED) {
emailStatusDiv.textContent = `Email not sent due to prediction error: ${error.message}`;
} else {
emailStatusDiv.textContent = `Email sending is disabled. Prediction failed: ${error.message}`;
}
emailStatusDiv.style.color = 'var(--clear-button-bg)';
} finally {
if (countUpIntervalId) { clearInterval(countUpIntervalId); countUpIntervalId = null; }
if (predictBtn) { predictBtn.textContent = 'Submit';}
updatePredictButtonState(); // Ensure button is re-enabled/disabled based on final prediction input state
}
}
// --- Dummy Send Email Function (when disabled) / Original logic (when enabled) ---
async function sendEmailWithReport(email, pdfBlob, fileName, sequence, prediction, confidence) {
if (!emailStatusDiv) return;
if (!IS_EMAIL_SENDING_ENABLED) {
console.log("Email sending is currently disabled. Not proceeding with backend call.");
emailStatusDiv.textContent = 'Email report was NOT sent: Functionality is disabled.';
emailStatusDiv.style.color = 'var(--info-color)';
return;
}
// --- Original email sending logic (ONLY runs if IS_EMAIL_SENDING_ENABLED is true) ---
emailStatusDiv.textContent = 'Sending email...';
emailStatusDiv.style.color = 'var(--info-color)'; // Blue for processing
const reader = new FileReader();
reader.readAsDataURL(pdfBlob);
reader.onloadend = async function() {
const base64data = reader.result;
const base64PdfContent = base64data.split(',')[1]; // Strip "data:application/pdf;base64," prefix
if (!clientInstanceEmail) {
emailStatusDiv.textContent = 'Email service is not ready. Please try again.';
emailStatusDiv.style.color = 'var(--clear-button-bg)';
console.error("Gradio email client instance is not initialized, even though IS_EMAIL_SENDING_ENABLED is true. Check initClient for errors.");
return;
}
try {
const emailResult = await clientInstanceEmail.predict(
"/send_email_report",
[
email, // recipient_email: str (Python)
base64PdfContent, // pdf_content_base64: str (Python)
fileName, // file_name: str (Python)
sequence, // sequence: str (Python)
prediction, // prediction: str (Python)
confidence // confidence: float (Python)
]
);
console.log("Email sending Gradio result:", emailResult);
if (emailResult && emailResult.data && emailResult.data[0]) {
const statusMessage = emailResult.data[0];
if (statusMessage.includes("successfully")) {
emailStatusDiv.textContent = statusMessage;
emailStatusDiv.style.color = 'var(--success-color)';
} else {
emailStatusDiv.textContent = `Failed to send email: ${statusMessage}`;
emailStatusDiv.style.color = 'var(--clear-button-bg)';
}
} else {
emailStatusDiv.textContent = 'Failed to send email: Unexpected response from service.';
emailStatusDiv.style.color = 'var(--clear-button-bg)';
}
} catch (error) {
emailStatusDiv.textContent = `Error communicating with email service: ${error.message}`;
emailStatusDiv.style.color = 'var(--clear-button-bg)';
console.error('Frontend error calling Gradio email API:', error);
}
};
reader.onerror = function(error) {
emailStatusDiv.textContent = `Error reading PDF file for email: ${error.message}`;
emailStatusDiv.style.color = 'var(--clear-button-bg)';
console.error('FileReader error:', error);
};
}
// --- PDF Generation Utility Functions (Unchanged) ---
async function getBase64Image(imgSrc) {
return new Promise((resolve) => {
if (!imgSrc) { resolve(null); return; }
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = () => {
if (img.naturalWidth === 0 || img.naturalHeight === 0) {
console.warn(`getBase64Image: Image at "${imgSrc}" has zero dimensions.`);
resolve(null); return;
}
try {
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth; canvas.height = img.naturalHeight;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
resolve(canvas.toDataURL("image/png"));
} catch (e) {
console.error(`Error converting image "${imgSrc}" to base64:`, e);
resolve(null);
}
};
img.onerror = () => {
console.error(`Failed to load image for base64: "${imgSrc}"`);
resolve(null);
};
img.src = imgSrc;
});
}
async function generatePDFReportContent(sequenceForPdf, predictionForPdf, confidenceForPdf, micResultsForPdf, limeFeaturesForPdf) {
if (typeof window.jspdf === 'undefined' || typeof window.jspdf.jsPDF === 'undefined' || typeof window.jspdf.jsPDF !== 'function') {
console.error("jsPDF library (window.jspdf.jsPDF) is not loaded or not correctly exposed as a function.");
showError("PDF generation library not loaded. Cannot create report.");
return null;
}
const jsPDF = window.jspdf.jsPDF;
let pdf;
try {
pdf = new jsPDF();
if (!pdf || !pdf.internal || !pdf.internal.pageSize || pdf.internal.pageSize.width === undefined || pdf.internal.pageSize.width === null) {
console.error("Critical error: jsPDF instance or its internal properties are invalid.");
showError("PDF generation failed: Invalid PDF object.");
return null;
}
} catch (e) {
console.error("Failed to instantiate jsPDF object:", e);
showError(`PDF generation failed: Could not initialize PDF library. Error: ${e.message}`);
return null;
}
const primaryC = [0,77,64];
const textC=[51,51,51];
const successC=[39,174,96];
const errorC=[231,76,60];
const headerTextC=[44,62,80];
const pageWidth = pdf.internal.pageSize.width;
let yPos = 15;
let toolLogoB64 = null, shapPlotB64 = null;
const toolLogoEl = document.querySelector('.logos-container img');
if (toolLogoEl && toolLogoEl.src) toolLogoB64 = await getBase64Image(toolLogoEl.src);
const shapImgEl = document.querySelector('#shap-plot-container img');
if (shapImgEl && shapImgEl.src) shapPlotB64 = await getBase64Image('shap.png');
if (toolLogoB64) {
const img = new Image(); img.src = toolLogoB64; await new Promise(r=>img.onload=r);
if(img.naturalWidth > 0){
const logoW = pageWidth*0.8, ratio=img.naturalHeight/img.naturalWidth, logoH=logoW*ratio, logoX=(pageWidth-logoW)/2;
pdf.addImage(toolLogoB64,'PNG',logoX,yPos,logoW,logoH); yPos+=logoH+10;
} else {yPos+=15;}
} else { yPos+=15;}
yPos += 5;
pdf.setFont("helvetica","bold"); pdf.setFontSize(28); pdf.setTextColor(headerTextC[0],headerTextC[1],headerTextC[2]);
pdf.text("Anti-microbial Peptides Report",pageWidth/2,yPos,{align:"center"}); yPos+=28+10;
pdf.setFontSize(16); pdf.setTextColor(primaryC[0],primaryC[1],primaryC[2]); pdf.text("Input Sequence:",20,yPos); yPos+=7;
pdf.setFontSize(10); pdf.setTextColor(textC[0],textC[1],textC[2]);
const seqLines=pdf.splitTextToSize(sequenceForPdf,pageWidth-40); pdf.text(seqLines,20,yPos); yPos+=(seqLines.length*(pdf.getFontSize()/pdf.internal.scaleFactor)*1.15)+18;
if(yPos+35 > pdf.internal.pageSize.height-30){pdf.addPage(); yPos=20;}
pdf.setFontSize(16); pdf.setTextColor(primaryC[0],primaryC[1],primaryC[2]); pdf.text("Analysis Summary:",20,yPos); yPos+=8;
const predHead=[['Metric','Value']], predBody=[['Prediction',predictionForPdf],['Confidence',`${(confidenceForPdf*100).toFixed(2)}%`]];
pdf.autoTable({startY:yPos, head:predHead, body:predBody, theme:'striped',
headStyles:{fillColor:primaryC,textColor:255,fontSize:11,fontStyle:'bold',halign:'left'},
bodyStyles:{textColor:textC,fontSize:10,cellPadding:2,lineWidth:0.1,lineColor:[200,200,200]},
columnStyles:{0:{cellWidth:70,halign:'left'},1:{halign:'left',cellWidth:'auto'}},
didParseCell: (data) => {
if(data.section==='body' && data.column.index === 1 && data.row.raw[0]==='Prediction'){
data.cell.styles.fontStyle='bold';
data.cell.styles.textColor = predictionForPdf.toLowerCase().includes('non-amp') ? errorC : successC;
} else if (data.section === 'body' && data.column.index === 1 && data.row.raw[0]==='Confidence'){
data.cell.styles.textColor = successC;
}
}
});
yPos=pdf.lastAutoTable.finalY+20;
const micDataForTable = [];
if (micResultsForPdf && Object.keys(micResultsForPdf).length > 0) {
Object.entries(micResultsForPdf).forEach(([bacterium, micVal]) => {
let isChecked = false;
if(micCheckboxes) {
micCheckboxes.forEach(cb => {
const cbLabel = cb.parentElement.querySelector('.mic-label').textContent.trim();
const normalizedCbLabel = cbLabel.toLowerCase().replace(/[\s.]/g, '');
const normalizedBacteriumName = bacterium.toLowerCase().replace(/[\s.]/g, '');
if (cb.checked && normalizedBacteriumName === normalizedCbLabel) {
isChecked = true;
}
});
}
if(isChecked) {
micDataForTable.push([bacterium, typeof micVal === 'number' ? micVal.toFixed(3) : String(micVal)]);
}
});
}
if(micDataForTable.length > 0){
if(yPos+35 > pdf.internal.pageSize.height-30){pdf.addPage(); yPos=20;}
pdf.setFontSize(16); pdf.setTextColor(primaryC[0],primaryC[1],primaryC[2]); pdf.text("Predicted MIC (µM):",20,yPos); yPos+=8;
pdf.autoTable({startY:yPos, head:[['Bacterium','MIC (µM)']], body:micDataForTable, theme:'striped',
headStyles:{fillColor:primaryC,textColor:255,fontSize:11,fontStyle:'bold',halign:'center'},
columnStyles:{0:{fontStyle:'italic',cellWidth:90,halign:'left'},1:{halign:'right',cellWidth:'auto'}},
styles:{cellPadding:2,fontSize:10,textColor:textC,lineColor:[200,200,200],lineWidth:0.1},
});
yPos=pdf.lastAutoTable.finalY+20;
} else {
if(yPos+25 > pdf.internal.pageSize.height-30){pdf.addPage(); yPos=20;}
pdf.setFontSize(10); pdf.setTextColor(100,100,100);
pdf.text("No MIC prediction displayed (non-AMP, no bacteria selected, or no valid predictions for selected bacteria).", 20, yPos); yPos+=15;
}
if(!limeFeaturesForPdf || limeFeaturesForPdf.length === 0){ limeFeaturesForPdf = []; }
if(limeFeaturesForPdf.length > 0) {
pdf.addPage(); yPos=20;
pdf.setFontSize(16); pdf.setTextColor(primaryC[0],primaryC[1],primaryC[2]);
pdf.text("Top Features Influencing Prediction (Local XAI by LIME)",20,yPos);
yPos+=8;
const limeHead = [['Feature Description','Importance (LIME Weight)']];
const limeBody = limeFeaturesForPdf.sort((a,b)=>Math.abs(b.value)-Math.abs(a.value))
.map(f=>[f.feature, typeof f.value === 'number' ? f.value.toFixed(4) : 'N/A']);
pdf.autoTable({startY:yPos, head:limeHead, body:limeBody, theme:'grid',
headStyles:{fillColor:primaryC,textColor:255,fontSize:10,fontStyle:'bold'},
styles:{fontSize:9,cellPadding:1.5,lineColor:[220,220,220],lineWidth:0.1},
columnStyles:{0:{cellWidth:100},1:{halign:'right'}},
didDrawCell: (data) => {
if(data.column.index===1 && data.row.section === 'body'){
const val = parseFloat(String(data.cell.raw).trim());
if(!isNaN(val)){
if(val > 0) pdf.setTextColor(successC[0],successC[1],successC[2]);
else if (val < 0) pdf.setTextColor(errorC[0],errorC[1],errorC[2]);
}
}
}
});
yPos=pdf.lastAutoTable.finalY+20;
} else {
if(yPos+20 > pdf.internal.pageSize.height-30){pdf.addPage();yPos=20;}
else { pdf.addPage(); yPos=20; }
pdf.setFontSize(10); pdf.setTextColor(100,100,100);
pdf.text("LIME explanation data not available or not generated for this prediction.", 20, yPos); yPos+=15;
}
if (shapPlotB64) {
const img = new Image(); img.src = shapPlotB64; await new Promise(r=>img.onload=r);
if(img.naturalWidth > 0){
let imgW=img.naturalWidth,imgH=img.naturalHeight,ratio=imgW/imgH,maxH=100,maxW=pageWidth-40;
if(imgW>maxW){imgW=maxW;imgH=imgW/ratio;} if(imgH>maxH){imgH=maxH;imgW=imgH*ratio;}
if(yPos+imgH+30 > pdf.internal.pageSize.height-30){pdf.addPage(); yPos=20;}
pdf.setFontSize(16); pdf.setTextColor(primaryC[0],primaryC[1],primaryC[2]);
pdf.text("Global SHAP Feature Importance:",20,yPos);
yPos+=8;
try{pdf.addImage(shapPlotB64,'PNG',(pageWidth-imgW)/2,yPos,imgW,imgH); yPos+=imgH+10;}
catch(e){console.error("Error adding SHAP PDF:",e); yPos+=10;}
}
} else {
if(yPos+20 > pdf.internal.pageSize.height-30){pdf.addPage();yPos=20;}
pdf.setFontSize(10); pdf.setTextColor(100,100,100);
pdf.text("Global SHAP plot image not available for this report.", 20, yPos); yPos+=15;
}
addPageNumbersAndFooter(pdf, pageWidth); // Pass pageWidth to the footer function
pdf.setPage(pdf.internal.getNumberOfPages());
pdf.setFontSize(10); pdf.setTextColor(primaryC[0],primaryC[1],primaryC[2]);
pdf.text("For inquiries: [email protected]", pageWidth/2, pdf.internal.pageSize.height-18, {align:"center"});
return pdf;
}
function addPageNumbersAndFooter(doc, pageWidth) {
const pageCount = doc.internal.getNumberOfPages();
for (let i = 1; i <= pageCount; i++) {
doc.setPage(i);
doc.setFontSize(9); doc.setTextColor(120,120,120);
doc.text(`Page ${i} of ${pageCount}`, doc.internal.pageSize.width - 20, doc.internal.pageSize.height - 7, { align: "right" });
doc.text("Generated by EPIC-AMP @ Zewail City", pageWidth / 2, doc.internal.pageSize.height - 7, { align: "center" });
}
}
</script>
</body>
</html>