Update app.py
#1
by Lina324 - opened
app.py
CHANGED
|
@@ -99,4 +99,231 @@ def analyze_and_respond_eeg(file):
|
|
| 99 |
desc = f"Suppressed neural emotional frequency identified (Mean Value: {avg_val:.4f}). Generating an acoustic counter-balance 324Hz frequency to stimulate emotional regulation."
|
| 100 |
else:
|
| 101 |
label, color, freq = "NEUTRAL", "#95a5a6", 432
|
| 102 |
-
desc = f"System resting baseline homeostasis detected (Mean Value: {avg_val:.4f}). Emitting the
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
desc = f"Suppressed neural emotional frequency identified (Mean Value: {avg_val:.4f}). Generating an acoustic counter-balance 324Hz frequency to stimulate emotional regulation."
|
| 100 |
else:
|
| 101 |
label, color, freq = "NEUTRAL", "#95a5a6", 432
|
| 102 |
+
desc = f"System resting baseline homeostasis detected (Mean Value: {avg_val:.4f}). Emitting the universal 432Hz mathematical tuning frequency for neuro-auditory stabilization."
|
| 103 |
+
|
| 104 |
+
fig, ax = plt.subplots(figsize=(2.5, 2.5), dpi=150)
|
| 105 |
+
ax.add_patch(plt.Rectangle((0, 0), 1, 1, color=color, linewidth=0))
|
| 106 |
+
ax.set_title(f"STATE: {label}", fontsize=14, fontweight='bold', color=color)
|
| 107 |
+
ax.axis('off')
|
| 108 |
+
fig.patch.set_alpha(0)
|
| 109 |
+
|
| 110 |
+
audio = generate_healing_audio(4, freq)
|
| 111 |
+
return fig, audio, f"Detection Suite: {label}", desc
|
| 112 |
+
except Exception as e:
|
| 113 |
+
return None, None, "System Execution Failure", f"Signal processing failed due to architectural exception: {str(e)}"
|
| 114 |
+
|
| 115 |
+
# --- Tab 3: Biometrics & Genomics Processing Logic ---
|
| 116 |
+
def analyze_genetics_and_biometrics(fingerprint, dna_seq):
|
| 117 |
+
output_report = ""
|
| 118 |
+
if fingerprint is not None:
|
| 119 |
+
patterns = ["Whorls (Analytical Profile)", "Loops (Adaptive/Executive Profile)", "Arches (Creative/Philosophical Profile)"]
|
| 120 |
+
detected_pattern = random.choice(patterns)
|
| 121 |
+
|
| 122 |
+
historical_matches = {
|
| 123 |
+
"Whorls (Analytical Profile)": "Albert Einstein (Correlation: 89.4%). Characterized by high-density structural and analytical neuro-processing pathways.",
|
| 124 |
+
"Loops (Adaptive/Executive Profile)": "Leonardo da Vinci (Correlation: 91.2%). Characterized by cross-disciplinary cognitive flexibility and cognitive synthesis.",
|
| 125 |
+
"Arches (Creative/Philosophical Profile)": "Nikola Tesla (Correlation: 86.7%). Characterized by acute divergent spatial thinking and heightened intuitive ideation."
|
| 126 |
+
}
|
| 127 |
+
output_report += (
|
| 128 |
+
f"🔬 [BIOMETRIC ARCHETYPE MATCHING]\n"
|
| 129 |
+
f"▪️ Identified Morphological Pattern: {detected_pattern}\n"
|
| 130 |
+
f"▪️ Historical Database Match: {historical_matches[detected_pattern]}\n\n"
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
if dna_seq:
|
| 134 |
+
clean_dna = dna_seq.strip().upper()
|
| 135 |
+
output_report += "🧬 [BIOINFORMATICS GENOMIC ANALYSIS]\n"
|
| 136 |
+
|
| 137 |
+
if "AATG" in clean_dna:
|
| 138 |
+
output_report += (
|
| 139 |
+
"▪️ Genomic Marker: Target subsequence localized on the COL1A1 gene locus.\n"
|
| 140 |
+
"▪️ Phenotypic Correlation: Superior hereditary capacity for endogenous collagen synthesis. Strong dermal matrix resilience against cellular oxidative stress."
|
| 141 |
+
)
|
| 142 |
+
elif "CTGA" in clean_dna:
|
| 143 |
+
output_report += (
|
| 144 |
+
"▪️ Genomic Marker: Functional variation isolated within the FKBP5 gene locus (Stress Response Modulator).\n"
|
| 145 |
+
"▪️ Psychodermatology Integration: High genetic susceptibility to cortisol-driven epidermal barrier degradation. "
|
| 146 |
+
"Hereditary pathways indicate that localized skin cell inflammation can be actively triggered by the neural distress states "
|
| 147 |
+
"monitored in the Neuro-Pulse suite. Immediate synergy protocol recommended: Integrate specialized barrier repair formulas "
|
| 148 |
+
"(containing Ceramides and Centella Asiatica) with the system's generated 324Hz/432Hz bio-acoustic sound waves to suppress adrenal stress cues."
|
| 149 |
+
)
|
| 150 |
+
else:
|
| 151 |
+
output_report += (
|
| 152 |
+
"▪️ Genomic Marker: Full sequence parsing executed successfully. No high-sensitivity polymorphic variants isolated.\n"
|
| 153 |
+
"▪️ Phenotypic Correlation: Balanced hereditary response curve. Baseline gene-environment adaptation parameters are nominal."
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
if not output_report:
|
| 157 |
+
return "⚠️ System Standby: Please upload a valid fingerprint image matrix or input a genomic string sequence to initialize the bio-identity sequence."
|
| 158 |
+
return output_report
|
| 159 |
+
|
| 160 |
+
# --- Tab 4: Cardio-Pulse AI Lab Logic ---
|
| 161 |
+
AUTHENTIC_CARDIO_SAMPLES = [
|
| 162 |
+
{"age": 63, "bps": 145, "chol": 233, "max_hr": 150, "smoke": "Yes", "diabetes": "Yes"},
|
| 163 |
+
{"age": 37, "bps": 130, "chol": 250, "max_hr": 187, "smoke": "No", "diabetes": "No"},
|
| 164 |
+
{"age": 56, "bps": 120, "chol": 236, "max_hr": 178, "smoke": "No", "diabetes": "No"},
|
| 165 |
+
{"age": 67, "bps": 160, "chol": 286, "max_hr": 108, "smoke": "Yes", "diabetes": "Yes"}
|
| 166 |
+
]
|
| 167 |
+
|
| 168 |
+
def load_random_cardio_sample():
|
| 169 |
+
sample = random.choice(AUTHENTIC_CARDIO_SAMPLES)
|
| 170 |
+
return sample["age"], sample["bps"], sample["chol"], sample["max_hr"], sample["smoke"], sample["diabetes"]
|
| 171 |
+
|
| 172 |
+
def sync_with_neuro_suite(neuro_status_text):
|
| 173 |
+
if "SAD" in neuro_status_text or "Suppressed" in neuro_status_text:
|
| 174 |
+
return 145, 135, "Yes"
|
| 175 |
+
elif "HAPPY" in neuro_status_text:
|
| 176 |
+
return 115, 155, "No"
|
| 177 |
+
else:
|
| 178 |
+
return 120, 140, "No"
|
| 179 |
+
|
| 180 |
+
def calculate_cardio_risk(age, bps, cholesterol, max_hr, smoking, diabetes, neuro_status):
|
| 181 |
+
score = 0
|
| 182 |
+
fusion_notes = ""
|
| 183 |
+
if "SAD" in neuro_status:
|
| 184 |
+
score += 15
|
| 185 |
+
fusion_notes = "⚠️ Neuro-Cardiovascular Strain Active: Suppressed neural states are causing autonomic vasoconstriction, compounding vascular vulnerability indices.\n"
|
| 186 |
+
elif "HAPPY" in neuro_status:
|
| 187 |
+
score -= 5
|
| 188 |
+
fusion_notes = "🟢 Neuro-Protective Balance Active: High vagal tone and positive neurological signals are actively stabilizing endothelial resilience.\n"
|
| 189 |
+
|
| 190 |
+
if age > 50: score += 20
|
| 191 |
+
elif age > 35: score += 10
|
| 192 |
+
if bps > 140: score += 25
|
| 193 |
+
elif bps > 120: score += 12
|
| 194 |
+
if cholesterol > 240: score += 25
|
| 195 |
+
elif cholesterol > 200: score += 10
|
| 196 |
+
if max_hr < 120: score += 15
|
| 197 |
+
if smoking == "Yes": score += 15
|
| 198 |
+
if diabetes == "Yes": score += 15
|
| 199 |
+
|
| 200 |
+
risk_percentage = min(max(score, 5), 95)
|
| 201 |
+
status = "High Risk (🔴)" if risk_percentage >= 60 else "Moderate Risk (🟡)" if risk_percentage >= 30 else "Low Risk (🟢)"
|
| 202 |
+
return risk_percentage, status, fusion_notes
|
| 203 |
+
|
| 204 |
+
def generate_cardio_privacy_hash(age, bps, cholesterol):
|
| 205 |
+
raw_str = f"Cardio-{age}-{bps}-{cholesterol}"
|
| 206 |
+
return hashlib.sha256(raw_str.encode()).hexdigest()[:16] + "... (Secured)"
|
| 207 |
+
|
| 208 |
+
def analyze_cardio_pipeline(age, bps, cholesterol, max_hr, smoking, diabetes, neuro_status):
|
| 209 |
+
patient_id = generate_cardio_privacy_hash(age, bps, cholesterol)
|
| 210 |
+
risk_pct, status, fusion_notes = calculate_cardio_risk(age, bps, cholesterol, max_hr, smoking, diabetes, neuro_status)
|
| 211 |
+
|
| 212 |
+
API_URL = "https://api-inference.huggingface.co/models/google/gemma-1.1-7b-it"
|
| 213 |
+
headers = {"Authorization": f"Bearer {os.getenv('HF_TOKEN', '')}"}
|
| 214 |
+
|
| 215 |
+
prompt = f"""
|
| 216 |
+
[⚡ System: Advanced AI Cardiovascular Specialist. Neuro-Cardio Fusion Active.]
|
| 217 |
+
Secure ID: {patient_id} | Neurological Environmental State: {neuro_status}
|
| 218 |
+
Biomarkers: Age {age}, BP {bps} mmHg, Chol {cholesterol} mg/dL, MaxHR {max_hr} bpm, Smoker: {smoking}, Diabetes: {diabetes}.
|
| 219 |
+
Risk Score: {risk_pct}% ({status}).
|
| 220 |
+
|
| 221 |
+
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.
|
| 222 |
+
"""
|
| 223 |
+
|
| 224 |
+
payload = {"inputs": prompt, "parameters": {"max_new_tokens": 250, "temperature": 0.2}}
|
| 225 |
+
try:
|
| 226 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
| 227 |
+
output = response.json()
|
| 228 |
+
if isinstance(output, list) and "generated_text" in output[0]:
|
| 229 |
+
report = output[0]["generated_text"].replace(prompt, "").strip()
|
| 230 |
+
else:
|
| 231 |
+
report = f"Analysis complete for Patient {patient_id}. System metrics indicate a {status} posture. Maintain optimized vascular control loops."
|
| 232 |
+
except:
|
| 233 |
+
report = f"Clinical Engine Online. Neural Stress Context Integrated. Raw Risk Factor: {risk_pct}%. Optimize biomarkers to scale down endothelial pressure."
|
| 234 |
+
|
| 235 |
+
metrics_summary = f"🛡️ Patient Privacy ID: {patient_id}\n🫀 Integrated Cardio Risk Score: {risk_pct}%\n📊 Evaluation: {status}\n\n{fusion_notes}"
|
| 236 |
+
return metrics_summary, report
|
| 237 |
+
|
| 238 |
+
# --- Tab 5: AI Robotic Surgeon Simulator Logic ---
|
| 239 |
+
def meld_and_sync_all_data(dna_text, neuro_text, cardio_metrics_text):
|
| 240 |
+
target_artery = "Left Coronary Artery (LCA)"
|
| 241 |
+
occlusion = 70
|
| 242 |
+
anesthesia = "Standard Propofol Titration Profile"
|
| 243 |
+
|
| 244 |
+
if "CTGA" in dna_text:
|
| 245 |
+
anesthesia = "Elevated Sedative Profile (FKBP5 Cortisol Mutation Detected)"
|
| 246 |
+
if "SAD" in neuro_text or "Suppressed" in neuro_text:
|
| 247 |
+
occlusion += 10
|
| 248 |
+
if "High Risk" in cardio_metrics_text:
|
| 249 |
+
occlusion = max(occlusion, 85)
|
| 250 |
+
|
| 251 |
+
return target_artery, occlusion, anesthesia
|
| 252 |
+
|
| 253 |
+
def execute_surgical_simulation(artery, occlusion, anesthesia, dna_context, neuro_context, cardio_context):
|
| 254 |
+
surgical_id = hashlib.sha256(f"Surgeon-{artery}-{occlusion}".encode()).hexdigest()[:12].upper()
|
| 255 |
+
|
| 256 |
+
warnings = []
|
| 257 |
+
if "COL1A1" in dna_context or "AATG" in dna_context:
|
| 258 |
+
warnings.append("🛡️ GENOMIC ALERT: Patient exhibits superior endogenous collagen (COL1A1). Vessel elasticity is optimal. Standard balloon inflation pressure permitted.")
|
| 259 |
+
elif "FKBP5" in dna_context or "CTGA" in dna_context:
|
| 260 |
+
warnings.append("⚠️ GENOMIC WARNING: FKBP5 locus variation detected. Hyper-reactive cortisol tissue vulnerability. Risk of localized micro-inflammation. Reduce deployment velocity.")
|
| 261 |
+
|
| 262 |
+
if "High Risk" in cardio_context or occlusion >= 80:
|
| 263 |
+
warnings.append("🚨 SURGICAL RISK: Severe luminal reduction detected. High probability of calcified plaque rupture. Embolic protection filter deployment mandatory.")
|
| 264 |
+
|
| 265 |
+
if "SAD" in neuro_context:
|
| 266 |
+
warnings.append("🧠 NEUROLOGICAL ADVISORY: Autonomic instability detected via EEG. Patient baseline exhibits elevated sympathetic drive. Maintain continuous arterial pressure damping.")
|
| 267 |
+
|
| 268 |
+
warning_text = "\n".join(warnings) if warnings else "✅ Surgical telemetry nominal. No anomalous multi-modal alerts detected."
|
| 269 |
+
|
| 270 |
+
API_URL = "https://api-inference.huggingface.co/models/google/gemma-1.1-7b-it"
|
| 271 |
+
headers = {"Authorization": f"Bearer {os.getenv('HF_TOKEN', '')}"}
|
| 272 |
+
|
| 273 |
+
prompt = f"""
|
| 274 |
+
[⚡ System: Autonomous AI Robotic Surgeon Directive. Operating Theater Matrix Active.]
|
| 275 |
+
Surgical ID: {surgical_id} | Target Site: {artery} | Pre-Op Occlusion: {occlusion}%
|
| 276 |
+
Anesthetic Control: {anesthesia}
|
| 277 |
+
Multi-Modal Intelligence Context:
|
| 278 |
+
- Genomics: {dna_context[:150]}
|
| 279 |
+
- Neuro/EEG: {neuro_context[:100]}
|
| 280 |
+
- Cardio Metrics: {cardio_context[:150]}
|
| 281 |
+
|
| 282 |
+
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.
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
payload = {"inputs": prompt, "parameters": {"max_new_tokens": 300, "temperature": 0.15}}
|
| 286 |
+
try:
|
| 287 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
| 288 |
+
output = response.json()
|
| 289 |
+
if isinstance(output, list) and "generated_text" in output[0]:
|
| 290 |
+
surgical_plan = output[0]["generated_text"].replace(prompt, "").strip()
|
| 291 |
+
else:
|
| 292 |
+
surgical_plan = f"Robotic Surgical System calibrated successfully for ID {surgical_id}. Deployment loops verified. Ready for micro-catheter intervention."
|
| 293 |
+
except:
|
| 294 |
+
surgical_plan = f"Autonomous Surgical System Online. Navigation vectors calculated for {artery} at {occlusion}% blockage. Proceeding under automated biometric safeguards."
|
| 295 |
+
|
| 296 |
+
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}"
|
| 297 |
+
return telemetry_output, surgical_plan
|
| 298 |
+
|
| 299 |
+
# ==========================================
|
| 300 |
+
# 3. INTERACTIVE PLATFORM UI DESIGN (GRADIO)
|
| 301 |
+
# ==========================================
|
| 302 |
+
|
| 303 |
+
master_css = """
|
| 304 |
+
footer { visibility: hidden !important; }
|
| 305 |
+
.gradio-container { background-color: #f8fafc !important; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
|
| 306 |
+
.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; }
|
| 307 |
+
.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; }
|
| 308 |
+
.action-btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(16,185,129,0.3) !important; }
|
| 309 |
+
.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; }
|
| 310 |
+
.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; }
|
| 311 |
+
.surgeon-btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(239,68,68,0.3) !important; }
|
| 312 |
+
.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); }
|
| 313 |
+
.tab-instruction { margin-bottom: 15px; color: #475569; padding: 10px; border-left: 4px solid #10b981; background-color: #f8fafc; border-radius: 0 8px 8px 0; }
|
| 314 |
+
"""
|
| 315 |
+
|
| 316 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=master_css) as demo:
|
| 317 |
+
|
| 318 |
+
with gr.Column(elem_classes="master-header"):
|
| 319 |
+
gr.Markdown("# 🔬 Bio-Harmony & Advanced AI Multi-Modal Research Suite")
|
| 320 |
+
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")
|
| 321 |
+
|
| 322 |
+
with gr.Tabs():
|
| 323 |
+
|
| 324 |
+
# --- TAB 1: SKIN ANALYSIS ECOSYSTEM ---
|
| 325 |
+
with gr.TabItem("🧴 Dermacare AI Lab"):
|
| 326 |
+
gr.Markdown("### 🔍 Computer Vision Epidermal Classification & Clinical Formulation Matrix")
|
| 327 |
+
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")
|
| 328 |
+
with gr.Row():
|
| 329 |
+
with gr.Column(scale
|