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 requests | |
| 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 | |
| # ========================================== | |
| # --- Tab 1: Skin Diagnostics Logic --- | |
| 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" | |
| # --- Tab 2: Neuro-Signal Processing Logic --- | |
| 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)}" | |
| # --- Tab 3: Biometrics & Genomics Processing Logic --- | |
| 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. " | |
| "Hereditary pathways indicate that localized skin cell inflammation can be actively triggered by the neural distress states " | |
| "monitored in the Neuro-Pulse suite. Immediate synergy protocol recommended: Integrate specialized barrier repair formulas " | |
| "(containing Ceramides and Centella Asiatica) with the system's generated 324Hz/432Hz bio-acoustic sound waves to suppress adrenal stress cues." | |
| ) | |
| else: | |
| output_report += ( | |
| "▪️ Genomic Marker: Full sequence parsing executed successfully. No high-sensitivity polymorphic variants isolated.\n" | |
| "▪️ Phenotypic Correlation: Balanced hereditary response curve. Baseline gene-environment adaptation parameters are nominal." | |
| ) | |
| if not output_report: | |
| return "⚠️ System Standby: Please upload a valid fingerprint image matrix or input a genomic string sequence to initialize the bio-identity sequence." | |
| return output_report | |
| # --- Tab 4: Cardio-Pulse AI Lab Logic --- | |
| 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"} | |
| ] | |
| def load_random_cardio_sample(): | |
| 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 "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 "SAD" in neuro_status: | |
| score += 15 | |
| fusion_notes = "⚠️ Neuro-Cardiovascular Strain Active: Suppressed neural states are causing autonomic vasoconstriction, compounding vascular vulnerability indices.\n" | |
| elif "HAPPY" in neuro_status: | |
| score -= 5 | |
| fusion_notes = "🟢 Neuro-Protective Balance Active: High vagal tone and positive neurological signals are actively 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): | |
| 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) | |
| API_URL = "https://api-inference.huggingface.co/models/google/gemma-1.1-7b-it" | |
| headers = {"Authorization": f"Bearer {os.getenv('HF_TOKEN', '')}"} | |
| prompt = f""" | |
| [⚡ System: Advanced AI Cardiovascular Specialist. Neuro-Cardio Fusion Active.] | |
| Secure ID: {patient_id} | Neurological Environmental State: {neuro_status} | |
| Biomarkers: Age {age}, BP {bps} mmHg, Chol {cholesterol} mg/dL, MaxHR {max_hr} bpm, Smoker: {smoking}, Diabetes: {diabetes}. | |
| Risk Score: {risk_pct}% ({status}). | |
| Provide a professional, concise clinical interpretability report in English. Detail how the intersection of these physical biomarkers and the patient's current neurological stress levels drive this risk score. Outline 3 structured preventative recommendations. Keep it sharp and high-level. | |
| """ | |
| payload = {"inputs": prompt, "parameters": {"max_new_tokens": 250, "temperature": 0.2}} | |
| try: | |
| response = requests.post(API_URL, headers=headers, json=payload) | |
| output = response.json() | |
| if isinstance(output, list) and "generated_text" in output[0]: | |
| report = output[0]["generated_text"].replace(prompt, "").strip() | |
| else: | |
| report = f"Analysis complete for Patient {patient_id}. System metrics indicate a {status} posture. Maintain optimized vascular control loops." | |
| except: | |
| report = f"Clinical Engine Online. Neural Stress Context Integrated. Raw Risk Factor: {risk_pct}%. Optimize biomarkers to scale down endothelial pressure." | |
| 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 | |
| # --- Tab 5: AI Robotic Surgeon Simulator Logic --- | |
| 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 "CTGA" in dna_text: | |
| anesthesia = "Elevated Sedative Profile (FKBP5 Cortisol Mutation Detected)" | |
| if "SAD" in neuro_text or "Suppressed" in neuro_text: | |
| occlusion += 10 | |
| if "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): | |
| surgical_id = hashlib.sha256(f"Surgeon-{artery}-{occlusion}".encode()).hexdigest()[:12].upper() | |
| warnings = [] | |
| if "COL1A1" in dna_context or "AATG" in 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." | |
| API_URL = "https://api-inference.huggingface.co/models/google/gemma-1.1-7b-it" | |
| headers = {"Authorization": f"Bearer {os.getenv('HF_TOKEN', '')}"} | |
| prompt = f""" | |
| [⚡ System: Autonomous AI Robotic Surgeon Directive. Operating Theater Matrix Active.] | |
| Surgical ID: {surgical_id} | Target Site: {artery} | Pre-Op Occlusion: {occlusion}% | |
| Anesthetic Control: {anesthesia} | |
| Multi-Modal Intelligence Context: | |
| - Genomics: {dna_context[:150]} | |
| - Neuro/EEG: {neuro_context[:100]} | |
| - Cardio Metrics: {cardio_context[:150]} | |
| Generate a highly advanced, structured 4-step Surgical Procedure Protocol in English for a Percutaneous Coronary Intervention (PCI / Stenting). Include catheter entry, balloon expansion parameters adjusted for the patient's specific genetic/neural vulnerabilities, and post-stent endothelial optimization steps. Keep it professional, strict, and dense. | |
| """ | |
| payload = {"inputs": prompt, "parameters": {"max_new_tokens": 300, "temperature": 0.15}} | |
| try: | |
| response = requests.post(API_URL, headers=headers, json=payload) | |
| output = response.json() | |
| if isinstance(output, list) and "generated_text" in output[0]: | |
| surgical_plan = output[0]["generated_text"].replace(prompt, "").strip() | |
| else: | |
| surgical_plan = f"Robotic Surgical System calibrated successfully for ID {surgical_id}. Deployment loops verified. Ready for micro-catheter intervention." | |
| except: | |
| surgical_plan = f"Autonomous Surgical System Online. Navigation vectors calculated for {artery} at {occlusion}% blockage. Proceeding under automated biometric safeguards." | |
| telemetry_output = f"🏥 OPERATING THEATER TELEMETRY:\n==============================\n▶️ Session Cipher: OR-{surgical_id}\n▶️ Target Vessel: {artery}\n▶️ Calculated Tissue Density: {(occlusion*1.2):.1f} HU\n▶️ System Autonomy Level: Level 4 Autonomous Robotic Assured\n\n[CRITICAL ALERTS & SAFEGUARDS]\n{warning_text}" | |
| return telemetry_output, surgical_plan | |
| # ========================================== | |
| # 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); } | |
| .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. It maps diagnostic results with leading global dermatological compounds and established clinical routines.", elem_classes="tab-instruction") | |
| with gr.Row(): | |
| with gr.Column(scale |