Spaces:
Runtime error
Runtime error
Upload 2 files
Browse filesFiles changed (2)
- app.py+7-203
- visualization.py+132-26
1031 unmodified lines1032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411031 unmodified linesimport tracebackst.code(traceback.format_exc())# Direct Download Annotated Image Buttonst.markdown("---")st.markdown("### 📸 Download Annotated Structure Image")col1, col2 = st.columns([3, 1])with col1:st.info("💡 Generate a structure visualization with RMSD and sequence information embedded")with col2:if st.button("🖼️ Generate Annotated Image", use_container_width=True, type="primary"):with st.spinner("Generating annotated image..."):try:from visualization import extract_window_pdb, transform_pdb_string# Create a simple structure visualization using matplotlib# Since we can't capture py3Dmol directly, we'll create a matplotlib-based view# Extract structuresref_pdb = extract_window_pdb(selected_row['Ref_Path'],selected_row['Ref_Window'])query_pdb = extract_window_pdb(selected_row['Query_Path'],selected_row['Query_Window'])query_aligned_pdb = transform_pdb_string(query_pdb,selected_row['Rotation_Matrix'],selected_row['Query_COM'],selected_row['Ref_COM'])# Parse coordinates for visualizationfrom rmsd_utils import parse_residue_atoms# Create a matplotlib-based 3D visualizationimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dfig = plt.figure(figsize=(12, 9), dpi=150)ax = fig.add_subplot(111, projection='3d')# Function to extract coordinates from PDB stringdef get_coords_from_pdb_string(pdb_string):coords = []for line in pdb_string.split('\n'):if line.startswith(('ATOM', 'HETATM')):try:x = float(line[30:38].strip())y = float(line[38:46].strip())z = float(line[46:54].strip())atom_name = line[12:16].strip()coords.append((x, y, z, atom_name))except:continuereturn coords# Get coordinatesref_coords = get_coords_from_pdb_string(ref_pdb)query_coords = get_coords_from_pdb_string(query_aligned_pdb)# Plot reference structure (blue)if ref_coords:ref_x = [c[0] for c in ref_coords]ref_y = [c[1] for c in ref_coords]ref_z = [c[2] for c in ref_coords]ax.scatter(ref_x, ref_y, ref_z, c='#4A90E2', s=40, alpha=0.8, label='Reference')# Connect backbone atomsbackbone_atoms = ['P', "C4'", "C3'", "O3'"]ref_backbone = [(c[0], c[1], c[2]) for c in ref_coords if c[3] in backbone_atoms]if len(ref_backbone) > 1:bb_x = [c[0] for c in ref_backbone]bb_y = [c[1] for c in ref_backbone]bb_z = [c[2] for c in ref_backbone]ax.plot(bb_x, bb_y, bb_z, c='#4A90E2', linewidth=2, alpha=0.6)# Plot query structure (red)if query_coords:query_x = [c[0] for c in query_coords]query_y = [c[1] for c in query_coords]query_z = [c[2] for c in query_coords]ax.scatter(query_x, query_y, query_z, c='#E94B3C', s=40, alpha=0.8, label='Query (Aligned)')# Connect backbone atomsquery_backbone = [(c[0], c[1], c[2]) for c in query_coords if c[3] in backbone_atoms]if len(query_backbone) > 1:bb_x = [c[0] for c in query_backbone]bb_y = [c[1] for c in query_backbone]bb_z = [c[2] for c in query_backbone]ax.plot(bb_x, bb_y, bb_z, c='#E94B3C', linewidth=2, alpha=0.6)# Set labels and titleax.set_xlabel('X (Å)', fontsize=10)ax.set_ylabel('Y (Å)', fontsize=10)ax.set_zlabel('Z (Å)', fontsize=10)ax.legend(fontsize=10, loc='upper right')# Set viewing angleax.view_init(elev=20, azim=45)# Equal aspect ratioif ref_coords or query_coords:all_coords = ref_coords + query_coordsall_x = [c[0] for c in all_coords]all_y = [c[1] for c in all_coords]all_z = [c[2] for c in all_coords]max_range = max(max(all_x) - min(all_x),max(all_y) - min(all_y),max(all_z) - min(all_z)) / 2.0mid_x = (max(all_x) + min(all_x)) / 2mid_y = (max(all_y) + min(all_y)) / 2mid_z = (max(all_z) + min(all_z)) / 2ax.set_xlim(mid_x - max_range, mid_x + max_range)ax.set_ylim(mid_y - max_range, mid_y + max_range)ax.set_zlim(mid_z - max_range, mid_z + max_range)plt.tight_layout()# Save to temporary bufferbuf = io.BytesIO()plt.savefig(buf, format='png', dpi=150, bbox_inches='tight', facecolor='white')plt.close()buf.seek(0)# Now annotate this imageannotated_img = annotate_alignment_image(image_data=buf.read(),rmsd=selected_row['RMSD'],ref_name=selected_row['Reference'],query_name=selected_row['Query'],ref_sequence=selected_row['Ref_Sequence'],query_sequence=selected_row['Query_Sequence'],output_format='JPEG')# Generate filenameref_clean = selected_row['Reference'].replace('.pdb', '')query_clean = selected_row['Query'].replace('.pdb', '')filename = f"annotated_{ref_clean}_{query_clean}_RMSD_{selected_row['RMSD']:.3f}.jpg"# Show preview and download buttonst.success("✅ Annotated image generated!")st.image(annotated_img, caption="Annotated Structure Alignment", use_column_width=True)st.download_button(label="📥 Download Annotated JPEG",data=annotated_img.getvalue(),file_name=filename,mime="image/jpeg",use_container_width=True,help="Download JPEG with RMSD and sequence information")except Exception as e:st.error(f"Error generating annotated image: {str(e)}")import tracebackst.code(traceback.format_exc())# Fallback: offer the upload optionst.info("💡 Alternatively, you can download a screenshot from the 3D viewer above using the '📷 Download PNG' button, then upload it below:")uploaded_screenshot = st.file_uploader("Upload screenshot (PNG/JPG)",type=['png', 'jpg', 'jpeg'],key=f"screenshot_upload_fallback_{selected_viz_idx}")if uploaded_screenshot is not None:try:annotated_img = annotate_alignment_image(image_data=uploaded_screenshot.read(),rmsd=selected_row['RMSD'],ref_name=selected_row['Reference'],query_name=selected_row['Query'],ref_sequence=selected_row['Ref_Sequence'],query_sequence=selected_row['Query_Sequence'],output_format='JPEG')st.image(annotated_img, use_column_width=True)ref_clean = selected_row['Reference'].replace('.pdb', '')query_clean = selected_row['Query'].replace('.pdb', '')filename = f"annotated_{ref_clean}_{query_clean}_RMSD_{selected_row['RMSD']:.3f}.jpg"st.download_button(label="📥 Download Annotated JPEG",data=annotated_img.getvalue(),file_name=filename,mime="image/jpeg",use_container_width=True)except Exception as e2:st.error(f"Error annotating uploaded image: {str(e2)}")# Show transformation detailswith st.expander("🔧 Transformation Details"):1031 unmodified lines103210331034103510361037103810391040104110421043104410451031 unmodified linesimport tracebackst.code(traceback.format_exc())# Automatic Annotation Infost.markdown("---")st.success("✅ **Automatic Annotation:** When you click 'Download PNG' in the 3D viewer above, the image automatically includes RMSD, structure names, and sequences!")st.info("💡 **Customize font size:** Use the 'Annotation Font Size' dropdown in the viewer controls (top-right) to choose from Small, Medium, Large (default), or Extra Large fonts!")# Show transformation detailswith st.expander("🔧 Transformation Details"):
314 unmodified lines315316317318319320286 unmodified lines6076086096106116126136146156166176186196209 unmodified lines630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663314 unmodified lines<option value="gray">Gray</option></select></div></div><div class="rmsd-info">286 unmodified linesvar refName = "{ref_name}".replace('.pdb', '');var queryName = "{query_name}".replace('.pdb', '');var rmsdValue = "{f'{rmsd:.3f}' if rmsd is not None else 'NA'}";var filename = 'alignment_' + refName + '_' + queryName + '_RMSD_' + rmsdValue + '.png';// Ensure viewer is renderedif (viewer) {{viewer.render();}}// Get the container element (includes canvas + all overlays)const container = document.getElementById('container');if (!container) {{9 unmodified linesuseCORS: true,allowTaint: true}}).then(function(canvas) {{// Convert to PNGconst dataURL = canvas.toDataURL('image/png');// Create download linkconst link = document.createElement('a');link.download = filename;link.href = dataURL;// Trigger downloaddocument.body.appendChild(link);link.click();document.body.removeChild(link);}}).catch(function(error) {{console.error('html2canvas error:', error);// Fallback: just capture the canvas without overlaysconst canvas = document.querySelector('#container canvas');if (canvas) {{const dataURL = canvas.toDataURL('image/png');const link = document.createElement('a');link.download = filename;link.href = dataURL;document.body.appendChild(link);link.click();document.body.removeChild(link);}} else {{alert('Download failed. Please try again.');}}}});}} catch (error) {{314 unmodified lines315316317318319320321322323324325326327328329330286 unmodified lines6176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566579 unmodified lines667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769314 unmodified lines<option value="gray">Gray</option></select></div><div class="control-section"><div class="section-title">Annotation Font Size</div><select id="annotationFontSize"><option value="small">Small (18pt/16pt/14pt)</option><option value="medium">Medium (22pt/18pt/16pt)</option><option value="large" selected>Large (28pt/22pt/18pt)</option><option value="xlarge">Extra Large (36pt/28pt/22pt)</option></select></div></div><div class="rmsd-info">286 unmodified linesvar refName = "{ref_name}".replace('.pdb', '');var queryName = "{query_name}".replace('.pdb', '');var rmsdValue = "{f'{rmsd:.3f}' if rmsd is not None else 'NA'}";var refSeq = "{ref_sequence if ref_sequence else ''}";var querySeq = "{query_sequence if query_sequence else ''}";var filenameOriginal = 'alignment_' + refName + '_' + queryName + '_RMSD_' + rmsdValue + '.png';var filenameAnnotated = 'annotated_' + refName + '_' + queryName + '_RMSD_' + rmsdValue + '.png';// Get selected font sizeconst fontSizeSelect = document.getElementById('annotationFontSize');const fontSizeOption = fontSizeSelect ? fontSizeSelect.value : 'large';// Define font sizes based on selection (all values are at 2x scale for high resolution)let fontSizes;switch(fontSizeOption) {{case 'small':fontSizes = {{ rmsd: 36, name: 32, seq: 28 }}; // 18pt/16pt/14pt at 2xbreak;case 'medium':fontSizes = {{ rmsd: 44, name: 36, seq: 32 }}; // 22pt/18pt/16pt at 2xbreak;case 'large':fontSizes = {{ rmsd: 56, name: 44, seq: 36 }}; // 28pt/22pt/18pt at 2xbreak;case 'xlarge':fontSizes = {{ rmsd: 72, name: 56, seq: 44 }}; // 36pt/28pt/22pt at 2xbreak;default:fontSizes = {{ rmsd: 56, name: 44, seq: 36 }}; // Default to large}}// Ensure viewer is renderedif (viewer) {{viewer.render();}}// Get the container elementconst container = document.getElementById('container');if (!container) {{9 unmodified linesuseCORS: true,allowTaint: true}}).then(function(canvas) {{// Create ANNOTATED versionconst annotatedCanvas = document.createElement('canvas');annotatedCanvas.width = canvas.width;annotatedCanvas.height = canvas.height;const ctx = annotatedCanvas.getContext('2d');// Draw the original image onto new canvasctx.drawImage(canvas, 0, 0);// Add annotationsconst margin = 30; // Scaled for 2x resolutionconst padding = 24;const lineSpacing = 16;// Prepare annotation text with selected font sizesconst annotations = [{{ text: 'RMSD: ' + rmsdValue + ' Å', fontSize: fontSizes.rmsd, fontFamily: 'bold Arial', color: '#E94B3C' }},{{ text: '', fontSize: 20, fontFamily: 'Arial', color: '#333' }}, // Spacer{{ text: 'Reference: ' + refName, fontSize: fontSizes.name, fontFamily: 'Arial', color: '#333' }},{{ text: ' Seq: ' + refSeq, fontSize: fontSizes.seq, fontFamily: 'Courier New, monospace', color: '#666' }},{{ text: '', fontSize: 20, fontFamily: 'Arial', color: '#333' }}, // Spacer{{ text: 'Query: ' + queryName, fontSize: fontSizes.name, fontFamily: 'Arial', color: '#333' }},{{ text: ' Seq: ' + querySeq, fontSize: fontSizes.seq, fontFamily: 'Courier New, monospace', color: '#666' }}];// Calculate box dimensionslet maxWidth = 0;let totalHeight = padding * 2;const textMetrics = [];annotations.forEach(ann => {{if (ann.text) {{ctx.font = ann.fontSize + 'px ' + ann.fontFamily;const metrics = ctx.measureText(ann.text);const height = ann.fontSize * 1.2; // Approximate heighttextMetrics.push({{ width: metrics.width, height: height }});maxWidth = Math.max(maxWidth, metrics.width);totalHeight += height + lineSpacing;}} else {{textMetrics.push({{ width: 0, height: lineSpacing / 2 }});totalHeight += lineSpacing / 2;}}}});const boxWidth = maxWidth + padding * 2;const boxHeight = totalHeight;// Position box in bottom-leftconst boxX = margin;const boxY = annotatedCanvas.height - boxHeight - margin;// Draw semi-transparent white background with rounded cornersctx.fillStyle = 'rgba(255, 255, 255, 0.95)';const radius = 16;ctx.beginPath();ctx.moveTo(boxX + radius, boxY);ctx.lineTo(boxX + boxWidth - radius, boxY);ctx.quadraticCurveTo(boxX + boxWidth, boxY, boxX + boxWidth, boxY + radius);ctx.lineTo(boxX + boxWidth, boxY + boxHeight - radius);ctx.quadraticCurveTo(boxX + boxWidth, boxY + boxHeight, boxX + boxWidth - radius, boxY + boxHeight);ctx.lineTo(boxX + radius, boxY + boxHeight);ctx.quadraticCurveTo(boxX, boxY + boxHeight, boxX, boxY + boxHeight - radius);ctx.lineTo(boxX, boxY + radius);ctx.quadraticCurveTo(boxX, boxY, boxX + radius, boxY);ctx.closePath();ctx.fill();// Draw borderctx.strokeStyle = 'rgba(200, 200, 200, 0.95)';ctx.lineWidth = 2;ctx.stroke();// Draw textlet currentY = boxY + padding;annotations.forEach((ann, idx) => {{if (ann.text) {{ctx.font = ann.fontSize + 'px ' + ann.fontFamily;ctx.fillStyle = ann.color;ctx.fillText(ann.text, boxX + padding, currentY + textMetrics[idx].height * 0.8);currentY += textMetrics[idx].height + lineSpacing;}} else {{currentY += textMetrics[idx].height;}}}});// Download ONLY the annotated PNGconst annotatedDataURL = annotatedCanvas.toDataURL('image/png');const linkAnnotated = document.createElement('a');linkAnnotated.download = filenameAnnotated;linkAnnotated.href = annotatedDataURL;document.body.appendChild(linkAnnotated);linkAnnotated.click();document.body.removeChild(linkAnnotated);}}).catch(function(error) {{console.error('html2canvas error:', error);alert('Error creating images. Please try again.');}});}} catch (error) {{
app.py+7-203
visualization.py+132-26