Skip to content

yashy10/SafePath

ย 
ย 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

12 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

SafePath - Intelligent Route Safety Analysis

Find the safest walking paths in San Francisco using real-time crime and incident data

SafePath analyzes walking routes against real-time San Francisco crime statistics and 311 incident reports to recommend the safest paths to your destination.

SafePath Demo Python 3.9+ Node 16+


๐Ÿš€ Quick Start (3 Steps)

1. Clone Repository

git clone https://github.com/charliesturiale/AWS_Hackathon2025.git
cd AWS_Hackathon2025

2. Run Setup (First Time Only)

SETUP.bat

This will:

  • Check for Python 3.9+ and Node.js 16+
  • Install all dependencies automatically
  • Guide you through API key configuration

3. Launch Application

START_HERE.bat

That's it! ๐ŸŽ‰


๐Ÿ“‹ Prerequisites

Software (Auto-Checked by SETUP.bat)

  • Python 3.9+ - Download here
    • โš ๏ธ During installation, CHECK "Add Python to PATH"
  • Node.js 16+ - Download here
    • Use LTS version (default settings are fine)

API Keys (FREE)

DataSF API Token (Required)

  1. Go to data.sfgov.org
  2. Click "Sign Up" (free account)
  3. Go to Profile โ†’ Copy "App Token"

GraphHopper API Key (Required)

  1. Go to graphhopper.com
  2. Click "Get started for free"
  3. Copy API key from dashboard
  4. Note: Free tier = ~5 requests/minute (perfect for testing)

๐ŸŽฏ Features

  • Real-Time Data: Crime & 311 incidents updated every 10 minutes
  • Smart Routing: Generates 3 optimized route variations
  • Offline Optimization: Fast safety improvements (no extra API calls)
  • Time-Decay Algorithm: Recent incidents weighted more heavily
  • Distance-Based Detection: 200m safety buffer for incidents
  • Interactive Map: Visual routes with safety scores
  • Mobile Responsive: Works on all devices

๐Ÿงช Try It Out

Test these San Francisco routes:

  • Short: "Union Square, SF" โ†’ "Ferry Building, SF"
  • Long: "Golden Gate Park" โ†’ "Fisherman's Wharf"
  • Neighborhood: "Mission District" โ†’ "Castro District"

๐Ÿ“– Manual Setup (Mac/Linux or Advanced Users)

Click to expand manual installation steps

1. Clone Repository

git clone https://github.com/charliesturiale/AWS_Hackathon2025.git
cd AWS_Hackathon2025

2. Create .env File

Create a file named .env in the project root with:

# DataSF API Configuration
DATASF_API_TOKEN=your_datasf_token_here
DATASF_CRIME_API=https://data.sfgov.org/resource/gnap-fj3t.json
DATASF_311_API=https://data.sfgov.org/resource/vw6y-z8j6.json

# GraphHopper API Configuration
GRAPHHOPPER_API_KEY=your_graphhopper_key_here

# Server Configuration
BACKEND_PORT=8000
FRONTEND_URL=http://localhost:3000
DATA_REFRESH_INTERVAL=10

3. Setup Backend

cd backend
python3 -m venv venv
source venv/bin/activate  # Mac/Linux
# or
venv\Scripts\activate     # Windows
pip install -r requirements.txt

4. Setup Frontend

cd frontend
npm install

5. Run Backend (Terminal 1)

cd backend/app
source ../venv/bin/activate  # Mac/Linux
python -m uvicorn main:app --reload --port 8000

6. Run Frontend (Terminal 2)

cd frontend
npm start

7. Open Browser

Navigate to http://localhost:3000


๐Ÿ”ง Troubleshooting

โŒ "Python not found"

Solution: Install Python 3.9+ and make sure to check "Add to PATH" during installation.

โŒ "Node not found"

Solution: Install Node.js 16+ from nodejs.org

โŒ "Port 8000 already in use"

Solution (Windows):

netstat -ano | findstr :8000
taskkill /PID <process_id> /F

โŒ "Port 3000 already in use"

Solution: Stop other React apps or close terminals running on port 3000.

โŒ GraphHopper "429 Too Many Requests"

Solution:

  • Wait 60 seconds (rate limit resets)
  • Free tier = ~5 requests/minute
  • Consider upgrading for production

โŒ Frontend can't connect to backend

Checklist:

  1. Is backend running? Test: curl http://localhost:8000/api/health
  2. Check CORS settings in backend/app/main.py
  3. Verify .env file exists in project root

โŒ Module import errors

Solution:

cd backend
venv\Scripts\activate
pip install -r requirements.txt

๐Ÿ“ก API Endpoints

Health Check

GET /api/health

Response:

{
  "status": "healthy",
  "data": {
    "crime_incidents": 160,
    "311_incidents": 50,
    "last_fetch": "2025-10-29T20:08:09.061345"
  }
}

Calculate Routes

POST /api/routes
Content-Type: application/json

{
  "origin": "Union Square, San Francisco",
  "destination": "Pier 39, San Francisco"
}

Response:

{
  "routes": [
    {
      "id": 1,
      "name": "Safest Route",
      "description": "Safest path with minimal risk exposure",
      "distance": "2.5 mi",
      "time": "52 min",
      "safetyScore": 85,
      "total_risk": 1.51,
      "coordinates": [{"lat": 37.7830, "lng": -122.4060}, ...],
      "color": "#10b981"
    }
  ],
  "originCoords": {"lat": 37.7829, "lng": -122.4060},
  "destCoords": {"lat": 37.8098, "lng": -122.4103}
}

Get Statistics

GET /api/data/stats

๐Ÿงฎ How It Works

Risk Scoring Algorithm

High-risk incidents (72-hour decay):

risk = (max(0, 3-3t/72))ยฒ ร— exp(-dยฒ/0.02)

Medium/low-risk incidents (24-hour decay):

risk = (max(0, w-wt/24))ยฒ ร— exp(-dยฒ/0.02)

Where:

  • t = hours since incident
  • d = distance from route (km)
  • w = risk weight (1=low, 2=medium, 3=high)

Risk Categories

Risk Level Weight Decay Examples
High 3 72hr Robbery, Assault, Battery, Explosives
Medium 2 24hr Purse Snatch, Fights, Burglary
Low 1 24hr Suspicious Person, Threats, Harassment
Encampments 2 None Open encampments (until closed)

Route Optimization Process

  1. Generate Routes: Request 3 variations from GraphHopper
  2. Analyze Segments: Find areas within 200m of incidents
  3. Calculate Waypoints: Create safe alternatives (250m from threats)
  4. Offline Injection: Add waypoints using existing route anchors
  5. Validate: Verify improved safety with geodesic distance
  6. Rank: Sort by safety score and return top 3

๐Ÿ—๏ธ Project Structure

AWS_Hackathon2025/
โ”œโ”€โ”€ backend/
โ”‚   โ”œโ”€โ”€ app/
โ”‚   โ”‚   โ”œโ”€โ”€ main.py              # FastAPI application
โ”‚   โ”‚   โ”œโ”€โ”€ data_fetcher.py      # DataSF integration
โ”‚   โ”‚   โ””โ”€โ”€ risk_scorer.py       # Risk calculation engine
โ”‚   โ”œโ”€โ”€ cache/                   # Cached incident data
โ”‚   โ”œโ”€โ”€ requirements.txt         # Python dependencies
โ”‚   โ””โ”€โ”€ production_test_suite.py # Test suite
โ”œโ”€โ”€ frontend/
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ components/          # React components
โ”‚   โ”‚   โ””โ”€โ”€ services/            # API clients
โ”‚   โ”œโ”€โ”€ package.json             # Node dependencies
โ”‚   โ””โ”€โ”€ public/                  # Static assets
โ”œโ”€โ”€ .env                         # API keys (DO NOT COMMIT)
โ”œโ”€โ”€ .gitignore                   # Git ignore rules
โ”œโ”€โ”€ SETUP.bat                    # First-time setup
โ”œโ”€โ”€ START_HERE.bat               # Launch application
โ””โ”€โ”€ README.md                    # This file

๐Ÿงช Testing

Quick Backend Test

curl http://localhost:8000/api/health

Comprehensive Test Suite

cd backend
python production_test_suite.py

Tests include:

  • API verification
  • Route calculation accuracy
  • Risk scoring validation
  • Performance baselines
  • Load testing (respects API limits)

๐ŸŒ Production Deployment

Click to expand production deployment guide

Environment Variables

Backend .env (Production):

DATASF_API_TOKEN=your_production_token
GRAPHHOPPER_API_KEY=your_production_key
DATASF_CRIME_API=https://data.sfgov.org/resource/gnap-fj3t.json
DATASF_311_API=https://data.sfgov.org/resource/vw6y-z8j6.json
BACKEND_PORT=8000
FRONTEND_URL=https://your-domain.com
DATA_REFRESH_INTERVAL=10

CORS Configuration

Update backend/app/main.py:

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://your-domain.com"],  # Your frontend domain
    allow_credentials=True,
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
)

Production Server

Using Gunicorn (recommended):

cd backend
gunicorn app.main:app \
  --workers 4 \
  --bind 0.0.0.0:8000 \
  --worker-class uvicorn.workers.UvicornWorker

Frontend Build

cd frontend
npm run build
# Deploy build/ folder to static hosting (Vercel, Netlify, S3, etc.)

Hosting Options

Service Backend Frontend Difficulty
Heroku โœ… Free tier โŒ Easy
Railway โœ… Free tier โœ… Free tier Easy
Vercel โŒ โœ… Free tier Easy
AWS EC2 S3+CloudFront Medium
DigitalOcean Droplet Spaces Medium

๐Ÿ’ป Tech Stack

Backend:

  • FastAPI (Python 3.9+)
  • Uvicorn ASGI server
  • APScheduler (background tasks)
  • geopy, numpy, pandas

Frontend:

  • React 18 + TypeScript
  • Tailwind CSS + shadcn/ui
  • React Leaflet (maps)
  • Axios

APIs:

  • GraphHopper (routing/geocoding)
  • DataSF Crime Data
  • DataSF 311 Incidents

๐Ÿ“ Development

Backend Development

cd backend/app
source ../venv/bin/activate  # Mac/Linux
uvicorn main:app --reload --port 8000

Frontend Development

cd frontend
npm start

Code Style

  • Backend: PEP 8 (Python)
  • Frontend: ESLint + Prettier (TypeScript/React)

๐Ÿค Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open Pull Request

๐Ÿ“„ License

MIT License - See LICENSE file for details


๐Ÿ™ Acknowledgments


๐Ÿ“ž Support

Having issues?

  1. Check Troubleshooting section above
  2. Search existing GitHub issues
  3. Open a new issue with:
    • Error message
    • Steps to reproduce
    • OS and Python/Node versions

๐ŸŽ‰ Quick Command Reference

# First time setup
SETUP.bat

# Launch application
START_HERE.bat

# Individual backend
start-backend.bat

# Individual frontend
start-frontend.bat

# Test backend
curl http://localhost:8000/api/health

# Run tests
cd backend && python production_test_suite.py

Made with โค๏ธ for safer walking in San Francisco

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • Python 58.1%
  • TypeScript 19.0%
  • Jupyter Notebook 15.7%
  • Batchfile 4.7%
  • CSS 1.3%
  • JavaScript 0.8%
  • HTML 0.4%