# 🧬 Sirona AI — Clinical Triage & Guidance Assistant

Sirona AI is a startup-grade, high-fidelity Clinical AI Triage, differential diagnostic, and health guidance platform. Built using vanilla web technologies, Sirona AI integrates state-of-the-art LLM interfaces, smart diagnostic routing, offline sandboxing, and a premium glassmorphic UI to assist users in understanding symptoms, determining clinical urgency, and locating first-aid support.

---

## 🚀 Key Features

### 🩺 Clinical AI & Multimodal Triage
* **Llama-4 Scout Engine**: Connected to Groq's high-speed endpoint (`meta-llama/llama-4-scout-17b-16e-instruct`), cross-referencing global clinical databases including PubMed, OpenFDA, WHO, CDC, ICD-11, SNOMED CT, RxNorm, and DailyMed.
<<<<<<< HEAD
* **Multimodal Visual Logging**: Secure base64 file processing for vision-language analysis, allowing users to upload images of physical symptom sites (e.g., skin rashes, eye redness, cuts) directly in browser memory.
* **Lab-Aesthetic Triage Dossier**: Custom rendering of structured clinical triage reports showing diagnostic indicators, urgency scaling, differential diagnosis trees, contraindications, and confidence metrics.
* **Prescription Exports**: One-click professional print stylesheet formatting, clean A4 PDF rendering (via `HTML2PDF.js`), formatted email dispatch, and instant WhatsApp sharing. Includes a prominent, high-contrast disclaimer (**Avoid: making legal or medical decisions**) that renders seamlessly in both web and PDF formats.

### 📋 Smart Diagnostic Bridging
* **Automated Quiz Redirect**: Instantly flags brief descriptions (e.g., "stomach pain" or "chest tight") and redirects users to the appropriate category quiz.
* **Category-Based Triage Quizzes**: 8-question clinical assessment flows across 9 vital sectors (Neuro, Breath, Skin, Gut, Fever, etc.) to extract detailed patient history.
* **Quiz-to-Report Bridge**: Auto-bridges quiz answers back to the homepage and programmatically submits them behind the scenes to generate a comprehensive clinical triage report.
=======
* **Multimodal Visual Logging**: Secure base64 file processing for vision-language analysis, allowing users to upload high-definition images of physical symptom sites (e.g., skin rashes, eye redness, cuts).
* **Lab-Aesthetic Reports**: Custom rendering of structured clinical triage dossiers showing diagnostic indicators, urgency scaling, differential diagnosis trees, contraindications, and confidence metrics.
* **Prescription Exports**: One-click professional print stylesheet formatting, clean A4 PDF rendering (via `HTML2PDF.js`), formatted email dispatch, and instant WhatsApp sharing.

### 📋 Smart Diagnostic Bridging
* **Automated Quiz Redirect**: Instantly flags brief descriptions (e.g., "stomach pain" or "chest tight") and redirects users to the appropriate category quiz.
* **Category-Based Triage Quizzes**: 8-question clinical assessment flows across 9 vital sectors (Neuro, Breath, Skin, Gut, Fever, etc.) to extract patient history.
* **Quiz-to-Report Bridge**: Auto-bridges quiz answers back to the homepage and programmatically submits them behind the scenes to output a complete clinical triage report.
>>>>>>> 4a4e4108ecdc92f1a8e7d8c397c44146414a4d31

### 🚑 Emergency Safety & SOS Guide
* **First-Aid SOS Manuals**: Quick first-aid guide card search index covering 15+ acute protocols (CPR, Choking, Anaphylaxis, Venomous Bites, Heatstrokes) with direct calling options.
* **Interactive 2D Body Map**: Multi-select front/back SVG panels to map discomfort zones visually.
* **Post-Report Success Popup & Toolkit**: Shrunk to `440px` with a custom glowing border and a 5-second countdown progress bar that automatically pauses on button hover or click, directing users to wellbeing tools.

<<<<<<< HEAD
### 🧘 AI Wellbeing Companion & Mindfulness
* **Empathetic Emotional Support**: Conversational companion modal providing active-listening validation and stress coping strategies (e.g., 4-7-8 breathing techniques).
* **ElevenLabs TTS Integration**: Empathetic, realistic speech synthesis audio streams synced to a pulsing wave-rippling avatar canvas ring.
* **Ambient Audio Synth**: Native dynamically synthesized client-side audio drones and ambient relaxing soundscapes (binaural beats, rain, ocean) with customizable mixer channels.

### ✨ Stigma-Free Early Detection & Advocacy
* **Taboo Health Directory (`awareness.html`)**: A private, non-judgmental library covering highly stigmatized or ignored conditions (Reproductive Health/RTIs, Mental Health Crises, Gastrointestinal metric shifts, and Neglected Tropical Diseases like early-stage Leprosy).
* **Three-Tiered Content Architecture**: Every condition is broken down into clinical societal context, specific early warning tracking signs (like the ABCDE mole matrix or hypopigmented patch sensation testing), and immediate curability/action pathways.
=======
### 🧘 AI Wellbeing Companion
* **Empathetic Emotional Support**: Conversational companion modal providing active-listening validation and stress coping strategies (e.g., 4-7-8 breathing techniques).
* **ElevenLabs TTS Integration**: Empathetic, realistic speech synthesis audio streams synced to a pulsing wave-rippling avatar canvas ring.

### ✨ Stigma-Free Early Detection & Advocacy
* **Taboo Health Directory (`awareness.html`)**: A private, non-judgmental library covering highly stigmatized or ignored conditions (Reproductive Health/RTIs, Mental Health Crises, Gastrointestinal metric shifts, and Neglected Tropical Diseases like early-stage Leprosy).
* **Three-Tiered Content Architecture**: Every condition is broken down into clinical societal context, specific early warning tracking signs (like the ABCDE mole matrix or hypopigmented patch sensation testing), and immediate curability/action pathways to bypass social anxiety or village ostracization.
>>>>>>> 4a4e4108ecdc92f1a8e7d8c397c44146414a4d31
* **Contextual Safety Search**: Built-in header search targeting hidden symptoms directly, offering a safe space for private educational exploration before engaging an active AI consultation.

---

## 🛠️ Technical Stack & Client Libraries

* **Core Structure**: Vanilla HTML5 (semantic structure, unique interactive IDs, SVG paths).
* **Styling System**: Vanilla CSS3 Custom Properties (variables) facilitating real-time light/dark theme toggles, hardware-accelerated animations (`scale`, `translate3d`, `blur`), and premium glassmorphic frosted layouts.
* **Logic Engine**: Native JavaScript (ES6+ async/await, modular event handlers, local storage states, and local fallback triage dictionaries).
* **Client-Side Libraries**:
<<<<<<< HEAD
  * **Chart.js**: Client-side analytics rendering, mapping consultation velocity, symptoms distributions, and latency metrics in `dashboard.html`.
=======
  * **Chart.js**: Client-side analytics rendering for judges, mapping consultation velocity, symptoms distributions, and latency metrics in `dashboard.html`.
>>>>>>> 4a4e4108ecdc92f1a8e7d8c397c44146414a4d31
  * **HTML2PDF.js**: Client-side PDF generation converting styled HTML containers directly into print-ready PDF files.
  * **Lottie-web**: SVG-based animation engine playing splash screen logos.

---

## 🗄️ Database & Storage Architecture

### Firebase Firestore Collections
Sirona AI uses a hierarchical Firestore database model with offline-first client synchronization:
1. **`users/{uid}`**:
   * Stores user profile metadata, language selection, country details, and emergency Medical ID records (Age, Blood Type, Allergies, Medications, emergency contacts).
2. **`users/{uid}/consultations`**:
   * Stores historical differential diagnostic reports, SNOMED CT tags, ICD-11 codes, pain severity, and medication interaction summaries.
3. **`users/{uid}/symptom_logs`**:
   * Stores daily health indicators (temperature, pulse, symptom checkboxes, mood index, pain rating) for time-series analytics.

### Local Caching & State Sandboxing
When running offline or as a guest, the application switches to `localStorage` caches:
* `sirona_user`: Active auth session cache.
* `sirona_theme`: Current theme state (`dark` or `light`).
* `sirona_symptom_logs`: Offline time-series history log backup.
* `sirona_brief_form_state`: Form preservation state before quiz redirection.
* `sirona_care_wall_notes` / `sirona_liked_notes`: Persistent care support notes.
* `sirona_health_checklist`: Stored bookmarks of clinical goals from `awareness.html`.

---

## 🔌 Third-Party API Integrations

### 1. Groq Chat Completions API
* **Endpoint**: `https://api.groq.com/openai/v1/chat/completions`
* **Model**: `meta-llama/llama-4-scout-17b-16e-instruct`
* **Request Payload**:
  ```json
  {
    "model": "meta-llama/llama-4-scout-17b-16e-instruct",
    "messages": [
      { "role": "system", "content": "SYSTEM_CLINICAL_PROMPT" },
      { "role": "user", "content": "USER_SYMPTOM_DATA_OR_BASE64_IMAGE" }
    ],
    "temperature": 0.15,
    "max_tokens": 2048,
    "response_format": { "type": "json_object" }
  }
  ```

### 2. ElevenLabs Text-to-Speech API
* **Endpoint**: `https://api.elevenlabs.io/v1/text-to-speech/{voiceId}`
* **Model**: `eleven_monolingual_v1`
* **Request Payload**:
  ```json
  {
    "text": "EMPATHETIC_COMPANION_RESPONSE",
    "model_id": "eleven_monolingual_v1",
    "voice_settings": {
      "stability": 0.5,
      "similarity_boost": 0.75
    }
  }
  ```

---

## 🛡️ Clinical Safety & Shield System

<<<<<<< HEAD
Sirona AI implements a multi-tier safety validation framework operating *before* and *during* API execution, preventing inappropriate usage and safeguarding users during crises.
=======
Sirona AI implements a three-tier safety validation framework operating *before* API payloads are generated, preventing inappropriate usage and safeguarding users during crises.
>>>>>>> 4a4e4108ecdc92f1a8e7d8c397c44146414a4d31

### 1. Real-time Prompt Safety Verification
A real-time parser monitors the symptom description field (`#symptoms`) as the user types and intercepts form submission:

* **Category A: Dangerous / Critical Emergency Prompts**:
  * **Keywords Caught**: `"suicide"`, `"end my life"`, `"end it"`, `"kill myself"`, `"overdose"`, `"massive chest crushing pain"`, `"cannot breathe"`, `"severe bleeding"`, `"suicidal"`, `"self harm"`, and related self-harm/trauma markers.
  * **Real-time Behavior**: Displays a high-contrast **red warning box** inline under the input field, disables the submit button, changes the label to `"Emergency Blocked"`, and prevents any API report generation.
  * **Submission Behavior**: If triggered, overlays a full-screen, non-dismissible emergency danger card (`#emergency-danger-overlay`) completely overriding the chat/form view, clears all inputs for safety, and displays one-click regional hotline call buttons (911, 112, 988, SMS 741741).
  * **Warning Text**: 
    > 🚨 Immediate Human Intervention Required. Sirona AI has detected an emergency signature. If you are experiencing a life-threatening crisis or severe emotional distress, please step away from this software and connect with professional care immediately.

* **Category B: Irrelevant / Off-Topic Queries**:
  * **Keywords Caught**: Code keywords (`"python"`, `"javascript"`, `"coding"`, `"write a script"`), sports (`"won the match"`, `"match score"`), general knowledge, weather, etc.
  * **Behavior**: Blocks report generation, shows an inline blue/indigo system message card (`#symptom-warning-box.off-topic`) in the form stream, and prevents analysis.
  * **Warning Text**: 
    > 🤖 Platform Scope Restriction: Sirona AI is dedicated exclusively to medical triage, early health indicators, and wellness education. I am unable to answer general or non-medical questions. Please enter a symptom or health-related query to proceed.

* **Category C: Extremely Vague / Fragmented Inputs**:
  * **Keywords Caught**: Single-word inputs or phrases without clinical indicators (e.g. `"help"`, `"pain"`, `"sick"`, `"unwell"`).
  * **Behavior**: Blocks report generation and displays an orange inline context helper card (`#symptom-warning-box.vague`) to teach the user how to describe their symptom profile.
  * **Warning Text**: 
    > 📝 More Context Needed: To provide an accurate urgency score or education, I need a bit more detail. Please describe where the discomfort is located, how long you've felt it, and any other secondary signs.

### 2. Triage Urgency Safety Lockdown
<<<<<<< HEAD
If a diagnostic report returns an Urgency Score `>= 60` or `action_required == "EMERGENCY_OVERRIDE"`, Sirona AI triggers a systemic lockdown overlay:
=======
If a diagnostic report returns an Urgency Score `>= 7.5` or `action_required == "EMERGENCY_OVERRIDE"`, Sirona AI triggers a systemic lockdown overlay:
>>>>>>> 4a4e4108ecdc92f1a8e7d8c397c44146414a4d31
* Disables the main inputs and blocks subsequent diagnostic requests.
* Establishes a sticky, non-dismissible warning card containing direct emergency dial hotlines.
* Starts a 30-minute countdown safety contact window to encourage immediate offline professional medical consultation.

### 3. Wellbeing Companion Safety Override
The AI Wellbeing companion chatbot dynamically monitors text conversations. If the user mentions crisis or self-harm keywords, the modal companion screen is automatically closed and the system triggers the full clinical safety lockdown immediately.

### 4. AI Clinical Safety Safeguards
Sirona AI utilizes several structural and programmatic mechanisms to guarantee that its core clinical artificial intelligence runs safely:
* **Low-Temperature Hallucination Shield**: Configured with a low temperature parameter of `0.15` in API call payloads to minimize probabilistic variance and guarantee highly predictable, conservative clinical triages.
* **Strict Clinical System Prompt**: Enforces a strict system prompt that instructs the engine to cross-reference established databases, identify contraindications, avoid prescribing specific pharmaceutical brands, outline immediate emergency indications, and disclaim that it is a triage assistant rather than a primary medical provider.
* **Local Visual Privacy Processing**: Vision-based images uploaded by the user are processed as ephemeral base64-encoded strings held strictly in local browser memory and sent over secure TLS connections, bypassing permanent remote database indexing to protect user medical confidentiality.
* **Fail-Safe Fallback Engine**: If the device experiences network latency or falls offline, the application instantly routes symptoms to a local key-matching emergency dictionary rather than throwing an interface error, preserving essential triage accessibility.

---

## 🚀 Quick Start (Local Deployment)

Sirona AI operates serverless-ready and runs directly in browser sandboxes. To enable full Progressive Web App (PWA) cache syncs and service workers:

```bash
# Using Python
python -m http.server 8080

# Or Node.js
npx http-server -p 8080
```
Then navigate to **http://localhost:8080** in your web browser.
<<<<<<< HEAD

### 📂 Directory & File Structure
* [`index.html`](file:///c:/Projects/AiDoc/index.html) / [`script.js`](file:///c:/Projects/AiDoc/script.js) / [`style.css`](file:///c:/Projects/AiDoc/style.css) — Main client-side interface and core script engine.
* [`env.js`](file:///c:/Projects/AiDoc/env.js) — Environment credentials setup and local key storage handlers.
* [`analytics.js`](file:///c:/Projects/AiDoc/analytics.js) — Telemetry tracking and dashboard script connector.
* [`mobile-nav.js`](file:///c:/Projects/AiDoc/mobile-nav.js) — Mobile & desktop navigation drawer, injected dynamically on all pages.
* [`sw.js`](file:///c:/Projects/AiDoc/sw.js) / [`manifest.json`](file:///c:/Projects/AiDoc/manifest.json) — PWA service worker and mobile installer package assets.
* [`awareness.html`](file:///c:/Projects/AiDoc/awareness.html) — Stigma-Free Health Awareness Directory, Support Wall, and Stigma Quiz.
* [`faq.html`](file:///c:/Projects/AiDoc/faq.html) — Clinical FAQ backup file.
* [**`report/`**](file:///c:/Projects/AiDoc/report) — Structured clinical assessment report files:
  * [`report.html`](file:///c:/Projects/AiDoc/report/report.html) — UI framework for dynamic assessment reports and follow-up consultation chat.
  * [`report.js`](file:///c:/Projects/AiDoc/report/report.js) — Orchestrates dynamic clinical prompts, Groq differential analyses, Firestore syncing, and client-side PDF downloads.
* [**`legal/`**](file:///c:/Projects/AiDoc/legal) — Unified legal and compliance documents folder:
  * [`legal.html`](file:///c:/Projects/AiDoc/legal/legal.html) — Unified legal center, providing Terms, Privacy, and FAQ in a tabbed, context-aware interface.
  * [`terms.html`](file:///c:/Projects/AiDoc/legal/terms.html) — Terms and Conditions, updated with AI Guardrails and Human-in-the-Loop provisions.
  * [`privacy.html`](file:///c:/Projects/AiDoc/legal/privacy.html) — GDPR-compliant user health telemetry privacy policy.
* [**`quiz/`**](file:///c:/Projects/AiDoc/quiz) — Advanced category triage quiz pages:
  * [`diagnosis-quiz.html`](file:///c:/Projects/AiDoc/quiz/diagnosis-quiz.html) — Multi-step interactive quiz UI.
  * [`quiz.js`](file:///c:/Projects/AiDoc/quiz/quiz.js) — Handles scoring, navigation, and automatic homepage report bridge.
  * [`questions.js`](file:///c:/Projects/AiDoc/quiz/questions.js) — Structured question sets covering vital symptoms.
* [**`tracker/`**](file:///c:/Projects/AiDoc/tracker) — Chronic symptom monitoring files:
  * [`tracker.html`](file:///c:/Projects/AiDoc/tracker/tracker.html) — Daily symptom logger interface.
  * [`tracker.js`](file:///c:/Projects/AiDoc/tracker/tracker.js) — Graph and time-series logic using Chart.js.
* [**`wellbeing/`**](file:///c:/Projects/AiDoc/wellbeing) — Mindfulness and emotional companion tools:
  * [`wellbeing.html`](file:///c:/Projects/AiDoc/wellbeing/wellbeing.html) — Companion chat interface and ambient audio mixer panels.
  * [`wellbeing.js`](file:///c:/Projects/AiDoc/wellbeing/wellbeing.js) — Script managing personality states, Web Audio syntheses, and ElevenLabs API hooks.
* [**`account/`**](file:///c:/Projects/AiDoc/account) — User authentication and configuration:
  * [`login.html`](file:///c:/Projects/AiDoc/account/login.html) / [`login.js`](file:///c:/Projects/AiDoc/account/login.js) — Firebase OAuth and Guest credentials access flows.
  * [`onboarding.html`](file:///c:/Projects/AiDoc/account/onboarding.html) — Interactive onboarding slider for theme, language, and country setup.
  * [`profile.html`](file:///c:/Projects/AiDoc/account/profile.html) / [`profile.js`](file:///c:/Projects/AiDoc/account/profile.js) — Emergency Medical ID management and QR code generator.
* [**`sos/`**](file:///c:/Projects/AiDoc/sos) — standard clinical first-aid manuals (CPR, severe bleeding, choking, stroke, venomous bites, asthma attacks, etc.).
=======
>>>>>>> 4a4e4108ecdc92f1a8e7d8c397c44146414a4d31
