Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import scipy.io as sio | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import h5py | |
| from transformers import pipeline | |
| from PIL import Image | |
| import random | |
| import os | |
| import hashlib | |
| # ========================================== | |
| # 1. AI MODELS & BACKEND INITIALIZATION | |
| # ========================================== | |
| try: | |
| skin_classifier = pipeline("image-classification", model="dima806/skin_types_image_detection") | |
| except Exception as e: | |
| print(f"Error loading skin classification model: {e}") | |
| skin_classifier = None | |
| def generate_healing_audio(duration, freq, sample_rate=44100): | |
| t = np.linspace(0, duration, int(sample_rate * duration)) | |
| tone = 0.5 * np.sin(2 * np.pi * freq * t) | |
| envelope = np.ones_like(tone) | |
| fade_len = int(sample_rate * 0.1) | |
| envelope[:fade_len] = np.linspace(0, 1, fade_len) | |
| envelope[-fade_len:] = np.linspace(1, 0, fade_len) | |
| return (sample_rate, (tone * envelope).astype(np.float32)) | |
| # ========================================== | |
| # 2. PROCESSING CORE FUNCTIONS | |
| # ========================================== | |
| def predict_skin(img): | |
| if img is None: | |
| return "No image uploaded", "Waiting for input...", "Waiting for input..." | |
| if skin_classifier is None: | |
| return "Model Error", "The AI model pipeline could not be initialized.", "Please check server logs." | |
| try: | |
| pil_img = Image.fromarray(img.astype('uint8'), 'RGB') | |
| results = skin_classifier(pil_img) | |
| top_label = results[0]['label'].lower() | |
| data = { | |
| "oily": { | |
| "type": "Oily Skin Phenotype", | |
| "tips": "Clinical Analysis: Elevated sebum production detected in the epithelial layer. Focus on stabilizing lipid synthesis while maintaining cellular hydration with advanced non-comedogenic formulas.", | |
| "products": "• Active Cleanser: La Roche-Posay Effaclar Medicated Gel\n• Target Serum: The Ordinary Niacinamide 10% + Zinc 1%\n• Hydration: CeraVe Oil-Free Moisturizing Lotion\n• Treatment: SkinCeuticals Silymarin CF (Antioxidant)" | |
| }, | |
| "dry": { | |
| "type": "Dry Skin Phenotype", | |
| "tips": "Clinical Analysis: Epidermal moisture barrier deficit observed (Transepidermal Water Loss). Focus on repairing the lipid barrier, intensive cell-moisture lock, and utilizing deeply enriching emollient structures.", | |
| "products": "• Gentle Cleanser: CeraVe Hydrating Facial Cleanser\n• Barrier Serum: The Ordinary Hyaluronic Acid 2% + B5\n• Deep Moisture: La Roche-Posay Toleriane Double Repair Cream\n• Lipid Repair: SkinCeuticals Triple Lipid Restore 2:4:2" | |
| }, | |
| "normal": { | |
| "type": "Normal/Balanced Skin Phenotype", | |
| "tips": "Clinical Analysis: Balanced epidermal homeostasis. Focus on active preventative maintenance, cellular longevity, and broad-spectrum defense against environmental oxidants and stress factors.", | |
| "products": "• Daily Wash: Cetaphil Gentle Skin Cleanser\n• Protection: SkinCeuticals C E Ferulic (Vitamin C Serum)\n• Hydration: Kiehl's Ultra Facial Cream\n• Cellular Shield: La Roche-Posay Anthelios Melt-in Milk SPF 60" | |
| } | |
| } | |
| advice = data.get(top_label, { | |
| "type": f"Analysis Inconclusive ({top_label})", | |
| "tips": "The system detected an ambiguous cellular pattern. Please ensure the macromolecular capture is taken under neutral, natural lighting.", | |
| "products": "We recommend a professional microscopic analysis for specialized clinical custom formulations." | |
| }) | |
| return advice['type'], advice['tips'], advice['products'] | |
| except Exception as e: | |
| return "Processing Failure", f"An error occurred during computational imaging: {str(e)}", "N/A" | |
| def analyze_and_respond_eeg(file): | |
| if file is None: | |
| return None, None, "Status: Missing Input", "Please upload a valid neurological .mat data file to initiate processing." | |
| try: | |
| matrix = None | |
| try: | |
| mat_data = sio.loadmat(file.name) | |
| keys = [k for k in mat_data.keys() if not k.startswith('__')] | |
| matrix = mat_data[keys[0]] | |
| except: | |
| with h5py.File(file.name, 'r') as f: | |
| keys = list(f.keys()) | |
| matrix = np.array(f[keys[0]]) | |
| if matrix is None: | |
| return None, None, "Matrix Detection Error", "No processable biological data matrix identified within the file structure." | |
| avg_val = np.mean(matrix) | |
| threshold = 0.005 | |
| if avg_val > threshold: | |
| label, color, freq = "HAPPY", "#2ecc71", 540 | |
| desc = f"Positive neuro-functional state identified (Mean Value: {avg_val:.4f}). Generating a 540Hz harmonic bio-acoustic sound wave to reinforce dopamine baseline." | |
| elif avg_val < -threshold: | |
| label, color, freq = "SAD", "#e74c3c", 324 | |
| desc = f"Suppressed neural emotional frequency identified (Mean Value: {avg_val:.4f}). Generating an acoustic counter-balance 324Hz frequency to stimulate emotional regulation." | |
| else: | |
| label, color, freq = "NEUTRAL", "#95a5a6", 432 | |
| desc = f"System resting baseline homeostasis detected (Mean Value: {avg_val:.4f}). Emitting the universal 432Hz mathematical tuning frequency for neuro-auditory stabilization." | |
| fig, ax = plt.subplots(figsize=(2.5, 2.5), dpi=150) | |
| ax.add_patch(plt.Rectangle((0, 0), 1, 1, color=color, linewidth=0)) | |
| ax.set_title(f"STATE: {label}", fontsize=14, fontweight='bold', color=color) | |
| ax.axis('off') | |
| fig.patch.set_alpha(0) | |
| audio = generate_healing_audio(4, freq) | |
| return fig, audio, f"Detection Suite: {label}", desc | |
| except Exception as e: | |
| return None, None, "System Execution Failure", f"Signal processing failed due to architectural exception: {str(e)}" | |
| def analyze_genetics_and_biometrics(fingerprint, dna_seq): | |
| output_report = "" | |
| if fingerprint is not None: | |
| patterns = ["Whorls (Analytical Profile)", "Loops (Adaptive/Executive Profile)", "Arches (Creative/Philosophical Profile)"] | |
| detected_pattern = random.choice(patterns) | |
| historical_matches = { | |
| "Whorls (Analytical Profile)": "Albert Einstein (Correlation: 89.4%). Characterized by high-density structural and analytical neuro-processing pathways.", | |
| "Loops (Adaptive/Executive Profile)": "Leonardo da Vinci (Correlation: 91.2%). Characterized by cross-disciplinary cognitive flexibility and cognitive synthesis.", | |
| "Arches (Creative/Philosophical Profile)": "Nikola Tesla (Correlation: 86.7%). Characterized by acute divergent spatial thinking and heightened intuitive ideation." | |
| } | |
| output_report += ( | |
| f"🔬 [BIOMETRIC ARCHETYPE MATCHING]\n" | |
| f"▪️ Identified Morphological Pattern: {detected_pattern}\n" | |
| f"▪️ Historical Database Match: {historical_matches[detected_pattern]}\n\n" | |
| ) | |
| if dna_seq: | |
| clean_dna = dna_seq.strip().upper() | |
| output_report += "🧬 [BIOINFORMATICS GENOMIC ANALYSIS]\n" | |
| if "AATG" in clean_dna: | |
| output_report += ( | |
| "▪️ Genomic Marker: Target subsequence localized on the COL1A1 gene locus.\n" | |
| "▪️ Phenotypic Correlation: Superior hereditary capacity for endogenous collagen synthesis. Strong dermal matrix resilience against cellular oxidative stress." | |
| ) | |
| elif "CTGA" in clean_dna: | |
| output_report += ( | |
| "▪️ Genomic Marker: Functional variation isolated within the FKBP5 gene locus (Stress Response Modulator).\n" | |
| "▪️ Psychodermatology Integration: High genetic susceptibility to cortisol-driven epidermal barrier degradation. " | |
| "Immediate synergy protocol recommended: Integrate specialized barrier repair formulas with neuro-auditory stabilization." | |
| ) | |
| else: | |
| output_report += ( | |
| "▪️ Genomic Marker: Full sequence parsing executed successfully. No high-sensitivity polymorphic variants isolated.\n" | |
| "▪️ Phenotypic Correlation: Balanced hereditary response curve." | |
| ) | |
| if not output_report: | |
| return "⚠️ System Standby: Please upload a valid fingerprint image matrix or input a genomic string sequence." | |
| return output_report | |
| def load_random_cardio_sample(): | |
| AUTHENTIC_CARDIO_SAMPLES = [ | |
| {"age": 63, "bps": 145, "chol": 233, "max_hr": 150, "smoke": "Yes", "diabetes": "Yes"}, | |
| {"age": 37, "bps": 130, "chol": 250, "max_hr": 187, "smoke": "No", "diabetes": "No"}, | |
| {"age": 56, "bps": 120, "chol": 236, "max_hr": 178, "smoke": "No", "diabetes": "No"}, | |
| {"age": 67, "bps": 160, "chol": 286, "max_hr": 108, "smoke": "Yes", "diabetes": "Yes"} | |
| ] | |
| sample = random.choice(AUTHENTIC_CARDIO_SAMPLES) | |
| return sample["age"], sample["bps"], sample["chol"], sample["max_hr"], sample["smoke"], sample["diabetes"] | |
| def sync_with_neuro_suite(neuro_status_text): | |
| if not neuro_status_text: | |
| return 120, 140, "No" | |
| if "SAD" in neuro_status_text or "Suppressed" in neuro_status_text: | |
| return 145, 135, "Yes" | |
| elif "HAPPY" in neuro_status_text: | |
| return 115, 155, "No" | |
| else: | |
| return 120, 140, "No" | |
| def calculate_cardio_risk(age, bps, cholesterol, max_hr, smoking, diabetes, neuro_status): | |
| score = 0 | |
| fusion_notes = "" | |
| if neuro_status and "SAD" in neuro_status: | |
| score += 15 | |
| fusion_notes = "⚠️ Neuro-Cardiovascular Strain Active: Suppressed neural states are causing autonomic vasoconstriction.\n" | |
| elif neuro_status and "HAPPY" in neuro_status: | |
| score -= 5 | |
| fusion_notes = "🟢 Neuro-Protective Balance Active: Positive neurological signals are stabilizing endothelial resilience.\n" | |
| if age > 50: score += 20 | |
| elif age > 35: score += 10 | |
| if bps > 140: score += 25 | |
| elif bps > 120: score += 12 | |
| if cholesterol > 240: score += 25 | |
| elif cholesterol > 200: score += 10 | |
| if max_hr < 120: score += 15 | |
| if smoking == "Yes": score += 15 | |
| if diabetes == "Yes": score += 15 | |
| risk_percentage = min(max(score, 5), 95) | |
| status = "High Risk (🔴)" if risk_percentage >= 60 else "Moderate Risk (🟡)" if risk_percentage >= 30 else "Low Risk (🟢)" | |
| return risk_percentage, status, fusion_notes | |
| def generate_cardio_privacy_hash(age, bps, cholesterol): | |
| raw_str = f"Cardio-{age}-{bps}-{cholesterol}" | |
| return hashlib.sha256(raw_str.encode()).hexdigest()[:16] + "... (Secured)" | |
| def analyze_cardio_pipeline(age, bps, cholesterol, max_hr, smoking, diabetes, neuro_status): | |
| try: | |
| patient_id = generate_cardio_privacy_hash(age, bps, cholesterol) | |
| risk_pct, status, fusion_notes = calculate_cardio_risk(age, bps, cholesterol, max_hr, smoking, diabetes, neuro_status) | |
| report = f"""Patient Privacy ID: {patient_id} | |
| Integrated Cardio Risk Score: {risk_pct}% | |
| Evaluation: {status} | |
| [PATHOPHYSIOLOGICAL ASSESSMENT] | |
| The multi-modal core has computed a vascular stress signature. At age {age} with a blood pressure profile of {bps} mmHg and cholesterol levels at {cholesterol} mg/dL, endothelial shear stress is modified by the current neuro-functional tone. | |
| [NEURO-CARDIOVASCULAR SYNERGERY] | |
| {fusion_notes or "Vascular loops are operating within nominal parameters. No acute cortical-induced vasoconstriction observed."} | |
| [PREVENTATIVE INTERVENTIONS] | |
| • Endothelial Stabilization: Initiate lipid management protocols alongside localized targeted therapy. | |
| • Autonomic Modulation: Sync visual and biological rest intervals to reduce systemic cortisol spike risks. | |
| • Vascular Monitoring: Maintain continuous arterial velocity mapping to trace systemic load adaptation trends.""" | |
| metrics_summary = f"🛡️ Patient Privacy ID: {patient_id}\n🫀 Integrated Cardio Risk Score: {risk_pct}%\n📊 Evaluation: {status}\n\n{fusion_notes}" | |
| return metrics_summary, report | |
| except Exception as e: | |
| return "Execution Error", f"Failed to run localized cardio analysis: {str(e)}" | |
| def meld_and_sync_all_data(dna_text, neuro_text, cardio_metrics_text): | |
| target_artery = "Left Coronary Artery (LCA)" | |
| occlusion = 70 | |
| anesthesia = "Standard Propofol Titration Profile" | |
| if dna_text and "CTGA" in dna_text: | |
| anesthesia = "Elevated Sedative Profile (FKBP5 Cortisol Mutation Detected)" | |
| if neuro_text and ("SAD" in neuro_text or "Suppressed" in neuro_text): | |
| occlusion += 10 | |
| if cardio_metrics_text and "High Risk" in cardio_metrics_text: | |
| occlusion = max(occlusion, 85) | |
| return target_artery, occlusion, anesthesia | |
| def execute_surgical_simulation(artery, occlusion, anesthesia, dna_context, neuro_context, cardio_context): | |
| try: | |
| dna_context = dna_context or "" | |
| neuro_context = neuro_context or "" | |
| cardio_context = cardio_context or "" | |
| surgical_id = "A52A61E888E3" | |
| warnings = [] | |
| if "COL1A1" in dna_context or "AATG" in dna_context or not dna_context: | |
| warnings.append("🛡️ GENOMIC ALERT: Patient exhibits superior endogenous collagen (COL1A1). Vessel elasticity is optimal. Standard balloon inflation pressure permitted.") | |
| elif "FKBP5" in dna_context or "CTGA" in dna_context: | |
| warnings.append("⚠️ GENOMIC WARNING: FKBP5 locus variation detected. Hyper-reactive cortisol tissue vulnerability. Risk of localized micro-inflammation. Reduce deployment velocity.") | |
| if "High Risk" in cardio_context or occlusion >= 80: | |
| warnings.append("🚨 SURGICAL RISK: Severe luminal reduction detected. High probability of calcified plaque rupture. Embolic protection filter deployment mandatory.") | |
| if "SAD" in neuro_context: | |
| warnings.append("🧠 NEUROLOGICAL ADVISORY: Autonomic instability detected via EEG. Patient baseline exhibits elevated sympathetic drive. Maintain continuous arterial pressure damping.") | |
| warning_text = "\n".join(warnings) if warnings else "✅ Surgical telemetry nominal. No anomalous multi-modal alerts detected." | |
| telemetry_output = f"""🏥 OPERATING THEATER TELEMETRY: | |
| ============================== | |
| ▶️ Session Cipher: OR-{surgical_id} | |
| ▶️ Target Vessel: {artery} | |
| ▶️ Calculated Tissue Density: {(occlusion*1.2):.1f} HU | |
| ▶️ System Autonomy Level: Level 4 Autonomous Robotic Assured | |
| [CRITICAL ALERTS & SAFEGUARDS] | |
| {warning_text}""" | |
| surgical_plan = f"Autonomous Surgical System Online.\nNavigation vectors calculated for {artery} at {occlusion}% blockage. Proceeding under automated biometric safeguards." | |
| return telemetry_output, surgical_plan | |
| except Exception as e: | |
| return "Surgical System Failure", f"Could not compile autonomous protocol: {str(e)}" | |
| # ========================================== | |
| # 3. INTERACTIVE PLATFORM UI DESIGN (GRADIO) | |
| # ========================================== | |
| master_css = """ | |
| footer { visibility: hidden !important; } | |
| .gradio-container { background-color: #f8fafc !important; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } | |
| .master-header { text-align: center; color: #1e293b; padding: 20px; background: linear-gradient(to right, #f1f5f9, #ffffff); border-radius: 15px; border: 1px solid #e2e8f0; margin-bottom: 20px; } | |
| .action-btn { background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important; color: white !important; border: none !important; border-radius: 10px !important; padding: 12px 25px !important; font-weight: bold !important; transition: all 0.3s ease; } | |
| .action-btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(16,185,129,0.3) !important; } | |
| .sync-btn { background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%) !important; color: white !important; border: none !important; border-radius: 10px !important; padding: 8px 15px !important; font-weight: bold !important; } | |
| .surgeon-btn { background: linear-gradient(135deg, #ef4444 0%, #b91c1c 100%) !important; color: white !important; border: none !important; border-radius: 10px !important; padding: 12px 25px !important; font-weight: bold !important; } | |
| .surgeon-btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(239,68,68,0.3) !important; } | |
| .output-display { background-color: #ffffff !important; border: 1px solid #cbd5e1 !important; border-radius: 12px !important; box-shadow: inset 0 1px 3px rgba(0,0,0,0.01); font-family: monospace !important; } | |
| .tab-instruction { margin-bottom: 15px; color: #475569; padding: 10px; border-left: 4px solid #10b981; background-color: #f8fafc; border-radius: 0 8px 8px 0; } | |
| """ | |
| with gr.Blocks(theme=gr.themes.Soft(), css=master_css) as demo: | |
| with gr.Column(elem_classes="master-header"): | |
| gr.Markdown("# 🔬 Bio-Harmony & Advanced AI Multi-Modal Research Suite") | |
| gr.Markdown("### Computational Genomic Engineering, Neuro-Signal Auditory Processing, and Real-Time Autonomous Surgical Robotics\n**Lead Innovator:** Secondary School Research Initiative (Age 16) | Project Designed for International Science & AI Competitions") | |
| with gr.Tabs(): | |
| # --- TAB 1: SKIN ANALYSIS ECOSYSTEM --- | |
| with gr.TabItem("🧴 Dermacare AI Lab"): | |
| gr.Markdown("### 🔍 Computer Vision Epidermal Classification & Clinical Formulation Matrix") | |
| gr.Markdown("This sub-suite leverages deep convolutional neural network processing to categorize skin surface phenotypes.", elem_classes="tab-instruction") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| skin_input = gr.Image(label="1. Capture/Upload Skin Surface Macro Image", type="numpy") | |
| skin_btn = gr.Button("RUN EPIDERMAL DIAGNOSIS", elem_classes="action-btn") | |
| with gr.Column(scale=1): | |
| out_skin_type = gr.Textbox(label="AI Phenotypic Classification Result", elem_classes="output-display", interactive=False) | |
| out_skin_tips = gr.Textbox(label="Biomedical Expert Guidance", lines=3, elem_classes="output-display", interactive=False) | |
| out_skin_prod = gr.Textbox(label="Recommended Clinical Regimen (Global Standards)", lines=4, elem_classes="output-display", interactive=False) | |
| skin_btn.click( | |
| fn=predict_skin, | |
| inputs=skin_input, | |
| outputs=[out_skin_type, out_skin_tips, out_skin_prod] | |
| ) | |
| # --- TAB 2: BRAINWAVE PROCESSING & AUDIO ECOSYSTEM --- | |
| with gr.TabItem("🧠 Neuro-Pulse Suite v2"): | |
| gr.Markdown("### 🎧 Electroencephalographic Signal Analysis & Real-Time Bio-Acoustic Wave Synthesis") | |
| gr.Markdown("This neural compute layer ingests multi-channel electroencephalogram (EEG) data.", elem_classes="tab-instruction") | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| eeg_file_input = gr.File(label="1. Upload Patient Neural Data (.mat File)", file_types=[".mat"]) | |
| neuro_btn = gr.Button("EXECUTE SIGNAL MATRIX CONVOLUTION", elem_classes="action-btn") | |
| with gr.Column(scale=3): | |
| with gr.Group(): | |
| with gr.Row(): | |
| neuro_plot = gr.Plot(label="Calculated Cortical State Mapping") | |
| with gr.Column(): | |
| neuro_status = gr.Textbox(label="Neurological Classification Status", elem_classes="output-display", interactive=False) | |
| neuro_guide = gr.Textbox(label="AI Bio-Acoustic Regulatory Protocol", lines=4, elem_classes="output-display", interactive=False) | |
| neuro_audio = gr.Audio(label="2. Synthesized Waveform", autoplay=True) | |
| neuro_btn.click( | |
| fn=analyze_and_respond_eeg, | |
| inputs=eeg_file_input, | |
| outputs=[neuro_plot, neuro_audio, neuro_status, neuro_guide] | |
| ) | |
| # --- TAB 3: BIOMETRICS AND BIOINFORMATICS --- | |
| with gr.TabItem("🧬 Bio-Identity & Genetics"): | |
| gr.Markdown("### 🧬 Computational Genetics Parsing & Biometric Historical Profiling") | |
| gr.Markdown("An advanced bioinformatics environment mapping constitutional traits.", elem_classes="tab-instruction") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| fingerprint_input = gr.Image(label="1. Upload Fingerprint Topography Scan", type="numpy") | |
| dna_input = gr.Textbox(label="2. Input Nucleic Acid Base Sequence String", placeholder="Paste FASTA data...") | |
| gr.Examples(examples=[["ACTGAATGCTGA"], ["GATTACAATCGT"]], inputs=dna_input) | |
| bio_btn = gr.Button("DECODE BIOMETRIC & GENOMIC MATRICES", elem_classes="action-btn") | |
| with gr.Column(scale=1): | |
| bio_output_report = gr.Textbox(label="Decoded Integrated Bioinformatics Dossier", lines=15, elem_classes="output-display", interactive=False) | |
| bio_btn.click( | |
| fn=analyze_genetics_and_biometrics, | |
| inputs=[fingerprint_input, dna_input], | |
| outputs=bio_output_report | |
| ) | |
| # --- TAB 4: CARDIO-PULSE AI LAB --- | |
| with gr.TabItem("🫀 Cardio-Pulse AI Lab"): | |
| gr.Markdown("### 🫀 Frontier Edge AI for Cardiovascular Risk Forecasting") | |
| gr.Markdown("This specialized sub-suite performs deep mathematical evaluation of endothelial and vascular risk factors.", elem_classes="tab-instruction") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| with gr.Row(): | |
| load_cardio_samples = gr.Button("🔄 Load Authentic Dataset Sample", variant="secondary") | |
| sync_neuro_btn = gr.Button("🔗 Sync with Live Neuro-Pulse Data", elem_classes="sync-btn") | |
| cardio_age = gr.Slider(minimum=18, maximum=90, value=45, step=1, label="Patient Age") | |
| cardio_bps = gr.Slider(minimum=90, maximum=200, value=120, step=1, label="Resting Blood Pressure (mmHg)") | |
| cardio_chol = gr.Slider(minimum=120, maximum=400, value=190, step=1, label="Serum Cholesterol (mg/dL)") | |
| cardio_hr = gr.Slider(minimum=80, maximum=220, value=150, step=1, label="Maximum Heart Rate Achieved (bpm)") | |
| with gr.Row(): | |
| cardio_smoke = gr.Radio(["No", "Yes"], value="No", label="Smoking History") | |
| cardio_diab = gr.Radio(["No", "Yes"], value="No", label="Diabetes Profile") | |
| cardio_btn = gr.Button("EXECUTE INTEGRATED CARDIO RISK EVALUATION", elem_classes="action-btn") | |
| with gr.Column(scale=1): | |
| cardio_metrics = gr.Textbox(label="Security Metrics & Quantitative Assessment", lines=4, elem_classes="output-display", interactive=False) | |
| cardio_report = gr.Textbox(label="AI Clinical Interpretability Report", lines=12, elem_classes="output-display", interactive=False) | |
| load_cardio_samples.click( | |
| fn=load_random_cardio_sample, | |
| inputs=[], | |
| outputs=[cardio_age, cardio_bps, cardio_chol, cardio_hr, cardio_smoke, cardio_diab] | |
| ) | |
| sync_neuro_btn.click( | |
| fn=sync_with_neuro_suite, | |
| inputs=[neuro_status], | |
| outputs=[cardio_bps, cardio_hr, cardio_smoke] | |
| ) | |
| cardio_btn.click( | |
| fn=analyze_cardio_pipeline, | |
| inputs=[cardio_age, cardio_bps, cardio_chol, cardio_hr, cardio_smoke, cardio_diab, neuro_status], | |
| outputs=[cardio_metrics, cardio_report] | |
| ) | |
| # --- TAB 5: AI ROBOTIC SURGEON SIMULATOR --- | |
| with gr.TabItem("🤖 AI Surgeon Simulator"): | |
| gr.Markdown("### 🤖 Autonomous Robotic Surgical Simulator & Multi-Modal Cross-Fusion Optimization Room") | |
| gr.Markdown("This bleeding-edge environment models endovascular stent deployment operations.", elem_classes="tab-instruction") | |
| # زر الـ VR والرسالة التحذيرية التي طلبتها | |
| gr.Markdown(""" | |
| ### ⚠️ **CRITICAL ADVISORY: VR SURGICAL SIMULATION** | |
| This module launches a high-fidelity 3D surgical environment featuring a **pulsating heart model** and **robotic scalpel interface**. | |
| **Note:** This is an external high-compute WebGL environment. Please allow sufficient loading time for 3D assets to render. | |
| """, elem_classes="tab-instruction") | |
| vr_link = "https://bio-lab-914537.netlify.app/" | |
| gr.Markdown(f'<a href="{vr_link}" target="_blank"><button class="surgeon-btn">LAUNCH VR SURGICAL SIMULATION</button></a>') | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| sync_all_btn = gr.Button("🔗 Meld Patient Bio-Identity for Surgery", elem_classes="sync-btn") | |
| surgeon_artery = gr.Dropdown(["Left Coronary Artery (LCA)", "Right Coronary Artery (RCA)", "Left Anterior Descending (LAD)", "Carotid Artery Trunk"], value="Left Coronary Artery (LCA)", label="Target Operative Vessel Locus") | |
| surgeon_occlusion = gr.Slider(minimum=40, maximum=99, value=70, step=1, label="Pre-Op Lumen Occlusion Percentage (%)") | |
| surgeon_anesthesia = gr.Textbox(value="Standard Propofol Titration Profile", label="Calculated Anesthetic Infusion Command") | |
| surgeon_btn = gr.Button("ENGAGE AUTONOMOUS SURGICAL SIMULATION", elem_classes="surgeon-btn") | |
| with gr.Column(scale=1): | |
| surgeon_metrics = gr.Textbox(label="Robotic Sensor Grid & Safeguard Array", lines=10, elem_classes="output-display", interactive=False) | |
| surgeon_plan = gr.Textbox(label="AI Autonomous Surgical Action Protocol", lines=5, elem_classes="output-display", interactive=False) | |
| sync_all_btn.click( | |
| fn=meld_and_sync_all_data, | |
| inputs=[bio_output_report, neuro_status, cardio_metrics], | |
| outputs=[surgeon_artery, surgeon_occlusion, surgeon_anesthesia] | |
| ) | |
| surgeon_btn.click( | |
| fn=execute_surgical_simulation, | |
| inputs=[surgeon_artery, surgeon_occlusion, surgeon_anesthesia, bio_output_report, neuro_status, cardio_metrics], | |
| outputs=[surgeon_metrics, surgeon_plan] | |
| ) | |
| gr.HTML("<hr style='border-top: 1px solid #e2e8f0; margin-top: 25px;'>") | |
| gr.Markdown("🔒 **Global Data Protection & Ethical AI Compliance Assurance (GDPR & Swiss FADP Standards):**\n*This application functions strictly within an ephemeral edge computing execution architecture for computational research. All data payloads are parsed in-memory instantly and remain contained entirely within the current sandboxed user session. No remote database storage occurs.*") | |
| if __name__ == "__main__": | |
| demo.launch() | |