# Project export: LiveWire: real-time AI cable prediction for safer cities

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: Cal Hacks 12.0
- Tagline: AI that predicts and prevents city cable failures with real-time alerts and a voice agent using live sensor data and map visualization
- Devpost: https://devpost.com/software/livewire
- GitHub: https://github.com/marianaisaw/LiveWire
- Demo: https://my-elasticsearch-project-c80e6e.kb.us-west1.gcp.elastic.cloud/app/r/s/uw5qC
- Video: https://www.youtube.com/embed/o_GlztPGVYU?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 2 GitHub contributor(s) — lavirox (39 commits), Julia (Juli) Huang (25 commits)

## Devpost submission (written by the team)

### Inspiration

The 2018 Camp Fire was California's deadliest wildfire, killing 85 people and destroying the town of Paradise. The tragedy started with a single degraded power line component — a 97-year-old transmission hook that failed and sparked the fire. What if we could have detected this failure 308 days in advance? This question drove our team to build LiveWire. We discovered that with the right AI models and real-time data, we could have provided grid operators with 308 days of advance warning — enough time to repair the component, prevent the fire, and save 85 lives. LiveWire is our answer to infrastructure disasters: an AI-powered "electrocardiogram" for power grids that monitors vital signs and predicts catastrophic failures before they happen.

### What it does

LiveWire is an intelligent infrastructure monitoring system that combines physics-based modeling with advanced machine learning to predict power grid failures. Our system operates on two critical fronts: 🔥 Component Degradation Detection 308-day advance warning for infrastructure disasters like the Camp Fire Real-time monitoring of equipment aging and degradation Physics-based risk assessment with interpretable results ⚡ Cascade Failure Prevention >92% accuracy in predicting network-wide blackouts ML model analysis of grid topology and load patterns using Gradient Boosting Early detection before one component's failure spreads across regions 🌐 Real-Time Monitoring Pipeline IoT sensor simulation (Raspberry Pi hardware) Elastic Serverless cloud infrastructure for data processing Interactive React dashboard with multi-city visualizations Live risk assessment with green/yellow/red alert zones Core Innovation: Unlike traditional approaches that rely purely on historical data, LiveWire combines real network topology with physics-based models, achieving breakthrough accuracy on real disaster scenarios.

### How we built it

AI & Machine Learning Foundation We developed multiple complementary models: Grid Risk Model: Physics-based component degradation analysis Enhanced Gradient Boosting model: Deep learning for cascade pattern recognition Hybrid Ensemble: Combines multiple algorithms for robustness Real-Time Data Architecture Built a complete producer-consumer pipeline: Hardware Layer: Raspberry Pi sensors collecting temperature, vibration, strain, and power metrics Cloud Layer: Elastic Serverless with Agent Builder for real-time data streaming Processing Layer: Python applications running AI models on live sensor data Visualization Layer: React frontend with Mapbox GL for geographic grid visualization Technology Stack Backend: Python 3.13, scikit-learn, PyTorch, NetworkX, Pandas Frontend: React 18.2, Mapbox GL, Framer Motion, Recharts Infrastructure: Elastic Serverless, REST APIs, Agent Builder Hardware: Raspberry Pi simulation with realistic sensor data Data Integration Innovation We created a sophisticated data pipeline that: Converts network topology into realistic time-series sensor data Simulates physics-based cascade propagation across grid networks Maintains clean train/test splits for rigorous validation Integrates real historical disaster data (2018 Camp Fire) with synthetic network models

### Challenges we ran into

1. Data Quality vs Accuracy Challenge Problem: We discovered that synthetic electrical fault data only achieved ~50% accuracy, far below real-world requirements. Solution: We pivoted to incorporate real historical disaster data and actual network topologies, which dramatically improved performance. This led to our key insight: "Real data >> synthetic data" — validating why IoT sensor deployment is essential. 2. Model Architecture Complexity Problem: Different failure types (component degradation vs cascades) required fundamentally different modeling approaches. Solution: We developed specialized models for each scenario: Physics-based interpretable models for component failures ML Gradient Boosting models for complex cascade pattern recognition Ensemble methods for robustness across failure types 3. Real-Time Integration at Scale Problem: Bridging from research models to production-ready real-time monitoring. Solution: Built a complete Elastic Serverless infrastructure with: Agent Builder framework for structured data ingestion Producer-consumer architecture for scalable processing Multiple dashboard options (Kibana enterprise + custom React frontend) 4. Validation on Historical Events Problem: How do you prove your model would have worked on past disasters? Solution: We carefully reconstructed the 2018 Camp Fire scenario using historical MODIS satellite data and proved our Grid Risk Model would have provided 308 days of advance warning.

### Accomplishments we're proud of

🏆 Breakthrough Performance Metrics 308 days advance warning on the 2018 Camp Fire (historically validated) >92% detection accuracy on network cascade failures 68% cross-validation performance across multiple model architectures 🌟 Technical Innovation Novel hybrid approach: Successfully combined physics-based models with gradient boosting mdoels Real disaster validation: Proved effectiveness on actual historical catastrophes End-to-end system: From IoT sensors to interactive dashboards, completely functional Scalable architecture: Production-ready Elastic Serverless infrastructure 🎯 Real-World Impact Potential Disaster prevention: Could have saved 85 lives in the Camp Fire scenario Grid resilience: Network-wide blackout prevention capabilities Community safety: Early warning systems for infrastructure-dependent communities Economic value: Preventing billions in disaster damages through predictive maintenance 💻 Technical Excellence 11 comprehensive test scripts validating different model architectures Multiple data integration pipelines handling diverse data sources Professional documentation with clear setup and deployment guides Live demonstration capabilities with real-time sensor simulation

### What we learned

1. Data Quality Is Everything The most profound lesson was discovering the dramatic difference between synthetic and real data: Real disaster data: Excellent predictive signals Real network topology: Strong pattern recognition Pure synthetic data: Poor performance ceiling (~50%) This validates our core thesis: IoT sensor deployment is not optional — it's essential for breakthrough accuracy. 2. Physics + AI > Pure ML Traditional machine learning approaches miss critical domain knowledge. Our hybrid models that combine: Physics-based understanding (interpretable, fast) Gradient Boosting model pattern recognition (accurate, adaptive) Real network topology (actual grid structure) ...significantly outperform pure data-driven approaches. 3. Model Specialization Matters Different failure modes require different AI architectures: Component degradation: Physics-based models excel (308-day warning) Network cascades: Gradient boosting dominate (90% accuracy) Robustness: Ensemble methods provide stability across scenarios 4. Real-Time Architecture Complexity Building production-ready infrastructure monitoring requires: Robust data pipelines that handle sensor failures Scalable cloud architecture for multiple consumers Professional visualization tools for operator decision-making Clear separation between data collection and processing 5. Historical Validation Is Crucial Proving AI models work on past disasters provides: Credibility with utility companies and regulators Clear ROI calculations for deployment decisions Confidence in real-world performance Compelling narrative for stakeholder buy-in

### What's next

for LiveWire: for a safer city Immediate Next Steps (6 months) 🤝 Industry Partnerships Partner with Pacific Gas & Electric (PG&E) for pilot deployment Collaborate with California Public Utilities Commission for regulatory validation Work with insurance companies to quantify risk reduction value 🔬 Research Expansion Extend models to earthquake-triggered infrastructure failures Incorporate weather data for storm-related grid vulnerabilities Develop wildfire spread prediction integrated with grid monitoring Medium-Term Goals (1-2 years) 🌐 National Scale Deployment Expand from single-city demonstrations to regional grid networks Integrate with existing utility SCADA systems and control centers Develop mobile applications for field technician rapid response 🧠 Advanced AI Capabilities Incorporate satellite imagery for real-time infrastructure health assessment Add predictive maintenance scheduling optimization Develop community-level risk communication systems Long-Term Vision (3-5 years) 🏙️ Smart City Integration National Grid Intelligence: Monitor interconnected power networks across states Climate Resilience: Adapt infrastructure to extreme weather patterns Community Safety Networks: Early warning systems for neighborhoods Economic Optimization: AI-driven infrastructure investment prioritization 🌍 Global Impact Deploy in developing countries with aging grid infrastructure Create open-source versions for resource-constrained regions Establish international standards for AI-powered grid monitoring Technology Roadmap 🚀 Advanced Features Predictive Maintenance: Optimize repair schedules before failures occur Resource Allocation: AI-guided crew deployment for maximum impact Risk Communication: Automated alert systems for emergency management Economic Modeling: Cost-benefit analysis for infrastructure investments 🔬 Research Frontiers Quantum Computing: Explore quantum algorithms for complex network optimization Digital Twins: Create virtual replicas of entire regional power grids Autonomous Response: AI systems that can automatically reroute power during emergencies Call to Action LiveWire represents a paradigm shift from reactive disaster response to proactive disaster prevention. With 308 days of advance warning, we can save lives, protect communities, and build more resilient infrastructure. The future we're building: A world where infrastructure disasters like the Camp Fire become impossible because we detect and prevent them months before they occur. For safer cities. For protected communities. For a resilient future.

## README (from the GitHub repository)

# LiveWire: AI-Powered Grid Infrastructure Monitoring

**An electrocardiogram for the power grid** — predicting catastrophic failures with **99.73% accuracy** before they happen.

[![Live Demo](https://img.shields.io/badge/🚀_Live_Demo-Frontend-blue)](http://localhost:3000)
[![Elastic Dashboard](https://img.shields.io/badge/📊_Embedded_Dashboard-Real_Time-orange)](http://localhost:3000/elasticsearch)
[![Champion Model](https://img.shields.io/badge/🏆_Gradient_Boosting-99.73%25-brightgreen)](./CABLE_MODEL_ANALYSIS.md)
[![Real Data](https://img.shields.io/badge/📊_365K_Samples-Validated-success)](./test_real_dataset.py)
[![Python 3.13](https://img.shields.io/badge/Python-3.13-blue?logo=python)](https://www.python.org/)
[![React 18](https://img.shields.io/badge/React-18.2-61dafb?logo=react)](https://reactjs.org/)
[![Node.js](https://img.shields.io/badge/Node.js-Frontend-339933?logo=node.js)](https://nodejs.org/)
[![Elastic](https://img.shields.io/badge/Elastic-Serverless-005571?logo=elasticsearch)](https://www.elastic.co/)
[![Scikit-Learn](https://img.shields.io/badge/scikit--learn-ML-F7931E?logo=scikit-learn)](https://scikit-learn.org/)
[![PyTorch](https://img.shields.io/badge/PyTorch-Neural%20Networks-EE4C2C?logo=pytorch)](https://pytorch.org/)
[![NetworkX](https://img.shields.io/badge/NetworkX-Grid%20Analysis-yellow?logo=python)](https://networkx.org/)
[![Mapbox](https://img.shields.io/badge/Mapbox-GL%20Maps-000000?logo=mapbox)](https://www.mapbox.com/)
[![Framer Motion](https://img.shields.io/badge/Framer-Motion-0055FF?logo=framer)](https://www.framer.com/motion/)
[![Recharts](https://img.shields.io/badge/Recharts-Charts-ff7300?logo=react)](https://recharts.org/)
[![React Router](https://img.shields.io/badge/React%20Router-6-CA4245?logo=react-router)](https://reactrouter.com/)
[![Raspberry Pi](https://img.shields.io/badge/Raspberry%20Pi-IoT%20Hardware-A22265?logo=raspberry-pi)](https://www.raspberrypi.org/)

---

## 🚨 The Problem: Grid Failures Kill

**The 2018 Camp Fire killed 85 people.** It started with a single degraded power line component.

**Our Solution:** We proved we could have detected this failure **308 days in advance** — enough time to prevent the entire disaster.

**🏆 NEW:** Our **Optimized Gradient Boosting model** achieves **99.73% accuracy** on 365,000 real cable infrastructure samples!

---

## 🏆 What We Built

LiveWire is an **AI-powered electrocardiogram for power grids** that:

| **Achievement**             | **Impact**                       | **Proof**                        |
| --------------------------- | -------------------------------- | -------------------------------- |
| 🥇 **Champion AI Model**    | **99.73% accuracy** on real data | 365K cable samples validated     |
| 🔥 **Camp Fire Prediction** | 308 days advance warning         | Prevented disaster scenario      |
| ⚡ **Cascade Detection**    | 70% accuracy on blackouts        | Network-wide protection          |
| 🌐 **Real-Time Monitoring** | Live IoT sensor pipeline         | Embedded Elasticsearch dashboard |
| 📊 **Interactive Frontend** | Multi-city visualization         | React + Mapbox integration       |

**Bottom Line:** Deploy our IoT sensors. Get 308 days to act. Save lives.

---

## 💡 How It Works

### 🏆 The Champion AI Model

- **Optimized Gradient Boosting**: 99.73% accuracy winner on real cable data
- **22 Engineered Features**: Advanced thermal, mechanical, and electrical analysis
- **Real-Time Predictions**: 0.023ms per prediction for instant alerts
- **Production Ready**: Raspberry Pi deployment with Elasticsearch streaming

### The Real-Time Pipeline

```
Raspberry Pi Sensors → Gradient Boosting AI → Elastic Serverless → Dashboard Alerts
    (IoT Hardware)        (99.73% Accuracy)     (Cloud Database)    (React Frontend)
```

### 📊 Embedded Dashboard

- **Live Elasticsearch integration** directly in React frontend
- **Real-time cable monitoring** with red/yellow/green risk zones
- **Sensor fusion display**: Temperature, vibration, strain, power
- **Mapbox visualization** for cable network mapping

### Key Innovation: Physics + AI

Unlike pure data approaches, we combine:

- **Physics-based models** (interpretable, fast)
- **Neural networks** (pattern recognition, accuracy)
- **Real network topology** (actual grid structure)

---

### Quick Start Guide

```bash
# Navigate to frontend
cd frontend

# Install and run
npm install
npm start
# Opens at localhost:3000
```

### Real-time data pipeline from IoT sensors

```bash
# Start sensor simulation
python hardware/raspberry_pi_sensor.py

# Monitor in real-time
python database/realtime_reader.py

# View live dashboard
# https://my-elasticsearch-project-c80e6e.kb.us-west1.gcp.elastic.cloud
```

**Our predictive modelling approach**

```bash
# Test 1: Camp Fire Prediction (308 days)
python scripts/test_camp_fire.py

# Test 2: Cascade Detection (70% accuracy)
python scripts/test_enhanced_neural_network_cascade_models.py

# Test 3: Full System
python scripts/run_all_analyses.py
```

**Live Dashboards:**

- 📊 [Elastic Serverless Dashboard](https://my-elasticsearch-project-c80e6e.kb.us-west1.gcp.elastic.cloud) — Real-time sensor data (for demo purposes)
- 🎨 Frontend Dashboard — Interactive city visualizations (this is our client-facing final product)

---

## 🏗️ Architecture

### Backend: AI + Real-Time Data

```
LiveWire/
├── models/                    # 🧠 AI Models
│   ├── grid_risk_model.py    # 308-day predictions
│   ├── enhanced_neural.py    # 70% cascade detection
│   └── hybrid_ensemble.py   # Robust combinations
├── elastic/                   # ☁️ Real-Time Infrastructure
│   ├── serverless_setup.py  # Cloud configuration
│   ├── realtime_predictor.py # Live AI processing
│   └── dashboard_setup.py   # Visualization creation
└── hardware/                 # 🔌 IoT Integration
    └── raspberry_pi_sensor.py # Edge sensors
```

### Frontend: Interactive Dashboards

```
frontend/
├── src/components/
│   ├── LosAngelesMap.js      # City grid visualization
│   ├── Dashboard.js          # Real-time monitoring
│   └── ComponentInfoPanel.js # Detailed analytics
└── Live at: your-frontend-url.com
```

---

## 📊 Proven Results

### Real Historical Validation

- **✅ 2018 Camp Fire**: 308 days advance warning
- **✅ Network Cascades**: 70% detection accuracy
- **✅ Cross-Validation**: 68% robust performance

### Why Our Approach Works

**Key Finding:** Real data dramatically outperforms synthetic approaches:

- Real disaster data: **Excellent signals**
- Real network topology: **Strong patterns**
- Synthetic data alone: **Poor ceiling (~50%)**

This validates our core thesis: **Deploy real IoT sensors for breakthrough accuracy.**

---

## 🚀 Tech Stack

### AI & Backend

- **Python 3.13** — Core ML development
- **scikit-learn + PyTorch** — Model training
- **NetworkX** — Grid topology analysis
- **Elastic Serverless** — Real-time data pipeline

### Frontend & Visualization

- **React 18.2** — Interactive dashboards
- **Mapbox GL** — Geographic visualizations
- **Framer Motion** — Smooth animations
- **Recharts** — Real-time data plots

### IoT & Hardware

- **Raspberry Pi** — Edge sensor simulation
- **Agent Builder** — Elastic data structuring
- **REST APIs** — Sensor-to-cloud communication

---

## 🎯 Use Cases

| **Scenario**         | **LiveWire Solution**           | **Business Impact**              |
| -------------------- | ------------------------------- | -------------------------------- |
| Equipment aging      | 308-day early warnings          | Planned maintenance vs emergency |
| Cascade blackouts    | 70% prediction accuracy         | Regional stability protection    |
| Fire risk assessment | Historical disaster analysis    | Community evacuation planning    |
| Grid modernization   | Real-time infrastructure health | Investment prioritization        |

---

<!-- ### Backend Setup
```bash
# Clone and setup
git clone https://github.com/marianaisaw/LiveWire.git
cd LiveWire

# Python en

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 164 recognized source files, 3608 KB.
- CSS (language) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- PyTorch (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (120 of 230)

```
.gitignore
.vercelignore
analysis/analyze_performance.py
backend/elasticsearch_proxy.py
backend/live_component_api.py
backend/rul_api.py
backend/rul_elasticsearch_integration.py
backend/rul_prediction_pipeline.py
backend/rul_sensor_watcher.py
backend/synthetic_degradation.py
CABLE_MODEL_ANALYSIS.md
CAL_HACKS_GUIDE.md
data/calib/.gitkeep
data/calib/pre2018_camp_fire.csv
data/calib/pre2018.csv
data/camp_fire/.gitkeep
data/camp_fire/complete_dataset.csv
data/CMaps/readme.txt
data/CMaps/RUL_FD001.txt
data/CMaps/RUL_FD002.txt
data/CMaps/RUL_FD003.txt
data/CMaps/RUL_FD004.txt
data/CMaps/test_FD001.txt
data/CMaps/test_FD002.txt
data/CMaps/test_FD003.txt
data/CMaps/test_FD004.txt
data/CMaps/train_FD001.txt
data/CMaps/train_FD002.txt
data/CMaps/train_FD003.txt
data/CMaps/train_FD004.txt
data/CMaps/x.txt
data/elasticData.csv
data/power_grid_dataset_with_cascade_failures.csv
data/power_grid_dataset.csv
data/pre_fire/.gitkeep
data/pre_fire/2018_camp_fire_runup.csv
data/pre_fire/2018_runup.csv
data/processed/.gitkeep
data/processed/2022_data.csv
data/processed/accuracy_progression.csv
data/processed/cascade_failure_results.csv
data/processed/cascade_feature_importance.csv
data/processed/comprehensive_model_summary.csv
data/processed/enhanced_cascade_results.csv
data/processed/feature_selection_results.csv
data/processed/hybrid_cascade_results.csv
data/processed/optimized_cv_results.csv
data/processed/optimized_final_results.csv
data/processed/power_grid_enhanced_results.csv
data/processed/power_grid_results.csv
data/processed/power_grid_simple_results.csv
data/processed/ultra_optimized_results.csv
data/raw/.gitkeep
data/raw/cable_monitoring_dataset.csv
database/demo_architecture.py
database/pi_writer.py
database/realtime_reader.py
DEMO_CHECKLIST.md
demo_data_generator.py
DEMO_FILES_MANIFEST.md
demo_live_rul_with_model.py
DEMO_README.md
demo/hackathon_demo.py
elastic/credentials.json
elastic/dashboard_setup.py
elastic/elastic_agent.py
elastic/README.md
elastic/realtime_predictor.py
elastic/SERVERLESS_SETUP.md
elastic/serverless_setup.py
elastic/setup_elastic.py
ELASTICSEARCH_SETUP_STEP4_VERIFICATION.md
experiments/backtest_leadtime.py
experiments/calibrate_baseline.py
experiments/data_loader.py
experiments/predict_fire.py
experiments/test_complete_pipeline.py
frontend/.env.example
frontend/package.json
frontend/public/_redirects
frontend/public/index.html
frontend/public/manifest.json
frontend/README-FRONTEND.md
frontend/SETUP.md
frontend/src/App.css
frontend/src/App.js
frontend/src/components/Analytics.css
frontend/src/components/Analytics.js
frontend/src/components/ComponentInfoPanel.css
frontend/src/components/ComponentInfoPanel.js
frontend/src/components/Dashboard.css
frontend/src/components/Dashboard.js
frontend/src/components/EconomicAssessment.css
frontend/src/components/EconomicAssessment.js
frontend/src/components/ElasticsearchDashboard.css
frontend/src/components/ElasticsearchDashboard.js
frontend/src/components/ElasticsearchProxy.js
frontend/src/components/HealthVisualization.css
frontend/src/components/HealthVisualization.js
frontend/src/components/KibanaDashboard.css
frontend/src/components/KibanaDashboard.js
frontend/src/components/LandingPage.css
frontend/src/components/LandingPage.js
frontend/src/components/LiveComponentDashboard.css
frontend/src/components/LiveComponentDashboard.js
frontend/src/components/LiveElasticsearchDashboard.js
frontend/src/components/LiveMetrics.css
frontend/src/components/LiveMetrics.js
frontend/src/components/LiveSensor.css
frontend/src/components/LiveSensor.js
frontend/src/components/LosAngelesMap.css
frontend/src/components/LosAngelesMap.js
frontend/src/components/map/CableNetworkMap.js
frontend/src/components/map/MapLayers.js
frontend/src/components/ParadiseDemoMap.css
frontend/src/components/ParadiseDemoMap.js
frontend/src/components/SensorDetailsPanel.css
frontend/src/components/SensorDetailsPanel.js
frontend/src/components/SensorPointLayer.css
frontend/src/components/SensorPointLayer.js
[110 more files omitted for size]
```

### Dependencies

- frontend/package.json: @testing-library/jest-dom@^5.16.4, @testing-library/react@^13.3.0, @testing-library/user-event@^13.5.0, framer-motion@^7.2.1, lucide-react@^0.263.1, mapbox-gl@^3.16.0, react@^18.2.0, react-dom@^18.2.0, react-router-dom@^6.3.0, react-scripts@5.0.1, recharts@^2.5.0, web-vitals@^2.1.4
- requirements.txt: joblib, kaggle, numpy, pandas, scikit-learn, scipy

### Recent commits (newest first)

- Fix Vercel deployment - configure for React frontend subdirectory
- vercel integrate
- fixed merged
- resolved merge conflicts
- edits
- id
- still doesnt work
- try agaun
- live graph try again
- fix baseline data rul
- baseline data display
- plz
- new live view and speedup demo view i hope
- brooooooo
- speedup data aggregte
- quesiotnable live view
- rul calculation w pi. backend handles calculation. elastic takes in knob data and takes to dashboard for calculation
- elasticsearch integration to live component w raspberry pi
- backend integration works i hope
- rul backend api endpoint, expose rul predictor via flask endpoint for frontend

## Key source files (fetched from GitHub, selected and truncated for size)

### SECRETS_README.md

```markdown
# API Keys and Secrets Management

## 🔐 Secret Files Location

Your API keys are stored in the following files (all ignored by git):

### Root Directory
- **`.env`** - Main environment variables
- **`secrets.json`** - JSON format API keys

### Frontend Directory  
- **`frontend/.env`** - React environment variables

## 🔑 Available API Keys

### Claude AI API
- **Key**: `sk-ant-api03-***[HIDDEN]***`
- **Usage**: AI model interactions, chat features
- **Location**: `.env`, `secrets.json`, `frontend/.env`

### Mapbox API
- **Key**: `pk.***[HIDDEN]***`
- **Usage**: Map rendering, geolocation features
- **Location**: `.env`, `secrets.json`, `frontend/.env`

### Vercel Project
- **ID**: `***[HIDDEN]***`
- **Usage**: Deployment configuration
- **Location**: `.env`, `secrets.json`, `frontend/.env`

## 🛡️ Security Features

✅ **Git Protection**: All secret files are in `.gitignore`
✅ **Multiple Formats**: Environment vars, JSON, React env
✅ **Frontend Ready**: React apps can access `REACT_APP_*` variables
✅ **Backend Ready**: Python can load from `.env` or `secrets.json`

## 📝 Usage Examples

### Python Backend
```python
import json
import os
from dotenv import load_dotenv

# Method 1: Load from .env
load_dotenv()
claude_key = os.getenv('ANTHROPIC_API_KEY')
mapbox_key = os.getenv('MAPBOX_TOKEN')

# Method 2: Load from secrets.json
with open('secrets.json', 'r') as f:
    secrets = json.load(f)
    claude_key = secrets['claude_api_key']
    mapbox_key = secrets['mapbox_api_key']
```

### React Frontend
```javascript
// Access environment variables in React
const mapboxToken = process.env.REACT_APP_MAPBOX_TOKEN;
const claudeKey = process.env.REACT_APP_ANTHROPIC_API_KEY;
const vercelId = process.env.REACT_APP_VERCEL_TOKEN;
```

## ⚠️ Security Reminders

1. **Never commit secret files** - They're gitignored
2. **Don't share API keys** in chat/email
3. **Rotate keys** if compromised
4. **Use environment variables** in production
5. **Keep backups** of your keys securely

## 🔄 Git Status Check

To verify secrets are ignored:
```bash
git check-ignore .env secrets.json frontend/.env
# Should return all three files
```
```

### DEMO_FILES_MANIFEST.md

```markdown
# Demo Files Manifest

All files created to help you demonstrate that your predictive model is actually working.

## Created Files

### 1. Main Demo Script
📄 **`demo_live_rul_with_model.py`**
- Simulates Raspberry Pi sensor data into Elasticsearch
- Runs 3 scenarios: normal, temperature spike, multi-sensor degradation
- Shows RUL predictions changing in real-time
- Full colored output for judges
- Usage: `python demo_live_rul_with_model.py`

### 2. Quick Start Guide
📄 **`DEMO_README.md`**
- **START HERE** - Overview and 3-step setup
- What judges will see (console output and frontend)
- Key talking point
- FAQ for judges
- Troubleshooting

### 3. Setup Checklist
📄 **`DEMO_CHECKLIST.md`**
- Step-by-step setup (before judges arrive)
- What to show judges (during demo)
- Console output to highlight
- Time allocations per section
- Success criteria

### 4. Full Judge Walkthrough
📄 **`JUDGE_DEMO_PROOF_OF_MODEL.md`**
- Complete 5-minute demo script
- Act-by-act breakdown
- Full technical Q&A for judges
- Troubleshooting guide
- Elevator pitches (30-second and 1-minute versions)

### 5. Technical Integration Summary
📄 **`MODEL_INTEGRATION_SUMMARY.md`**
- How the model is integrated into your system
- Data flow: Pi → Elasticsearch → Backend → Model → Frontend
- Proof that it's working
- Model facts and performance metrics
- What judges will be impressed by

### 6. This File
📄 **`DEMO_FILES_MANIFEST.md`**
- List of all demo files
- Reading order
- Quick lookup guide

## Modified Files

### Backend Code
📝 **`backend/live_component_api.py`**
- Lines 242, 268: Enhanced logging
- Shows model being called with exact details
- Proves to judges that model is being invoked

## Reading Order

1. **`DEMO_README.md`** (5 min) - Get oriented
2. **`DEMO_CHECKLIST.md`** (5 min) - Know the setup
3. **`JUDGE_DEMO_PROOF_OF_MODEL.md`** (10 min) - Learn full walkthrough
4. **`MODEL_INTEGRATION_SUMMARY.md`** (5 min) - Understand technical details

Total time: 25 minutes to be fully prepared.

## Quick Lookup

| Question | File |
|----------|------|
| Where do I start? | DEMO_README.md |
| How do I set up? | DEMO_CHECKLIST.md |
| What if judges ask X? | JUDGE_DEMO_PROOF_OF_MODEL.md (FAQ) |
| How is the model integrated? | MODEL_INTEGRATION_SUMMARY.md |
| I'm nervous, what's my pitch? | JUDGE_DEMO_PROOF_OF_MODEL.md (Talking Points) |

## Before Demo (Do This)

- [ ] Read DEMO_README.md
- [ ] Read DEMO_CHECKLIST.md
- [ ] Run setup once to verify everything works
- [ ] Have all 3 terminals ready
- [ ] Know your 30-second pitch

## During Demo (Remember This)

- Point to backend console when model is called
- Highlight the "🤖 Calling RUL Gradient Boosting model..." line
- Show RUL countdown updating in frontend
- Demonstrate temperature spike → RUL drop
- Emphasize NASA C-MAPSS training data

## Success Indicators

✅ Backend logs show: "🤖 Calling RUL Gradient Boosting model..."
✅ Frontend RUL updates every 2 seconds
✅ Temperature spike scenario shows RUL dropping
✅ Judge
[truncated — 150 more characters]
```

### requirements.txt

```
numpy
pandas
scikit-learn
joblib
scipy
kaggle

```

### package.json

```
{
  "name": "livewire-root",
  "version": "1.0.0",
  "scripts": {
    "build": "cd frontend && npm install && npm run build",
    "start": "cd frontend && npm start"
  },
  "devDependencies": {},
  "dependencies": {}
}
```

### frontend/package.json

```
{
  "name": "livewire",
  "version": "1.0.0",
  "private": true,
  "proxy": "http://localhost:5001",
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "framer-motion": "^7.2.1",
    "lucide-react": "^0.263.1",
    "mapbox-gl": "^3.16.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.3.0",
    "react-scripts": "5.0.1",
    "recharts": "^2.5.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "vercel-build": "react-scripts build"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

```

### src/App.js

```javascript
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { CityProvider } from './contexts/CityContext';
import LandingPage from './components/LandingPage';
import Dashboard from './components/Dashboard';
import './App.css';

function App() {
  return (
    <CityProvider>
      <Router>
        <div className="App">
          <Routes>
            <Route path="/" element={<LandingPage />} />
            <Route path="/dashboard" element={<Dashboard />} />
          </Routes>
        </div>
      </Router>
    </CityProvider>
  );
}

export default App;

```

### frontend/src/index.js

```javascript
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

```

### frontend/src/App.js

```javascript
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { CityProvider } from './contexts/CityContext';
import LandingPage from './components/LandingPage';
import Dashboard from './components/Dashboard';
import ParadiseDemoMap from './components/ParadiseDemoMap';
import LiveElasticsearchDashboard from './components/LiveElasticsearchDashboard';
import LiveComponentDashboard from './components/LiveComponentDashboard';
import './App.css';

function App() {
  return (
    <CityProvider>
      <Router>
        <div className="App">
          <Routes>
            <Route path="/" element={<LandingPage />} />
            <Route path="/dashboard" element={<Dashboard />} />
            <Route path="/camp-fire-demo" element={<ParadiseDemoMap />} />
            <Route path="/elasticsearch" element={<LiveElasticsearchDashboard />} />
            <Route path="/live-component" element={<LiveComponentDashboard />} />
          </Routes>
        </div>
      </Router>
    </CityProvider>
  );
}

export default App;

```

### split_geojson.js

```javascript
const fs = require('fs');

console.log('Loading large GeoJSON file...');
const data = JSON.parse(fs.readFileSync('./public/data/california-transmission-lines.geojson', 'utf8'));

console.log(`Total features: ${data.features.length}`);

// Define region bounding boxes
const regions = {
  'paradise': {
    minLat: 39.5, maxLat: 40.0,
    minLon: -121.8, maxLon: -121.0
  },
  'san-francisco': {
    minLat: 37.3, maxLat: 38.0,
    minLon: -123.0, maxLon: -121.8
  },
  'los-angeles': {
    minLat: 33.8, maxLat: 34.2,
    minLon: -118.4, maxLon: -117.9
  }
};

// Split features by region
Object.entries(regions).forEach(([region, bbox]) => {
  const filtered = data.features.filter(feature => {
    if (!feature.geometry) return false;
    
    if (feature.geometry.type === 'LineString') {
      // Check if any coordinate is within bbox
      return feature.geometry.coordinates.some(coord => {
        const [lon, lat] = coord;
        return lat >= bbox.minLat && lat <= bbox.maxLat && 
               lon >= bbox.minLon && lon <= bbox.maxLon;
      });
    } else if (feature.geometry.type === 'Point') {
      const [lon, lat] = feature.geometry.coordinates;
      return lat >= bbox.minLat && lat <= bbox.maxLat && 
             lon >= bbox.minLon && lon <= bbox.maxLon;
    }
    return false;
  });

  const geojson = {
    type: 'FeatureCollection',
    features: filtered,
    metadata: {
      region,
      source: 'California Energy Commission GIS',
      bbox
    }
  };

  const filename = `./public/data/transmission-${region}.geojson`;
  fs.writeFileSync(filename, JSON.stringify(geojson));
  console.log(`✅ Created ${filename} with ${filtered.length} features`);
});

console.log('Done!');

```

### quick_demo.py

```python
"""
Quick Demo Runner for Judges
===========================

Pre-configured demo that runs immediately for judge presentations.
This will be auto-configured with your Elastic Serverless credentials.
"""

import sys
import os
import json

def load_credentials():
    """Load saved Elastic credentials"""
    try:
        with open('elastic/credentials.json', 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        print("❌ No credentials found. Run: python setup_complete.py first")
        return None

def quick_judge_demo():
    """2-minute demo perfect for judges"""
    print("🔥 LIVEWIRE JUDGE DEMO")
    print("Infrastructure monitoring with Elastic Agent Builder on Serverless")
    print("=" * 60)
    
    # Load credentials
    creds = load_credentials()
    if not creds:
        return
    
    print("Elastic Serverless credentials loaded")
    print(f"🌐 Connected to: {creds['cloud_id'].split(':')[0]}")
    print()
    
    # Import and run
    try:
        sys.path.append(os.path.dirname(os.path.abspath(__file__)))
        from elastic.elastic_agent import LiveWireElasticAgent
        
        print("🤖 Initializing LiveWire Elastic Agent...")
        agent = LiveWireElasticAgent(creds['cloud_id'], creds['api_key'])
        
        # Demo components with different scenarios
        components = [
            "JUDGE_DEMO_NORMAL",     # Shows green/normal
            "JUDGE_DEMO_WARNING",    # Shows yellow/warning  
            "JUDGE_DEMO_CRITICAL"    # Shows red/critical with alerts
        ]
        
        print("🎬 Starting judge demo...")
        print("Watch real-time data streaming to Elastic Serverless")
        print("🚨 Alerts will be generated for critical conditions")
        print("⏱️ Demo duration: 2 minutes")
        print()
        print("🗣️ TELL THE JUDGES:")
        print("   'This is a custom Elastic Agent Builder running on Serverless'")
        print("   'Real-time infrastructure monitoring with AI predictions'")
        print("   'Our model predicted the Camp Fire 308 days early'")
        print("   'Zero infrastructure management, pure cloud-native'")
        print()
        
        # Run the demo
        agent.start_monitoring(components, interval=4, duration=120)
        
        print("\nDEMO COMPLETE!")
        print("Data sent to Elastic Serverless:")
        print(f"   Metrics: metrics-livewire.sensors-default")
        print(f"   Alerts: logs-livewire.alerts-default")
        print()
        print("CRITERIA ACHIEVED:")
        print("Elastic Agent Builder + Serverless Instance")
        print("Real-world Application + Live Data Streams")
        
    except Exception as e:
        print(f"Demo error: {e}")
        print("Make sure you ran: python setup_complete.py first")

if __name__ == "__main__":
    quick_judge_demo()
```

[152 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]