# Project export: Navara AI

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: TreeHacks 2026
- Tagline: Navara AI finds new uses for FDA-approved drugs in 5 seconds. We analyze 25,000 diseases against 15,000 drugs, cutting discovery time from 15 years to months and costs from $2.6B to $2M.
- Devpost: https://devpost.com/software/navara-ai
- GitHub: https://github.com/ShruthiSathya/navara_ai
- Video: https://www.youtube.com/embed/r5QhLCA5k9E?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 1 GitHub contributor(s) — shruthi (14 commits)

## Devpost submission (written by the team)

### Inspiration

At 2 AM on Friday night, scrolling through research papers, I came across a devastating statistic: 95% of rare diseases have no FDA-approved treatment. Over 400 million people worldwide suffer from rare diseases, and most will never see a cure in their lifetime. But here's the twist: the cure might already exist. Drug repurposing has accidentally given us some of medicine's greatest breakthroughs. Viagra was originally for heart disease. Thalidomide, once banned, now treats cancer. These discoveries were pure luck, taking decades to stumble upon. I realized: what if we could systematically search every FDA-approved drug against every disease? The data exists across multiple biomedical databases. With 48 hours, could I build an AI that finds these hidden connections in seconds instead of decades? That's when Navara AI was born.

### What it does

Navara AI is like a matchmaking service for drugs and diseases. Here's the magic: You enter a disease name (any of 25,000 diseases) In under 5 seconds, it analyzes 15,000+ FDA-approved drugs Returns ranked candidates with biological evidence Automatically filters dangerous contraindications Validates results with clinical trial data and scientific literature But it's not just a database search. Navara builds a knowledge graph connecting diseases, genes, pathways, and drugs, then uses multi-factor scoring to find the most promising matches. It's computational biology meets real-time AI. The Technical Challenge Building this in a hackathon meant solving three massive problems: Problem 1: Data Integration I needed to integrate six different biomedical APIs in real-time: OpenTargets (disease-gene associations) ChEMBL (FDA-approved drugs) DGIdb (drug-gene interactions) ClinicalTrials.gov (clinical trials) PubMed (scientific literature) OpenFDA (adverse events) Each has different formats, rate limits, and quirks. No existing library handles them all. Problem 2: Intelligent Scoring How do you score a drug-disease match? I built a multi-factor algorithm that combines: Stotal=α⋅Sgene+β⋅Spathway+γ⋅Smoa+δ⋅SclinicalS_{\text{total}} = \alpha \cdot S_{\text{gene}} + \beta \cdot S_{\text{pathway}} + \gamma \cdot S_{\text{moa}} + \delta \cdot S_{\text{clinical}}Stotal​=α⋅Sgene​+β⋅Spathway​+γ⋅Smoa​+δ⋅Sclinical​ where genes and pathways use Jaccard similarity: J(A,B)=∣A∩B∣∣A∪B∣J(A, B) = \frac{|A \cap B|}{|A \cup B|}J(A,B)=∣A∪B∣∣A∩B∣​ Problem 3: Safety First High scores don't mean safe. Some drugs actively worsen diseases they score highly for. I built a contraindication engine that automatically filters dangerous drugs with medical reasoning.

### How we built it

The Stack Backend: Python + FastAPI Async architecture for concurrent API calls NetworkX for graph-based knowledge representation Custom caching system (queries went from 30s to 2s) Pydantic models for data validation Frontend: React + TailwindCSS Terminal-inspired brutalist design Real-time state management with React hooks Progressive disclosure UI (complex data made simple) Graph paper backgrounds and monospace fonts

### Challenges we ran into

Challenge 1: The Great API Debugging Session (Hour 25-28) Problem: All scores were 0.0. Every drug. Every disease. Investigation: Checked API responses: Working Checked graph construction: Working Checked scoring logic: Working Checked gene matching: BROKEN Root Cause: OpenTargets uses gene symbols like "ENSG00000012048". DGIdb uses gene names like "BRCA1". They never matched. Solution: Built a gene name normalization layer that maps between different identifier systems. 3 hours of debugging, 30 lines of code to fix. Lesson: Always check data formats first, not algorithm logic. Challenge 2: Performance Nightmare (Hour 16-20) Problem: First query took 45 seconds. Unusable. Analysis: Fetching 15,000 drugs: 15 seconds Querying drug interactions for each: 30 seconds Building graph: 0.5 seconds Solution: Multi-level caching strategy: Cache all FDA drugs (refresh daily) Cache drug-gene interactions (refresh weekly) Cache disease data (refresh per session) Result: 95% reduction in response time. First query: 8s. Subsequent: 0.5s. Lesson: In hackathons, performance is a feature. Challenge 3: The Dopamine Paradox (Hour 35) Problem: For Parkinson's disease, top result was Haloperidol (antipsychotic). Biologically makes sense (targets dopamine pathways). Medically disastrous (worsens Parkinson's). Solution: Built contraindication engine with pharmacological rules. High-scoring drugs can still be filtered if they're dangerous. Implementation: pythonif drug.mechanism == "dopamine_antagonist" and disease == "Parkinson": filter_out(drug, reason="Worsens motor symptoms") Lesson: Domain knowledge beats pure algorithms. Medical AI needs safety guardrails. Challenge 4: UI Complexity (Hour 28-32) Problem: Each drug has 50+ genes, 20+ pathways, mechanism explanation, clinical trials, papers, adverse events. How do you show this without overwhelming users? Solution: Progressive disclosure Level 1: Score + confidence + drug name Level 2: Top 3 genes, top 3 pathways, mechanism Level 3: Full details (expandable) Level 4: Clinical validation (separate modal) Lesson: Good UX is hiding complexity, not avoiding it. Challenge 5: The 11th Hour Bug (Hour 46) Problem: Clinical validation broke 2 hours before submission. PubMed API started returning 403 errors. Quick Fix: pythontry: papers = fetch_pubmed() except: papers = {"warning": "PubMed temporarily unavailable"} Lesson: Graceful degradation saves demos. External APIs will fail at the worst time.

### Accomplishments we're proud of

It Actually Works This isn't a mockup or prototype. Navara AI: Queries six real biomedical APIs in real-time Processes 15,000+ actual FDA-approved drugs Analyzes 25,000+ real diseases from medical databases Returns scientifically valid results (validated against literature) Handles edge cases gracefully The Validation Rate I tested Navara's predictions against published research: 85%+ of top-ranked candidates have supporting literature in PubMed For Parkinson's disease: Found levodopa (standard treatment) as #1 For diabetes: Found metformin, insulin, sulfonylureas in top 5 For hypertension: Found ACE inhibitors, beta-blockers in top 10 The system isn't just fast - it's accurate. Safety-First Design Built a contraindication engine that caught: Dopamine antagonists for Parkinson's (would worsen symptoms) Proconvulsants for epilepsy (could trigger seizures) Anticholinergics for Alzheimer's (cognitive impairment) Zero false negatives on major contraindications tested. The Performance Leap Initial query: 45 seconds to Final: 0.5 seconds (after cache) That's a 90x speedup from smart caching and async architecture. The UI Design Created a unique terminal-inspired aesthetic: Graph paper backgrounds Monospace fonts (Courier Prime) Brutalist card layouts Black/white/green color scheme Looks like a professional computational biology tool, not a hackathon project. Built Solo in 48 Hours No team. Just me, six APIs, and a lot of coffee.

### What we learned

Technical Skills APIs Are Hard Every API has quirks (rate limits, formats, error codes) Always implement retries with exponential backoff Cache everything expensive Plan for API failures in production Graph Databases Are Powerful NetworkX made relationship queries elegant Path-finding algorithms perfect for "how are drug X and disease Y connected?" Visualization helps debug complex data React State Management useState for simple state useEffect for side effects and API calls Proper loading states make UX professional Performance Optimization First rule: Measure before optimizing Second rule: Cache is king Third rule: Async everything Domain Knowledge Computational Biology Disease-gene associations aren't binary (they have confidence scores) Drugs can target 1-100+ genes Pathways are hierarchical (need to handle parent-child relationships) Gene names are inconsistent across databases (normalization required) Pharmacology Mechanism of action matters more than just shared genes Contraindications can be absolute (never use) or relative (use cautiously) Clinical validation requires multiple evidence types Safety signals from adverse events need statistical significance Drug Development Traditional: 15 years, $2.6B, 90% failure rate Repurposing: 3-7 years, $2M, 70% success rate (safety proven) Regulatory pathway: 505(b)(2) allows abbreviated approval process Hackathon Strategy Scope Ruthlessly Started with 20 features, built 8 Cut machine learning model (use rule-based scoring) Cut drug combination analysis (too complex) Cut user authentication (not needed for demo) Build Iteratively Backend first (can test with curl) Then minimal frontend (prove integration) Then polish UI (time permitting) Always have something demo-able Validate Early Tested with known repurposing cases (Sildenafil for pulmonary hypertension) Cross-referenced with PubMed papers Asked pharmacology experts (via Discord) Caught the dopamine antagonist bug before demo Demo-Driven Development What looks cool in a 2-minute demo? Live search with real-time results Actual drug names people recognize Clear visualizations of shared genes

### What's next

Immediate (Post-Hackathon) Technical Improvements Machine learning model trained on successful repurposing cases Drug combination analysis (synergistic effects) Molecular docking simulation for binding validation Batch processing for multiple diseases Data Expansion Add DrugBank (more drug details) Add SIDER (side effects database) Add STRING (protein interactions) Add patient stratification (pharmacogenomics) Product Features User accounts and saved queries Export to PDF/Excel Share results via URL API access for researchers Medium-Term (3-6 Months) Clinical Validation Partner with research labs to validate top predictions Run retrospective analysis on successful repurposing cases Publish findings in biomedical journals Present at computational biology conferences Platform Scale Handle 1000+ concurrent users Reduce first query time to <3 seconds Add real-time literature monitoring Mobile app (iOS/Android) Long-Term (1+ Year) Real-World Impact Partner with pharmaceutical companies Support 505(b)(2) regulatory submissions Fund clinical trials for top candidates Track drugs that go from Navara to FDA approval Academic Collaboration Open-source core algorithms Release dataset of validated predictions Build API for research community Create educational resources The Dream See a drug discovered by Navara AI enter clinical trials. Watch it get FDA approval. Know that patients with rare diseases have treatment because an AI found a connection that humans missed. That's why we built this.

## README (from the GitHub repository)

# Navara AI - Drug Repurposing Platform

A production-grade AI-powered platform for discovering new therapeutic applications of FDA-approved drugs using advanced computational biology and machine learning.

## Overview

Navara AI accelerates drug discovery by identifying repurposing opportunities for existing FDA-approved medications. The platform integrates six major biomedical databases and uses graph-based machine learning to discover novel drug-disease relationships in real-time.

### Key Features

- Real-time analysis of 25,000+ diseases against 15,000+ FDA-approved drugs
- Integration with six authoritative medical databases
- Safety filtering system that automatically removes contraindicated drugs
- Clinical validation engine with trial data and literature evidence
- Graph-based knowledge representation of drug-gene-disease relationships
- Sub-5-second query response time after initial cache build

## System Architecture

### Backend Stack

- **Framework**: FastAPI with async/await architecture
- **Data Sources**: 
  - OpenTargets Platform (disease-gene associations)
  - ChEMBL (FDA-approved drugs)
  - DGIdb (drug-gene interactions)
  - ClinicalTrials.gov (clinical trial data)
  - PubMed (scientific literature)
  - OpenFDA (adverse event reports)
- **Graph Engine**: NetworkX for biological network analysis
- **Machine Learning**: Custom scoring algorithms with multi-factor weighted analysis

### Frontend Stack

- **Framework**: React 18 with Vite
- **Styling**: TailwindCSS with custom terminal-inspired theme
- **UI Design**: Monospace typography, graph paper backgrounds, brutalist aesthetic

## Installation

### Prerequisites

- Python 3.9 or higher
- Node.js 18 or higher
- pip3 and npm package managers

### Quick Start

1. Clone the repository:
```bash
git clone <repository-url>
cd navara-ai
```

2. Run the automated setup:
```bash
chmod +x setup_production_apis.sh
./setup_production_apis.sh
```

3. Start the application:
```bash
chmod +x start.sh
./start.sh
```

4. Access the platform:
   - Frontend: http://localhost:3000
   - Backend API: http://localhost:8000
   - API Documentation: http://localhost:8000/docs

### Manual Installation

#### Backend Setup

```bash
cd backend
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt
uvicorn main:app --host 0.0.0.0 --port 8000
```

#### Frontend Setup

```bash
cd frontend
npm install
npm run dev
```

## Usage

### Basic Query

1. Enter a disease name (e.g., "Parkinson Disease")
2. Set minimum score threshold (default: 0.2)
3. Set maximum number of candidates (default: 10)
4. Click "Initiate Repurposing Analysis"

### Understanding Results

Each drug candidate includes:

- **Composite Score**: Overall match score (0-1 scale)
- **Confidence Level**: High, Medium, or Low based on evidence strength
- **Shared Genes**: Gene targets common to drug and disease
- **Shared Pathways**: Biological pathways modulated by both
- **Mechanism of Action**: How the drug works at molecular level
- **Clinical Validation**: Trial data, literature, safety signals

### Safety Filtering

The platform automatically filters drugs with:

- **Absolute Contraindications**: Never use (e.g., dopamine antagonists for Parkinson's)
- **Relative Contraindications**: Use with extreme caution (configurable)

Filtered drugs are displayed separately with clear explanations.

### Clinical Validation

Click "Validate Clinically" on any candidate to retrieve:

- Active clinical trials from ClinicalTrials.gov
- Published literature from PubMed
- Adverse event data from OpenFDA
- Mechanism compatibility analysis
- Overall risk assessment (Low/Medium/High)

## API Documentation

### POST /analyze

Analyze a disease and return drug repurposing candidates.

**Request Body:**
```json
{
  "disease_name": "string",
  "min_score": 0.2,
  "max_results": 10
}
```

**Response:**
```json
{
  "success": true,
  "disease": {
    "name": "string",
    "genes_count": 0,
    "pathways_count": 0,
    "top_genes": ["string"]
  },
  "candidates": [
    {
      "drug_name": "string",
      "score": 0.85,
      "confidence": "high",
      "shared_genes": ["string"],
      "shared_pathways": ["string"],
      "mechanism": "string",
      "explanation": "string"
    }
  ],
  "filtered_count": 0,
  "filtered_drugs": []
}
```

### POST /validate_clinical

Perform clinical validation on a drug-disease pair.

**Request Body:**
```json
{
  "drug_name": "string",
  "disease_name": "string",
  "drug_data": {},
  "disease_data": {}
}
```

**Response:**
```json
{
  "success": true,
  "validation": {
    "risk_level": "LOW",
    "recommendation": "string",
    "clinical_trials": {},
    "literature_evidence": {},
    "safety_signals": {},
    "mechanism_analysis": {}
  }
}
```

## Configuration

### Backend Configuration

Edit `backend/.env` (create if doesn't exist):

```env
# Server configuration
HOST=0.0.0.0
PORT=8000

# Cache configuration
CACHE_DIR=/tmp/drug_repurposing_cache
CACHE_DRUGS=true

# API rate limits
MAX_REQUESTS_PER_MINUTE=60

# Scoring thresholds
MIN_GENE_SCORE=0.1
MIN_PATHWAY_SCORE=0.1
```

### Frontend Configuration

Edit `frontend/vite.config.js`:

```javascript
export default defineConfig({
  server: {
    port: 3000,
    proxy: {
      '/api': {
        target: 'http://localhost:8000',
        changeOrigin: true,
      }
    }
  }
})
```

## Development

### Project Structure

```
navara-ai/
├── backend/
│   ├── main.py                 # FastAPI application
│   ├── models.py              # Pydantic data models
│   ├── requirements.txt       # Python dependencies
│   └── pipeline/
│       ├── data_fetcher.py    # Database integration
│       ├── graph_builder.py   # Knowledge graph construction
│       ├── scorer.py          # Scoring algorithms
│       ├── drug_filter.py     # Safety filtering
│       └── clinical_validator.py  # Clinical validation
├── frontend/
│   ├── src/
│   │   ├── App.jsx           # Main React component
│   │   ├── App.css           # Custom styles
│   │   └── main.jsx          # Entry point
│   ├── package.json          # Node dependencies
│   └── vite.config.js        # Vite configuration
├── start.sh                  # Startup script
├── stop.sh                   # Shutdown script
└── README.md                 # This file
```

### Running Tests

Backend tests:
```bash
cd backend
source venv/bin/activate
python -m pytest tests/
```

Database connectivity test:
```bash
cd backend
python test_production_apis.py
```

### Diagnostic Tools

Check why no candidates appear:
```bash
cd backend
python diagnose.py
```

Rebuild drug database cache:
```bash
python rebuild_database.py
```

## Performance Optimization

### First Query

- Duration: 5-10 seconds
- Reason: Building initial cache, fetching from APIs
- Impact: One-time operation per disease

### Subsequent Queries

- Duration: Less than 2 seconds
- Reason: Using cached data
- Impact: Production-ready response time

### Cache Management

Cache location: `/tmp/drug_repurposing_cache/`

Clear cache:
```bash
rm -rf /tmp/drug_repurposing_cache/
```

## Known Limitations

1. **Network Dependency**: Requires internet connection for initial data fetching
2. **Cache Persistence**: Cache stored in /tmp may be cleared on system restart
3. **API Rate Limits**: Some external APIs have rate limits (handled with exponential backoff)
4. **Disease Name Matching**: Requires exact or close disease names from OpenTargets database
5. **DGIdb Coverage**: Not all drugs have gene target information available

## Troubleshooting

### Backend fails to start

Check logs:
```bash
cat backend.log
```

Common issues:
- Port 8000 already in use: `lsof -ti:8000 | xargs kill -9`
- Missing dependencies: `pip install -r requirements.txt`
- Python version: Ensure Python 3.9+

### Frontend fails to start

Check logs:
```bash
cat frontend.log
```

Common issues:
- Port 3000 already in use: `lsof -ti:3000 | xargs kill -9`
- Missing node_modules: `cd fr

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 28 recognized source files, 209 KB.
- Anthropic (technology) — detected in the code
- CSS (language) — detected in the code
- FastAPI (technology) — 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
- Tailwind CSS (technology) — detected in the code
- Node.js (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (37 of 37)

```
.gitignore
backend/diagnose_backend.py
backend/diagnose.py
backend/main.py
backend/models.py
backend/pip.pyz
backend/pipeline/__init__.py
backend/pipeline/clinical_validator.py
backend/pipeline/data_fetcher.py
backend/pipeline/drug_filter.py
backend/pipeline/graph_builder.py
backend/pipeline/llm_explainer.py
backend/pipeline/production_pipeline.py
backend/pipeline/scorer.py
backend/requirements_clinical.txt
backend/requirements.txt
backend/test_databases.py
backend/test_dgidb_comprehensive.py
backend/test_diseases.py
backend/test_production_apis.py
backend/test_results.txt
frontend/index.html
frontend/package-lock 2.json
frontend/package.json
frontend/Postcss.config.js
frontend/src/App.css
frontend/src/App.css 
frontend/src/App.jsx
frontend/src/index.css
frontend/src/index.css 
frontend/src/main.jsx
frontend/tailwind.config.js
frontend/vite.config.js
README.md
setup_production_apis.sh
start.sh
stop.sh
```

### Dependencies

- backend/requirements.txt: aiohttp@==3.10.5, aiosqlite@==0.20.0, anthropic@==0.40.0, certifi@==2024.8.30, fastapi@==0.115.0, httpx@==0.26.0, networkx@==3.3, numpy@==1.26.4, pydantic@==2.9.2, pytest@==7.4.4, pytest-asyncio@==0.23.0, python-dotenv@==1.0.1, requests@==2.31.0, scipy@>=1.14.1, sqlalchemy@==2.0.23, tenacity@==8.2.3, uvicorn[standard]@==0.30.6
- frontend/package.json: @types/react@^18.2.43, @types/react-dom@^18.2.17, @vitejs/plugin-react@^4.2.1, autoprefixer@^10.4.16, postcss@^8.4.32, react@^18.2.0, react-dom@^18.2.0, tailwindcss@^3.4.0, vite@^5.0.8

### Recent commits (newest first)

- Update README.md
- final code
- ui changes and fixed filtering
- fix filter
- new files
- filter fix
- new code with filtering
- new changes
- fixing scoring and making scientifically accurate
- fixed dgidb api
- new code
- connect frontend to backend
- fix database API
- add public databases not manual
- new code

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

### frontend/package.json

```
{
  "name": "drug-repurposing-frontend",
  "private": true,
  "version": "2.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/react": "^18.2.43",
    "@types/react-dom": "^18.2.17",
    "@vitejs/plugin-react": "^4.2.1",
    "autoprefixer": "^10.4.16",
    "postcss": "^8.4.32",
    "tailwindcss": "^3.4.0",
    "vite": "^5.0.8"
  }
}
```

### backend/requirements.txt

```
# Production Requirements for Drug Repurposing Platform
# All packages are open-source and free to use

# Web Framework
fastapi==0.115.0
uvicorn[standard]==0.30.6

# HTTP Client (for API calls) - WITH SSL FIX
aiohttp==3.10.5
certifi==2024.8.30  # Up-to-date SSL certificates
requests==2.31.0

# Data Processing
pydantic==2.9.2
python-dotenv==1.0.1

# Graph Analysis
networkx==3.3

# Database & Caching
aiosqlite==0.20.0
sqlalchemy==2.0.23

# Scientific Computing
numpy==1.26.4
scipy>=1.14.1

# Anthropic API (for AI explanations)
anthropic==0.40.0

# Rate Limiting & Retry Logic
tenacity==8.2.3

# Testing
pytest==7.4.4
pytest-asyncio==0.23.0
httpx==0.26.0
```

### backend/main.py

```python
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import logging
from pipeline.production_pipeline import ProductionPipeline
from pipeline.clinical_validator import ClinicalValidator
from pipeline.drug_filter import DrugSafetyFilter

# Set up logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

app = FastAPI(
    title="Drug Repurposing API",
    description="AI-powered drug repurposing using gene-disease relationships",
    version="2.0.0"
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Global pipeline instance
pipeline = None

@app.on_event("startup")
async def startup_event():
    """Initialize the pipeline on startup."""
    global pipeline
    logger.info("🚀 Starting Drug Repurposing API...")
    logger.info("📊 Databases: OpenTargets, ChEMBL, DGIdb, ClinicalTrials.gov")
    try:
        pipeline = ProductionPipeline()
        # ProductionPipeline initializes itself in __init__, no separate initialize() needed
        logger.info("✅ API ready!")
    except Exception as e:
        logger.error(f"❌ Failed to initialize pipeline: {e}")
        raise

@app.on_event("shutdown")
async def shutdown_event():
    """Clean up on shutdown."""
    global pipeline
    # ProductionPipeline doesn't have a close() method
    logger.info("👋 API shutdown complete")

@app.get("/", tags=["Health"])
async def root():
    """Health check endpoint."""
    return {
        "status": "online",
        "service": "Drug Repurposing API",
        "version": "2.0.0"
    }

@app.post("/analyze", tags=["Analysis"])
async def analyze_disease(request: dict):
    """
    Analyze a disease and find repurposing candidates with safety filtering.
    """
    global pipeline
    
    if not pipeline:
        return {
            "success": False,
            "error": "Pipeline not initialized"
        }
    
    try:
        disease_name = request.get('disease_name')
        min_score = request.get('min_score', 0.2)
        max_results = request.get('max_results', 10)
        
        if not disease_name:
            return {
                "success": False,
                "error": "Missing disease_name"
            }
        
        logger.info(f"Analysis request: {disease_name}")
        
        # Run gene-based analysis
        result = await pipeline.analyze_disease(
            disease_name=disease_name,
            min_score=min_score,
            max_results=max_results * 2  # Get extra candidates before filtering
        )
        
        if not result['success']:
            return result
        
        # ⭐ FIX: Ensure candidates have the required fields for filtering
        candidates = result.get('candidates', [])
        for candidate in candidates:
            # Ensure 'indication' field exists (drug_filter expects 'indication')
            if 'indication' not in candidate and 'original_indication' in candidate:
                candidate['indication'] = candidate['original_indication']
            elif 'indication' not in candidate:
                candidate['indication'] = ''
            
            # Ensure 'mechanism' field exists
            if 'mechanism' not in candidate:
                candidate['mechanism'] = ''
        
        # ⭐ FIXED: Apply safety filter with CORRECT settings
        safety_filter = DrugSafetyFilter()
        
        original_count = len(candidates)
        
        try:
            # FIXED: Set remove_relative=True to filter out ALL contraindicated drugs
            # This is critical for safety - "relative" contraindications like olanzapine
            # for diabetes or beta-blockers for asthma are still dangerous!
            safe_candidates, filtered_out = await safety_filter.filter_candidates(
                candidates=candidates,
                disease_name=disease_name,
                remove_absolute=True,   # Remove absolutely contraindicated
                remove_relative=True    # FIXED: Also remove relatively contraindicated (was False!)
            )
            
            # Limit to requested max_results after filtering
            safe_candidates = safe_candidates[:max_results]
            
            logger.info(
                f"Safety filter: {original_count} → {len(safe_candidates)} candidates "
                f"({len(filtered_out)} filtered out)"
            )
            
            # Update result with filtered candidates
            result['candidates'] = safe_candidates
            result['filtered_count'] = len(filtered_out)
            result['filtered_drugs'] = [
                {
                    'drug_name': c['drug_name'],
                    'reason': c.get('contraindication', {}).get('reason', 'Unknown'),
                    'severity': c.get('contraindication', {}).get('severity', 'unknown')
                }
                for c in filtered_out
            ]
            
        except Exception as filter_error:
            logger.error(f"Safety filter error: {filter_error}")
            # If filtering fails, return unfiltered results with warning
            result['candidates'] = candidates[:max_results]
            result['filtered_count'] = 0
            result['filtered_drugs'] = []
            result['filter_warning'] = f"Safety filter error: {str(filter_error)}"
        
        return result
    
    except Exception as e:
        logger.error(f"Analysis error: {e}")
        import traceback
        traceback.print_exc()
        
        return {
            "success": False,
            "error": str(e)
        }

@app.post("/validate_clinical", tags=["Analysis"])
async def validate_clinical(request: dict):
    """
    Validate a drug candidate clinically using multiple databases.
    
    Checks:
    - Clinical trials (ClinicalTrials.gov)
    - 
[truncated — 1536 more characters]
```

### frontend/src/main.jsx

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

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)
```

### frontend/src/App.jsx

```javascript
import React, { useState, useEffect } from 'react';
import './App.css';

function App() {
  const [diseaseName, setDiseaseName] = useState('');
  const [maxResults, setMaxResults] = useState(10);
  const [minScore, setMinScore] = useState(0.2);
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState(null);
  const [error, setError] = useState(null);
  const [loadingMessage, setLoadingMessage] = useState('');
  const [validatingIndex, setValidatingIndex] = useState(null);
  const [clinicalResults, setClinicalResults] = useState({});

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setResults(null);
    setClinicalResults({});
    setLoadingMessage('🔍 Searching for disease in database...');

    try {
      const response = await fetch('http://localhost:8000/analyze', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          disease_name: diseaseName,
          min_score: minScore,
          max_results: maxResults,
        }),
      });

      const data = await response.json();

      if (!data.success) {
        setError({
          message: data.error || 'An error occurred',
          suggestion: data.suggestion || 'Please try again with a different disease name.'
        });
        setLoadingMessage('');
        setLoading(false);
        return;
      }

      setResults(data);
      setLoadingMessage('');
      
    } catch (err) {
      console.error('Error:', err);
      setError({
        message: 'Failed to connect to server',
        suggestion: 'Please make sure the backend server is running on port 8000.'
      });
      setLoadingMessage('');
    } finally {
      setLoading(false);
    }
  };

  const handleClinicalValidation = async (candidate, index) => {
    setValidatingIndex(index);
    
    try {
      const response = await fetch('http://localhost:8000/validate_clinical', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          drug_name: candidate.drug_name,
          disease_name: results.disease.name,
          drug_data: {
            mechanism: candidate.mechanism,
            indication: candidate.indication
          },
          disease_data: {
            name: results.disease.name,
            description: results.disease.description
          }
        }),
      });

      const data = await response.json();

      if (data.success) {
        setClinicalResults(prev => ({
          ...prev,
          [index]: data.validation
        }));
      } else {
        setClinicalResults(prev => ({
          ...prev,
          [index]: {
            error: data.error || 'Validation failed'
          }
        }));
      }
    } catch (err) {
      console.error('Clinical validation error:', err);
      setClinicalResults(prev => ({
        ...prev,
        [index]: {
          error: 'Failed to connect to validation service'
        }
      }));
    } finally {
      setValidatingIndex(null);
    }
  };

  const getRiskColor = (riskLevel) => {
    switch(riskLevel) {
      case 'LOW': return '#10b981';
      case 'MEDIUM': return '#f59e0b';
      case 'HIGH': return '#ef4444';
      default: return '#6b7280';
    }
  };

  const getScoreColor = (score) => {
    if (score >= 0.7) return '#10b981';
    if (score >= 0.5) return '#f59e0b';
    return '#ef4444';
  };

  const getConfidenceBadge = (confidence) => {
    const colors = {
      high: 'bg-green-500 text-white',
      medium: 'bg-yellow-500 text-white',
      low: 'bg-red-500 text-white',
    };
    return colors[confidence?.toLowerCase()] || colors.low;
  };

  useEffect(() => {
    if (results) {
      const molecules = document.querySelectorAll('.molecule-3d');
      molecules.forEach((mol, i) => {
        mol.style.animation = `rotate3d ${3 + i * 0.5}s linear infinite`;
      });
    }
  }, [results]);

  return (
    <div className="min-h-screen relative overflow-hidden">
      {/* Graph paper background */}
      <div className="graph-paper-bg"></div>

      <div className="container mx-auto px-4 py-8 max-w-7xl relative z-10">
        {/* Header */}
        <div className="text-center mb-12">
          <h1 className="text-6xl font-black mb-4 glitch-text" data-text="Navara AI">
            🧬 NAVARA AI
          </h1>
          <p className="text-xl font-mono" style={{ letterSpacing: '0.1em' }}>
            {'>'} AI-POWERED THERAPEUTIC DISCOVERY SYSTEM {'<'}
          </p>
          <div className="mt-4 flex justify-center gap-4 flex-wrap">
            <div className="status-indicator">
              <span className="status-dot"></span>
              <span className="text-sm font-mono font-bold">DATABASES: ONLINE</span>
            </div>
            <div className="status-indicator">
              <span className="status-dot"></span>
              <span className="text-sm font-mono font-bold">AI: ACTIVE</span>
            </div>
          </div>
        </div>

        {/* Input Form */}
        <div className="terminal-window mb-8">
          <div className="terminal-header">
            <div className="flex items-center gap-2">
              <div className="w-3 h-3 rounded-full bg-red-500"></div>
              <div className="w-3 h-3 rounded-full bg-yellow-500"></div>
              <div className="w-3 h-3 rounded-full bg-green-500"></div>
            </div>
            <div className="font-mono text-sm">
              QUERY_INTERFACE.EXE
            </div>
          </div>
          
          <div className="terminal-body">
            <form onSubmit={handleSubmit} className="space-y-6">
              <div>
                <label className="block font-mono mb-2 text-sm font-bold" style={{ letterSpacing: '0.1em' }}>
                  {'>'} TARGET_DISEASE:
                </label>
                <input
                  type="text"
       
[truncated — 22549 more characters]
```

### stop.sh

```shell
#!/bin/bash

echo "🛑 Stopping AI Drug Repurposing Engine..."

# Check if PID files exist
if [ -f ".backend.pid" ]; then
    BACKEND_PID=$(cat .backend.pid)
    if ps -p $BACKEND_PID > /dev/null 2>&1; then
        echo "Stopping backend (PID: $BACKEND_PID)..."
        kill $BACKEND_PID
        echo "✅ Backend stopped"
    else
        echo "⚠️  Backend process not found"
    fi
    rm .backend.pid
else
    echo "⚠️  No backend PID file found"
fi

if [ -f ".frontend.pid" ]; then
    FRONTEND_PID=$(cat .frontend.pid)
    if ps -p $FRONTEND_PID > /dev/null 2>&1; then
        echo "Stopping frontend (PID: $FRONTEND_PID)..."
        kill $FRONTEND_PID
        echo "✅ Frontend stopped"
    else
        echo "⚠️  Frontend process not found"
    fi
    rm .frontend.pid
else
    echo "⚠️  No frontend PID file found"
fi

# Also kill any remaining processes on the ports
echo ""
echo "Checking for processes on ports 8000 and 3000..."
lsof -ti:8000 | xargs kill -9 2>/dev/null && echo "✅ Killed remaining processes on port 8000" || echo "No processes on port 8000"
lsof -ti:3000 | xargs kill -9 2>/dev/null && echo "✅ Killed remaining processes on port 3000" || echo "No processes on port 3000"

echo ""
echo "✅ All services stopped!"
```

### start.sh

```shell
#!/bin/bash

echo "🧬 AI Drug Repurposing Engine - Startup Script"
echo "=============================================="
echo ""

# Check if we're in the right directory
if [ ! -f "README.md" ]; then
    echo "❌ Error: Please run this script from the drug-repurposing-app directory"
    exit 1
fi

# Function to check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Check Python
if ! command_exists python3; then
    echo "❌ Python 3 is not installed. Please install Python 3.9 or higher."
    exit 1
fi

echo "✅ Python found: $(python3 --version)"

# Check Node
if ! command_exists node; then
    echo "❌ Node.js is not installed. Please install Node.js 18 or higher."
    exit 1
fi

echo "✅ Node.js found: $(node --version)"

# Setup backend
echo ""
echo "📦 Setting up backend..."
cd backend

# Create virtual environment if it doesn't exist
if [ ! -d "venv" ]; then
    echo "Creating Python virtual environment..."
    python3 -m venv venv
fi

# Activate virtual environment
source venv/bin/activate

# Install backend dependencies
echo "Installing backend dependencies..."
pip install -q -r requirements.txt

echo "✅ Backend setup complete!"

# Start backend in background
echo ""
echo "🚀 Starting backend server on http://localhost:8000..."
uvicorn main:app --host 0.0.0.0 --port 8000 > ../backend.log 2>&1 &
BACKEND_PID=$!
echo "Backend PID: $BACKEND_PID"

# Wait for backend to start
sleep 3

# Check if backend is running
if ps -p $BACKEND_PID > /dev/null; then
    echo "✅ Backend server started successfully!"
else
    echo "❌ Backend failed to start. Check backend.log for errors."
    exit 1
fi

# Setup frontend
echo ""
echo "📦 Setting up frontend..."
cd ../frontend

# Install frontend dependencies if node_modules doesn't exist
if [ ! -d "node_modules" ]; then
    echo "Installing frontend dependencies (this may take a minute)..."
    npm install
fi

echo "✅ Frontend setup complete!"

# Start frontend
echo ""
echo "🚀 Starting frontend server on http://localhost:3000..."
npm run dev > ../frontend.log 2>&1 &
FRONTEND_PID=$!
echo "Frontend PID: $FRONTEND_PID"

# Wait for frontend to start
sleep 3

# Save PIDs to file for cleanup
cd ..
echo $BACKEND_PID > .backend.pid
echo $FRONTEND_PID > .frontend.pid

echo ""
echo "=============================================="
echo "✨ Application is now running!"
echo "=============================================="
echo ""
echo "🌐 Frontend: http://localhost:3000"
echo "🔧 Backend:  http://localhost:8000"
echo "📊 API Docs: http://localhost:8000/docs"
echo ""
echo "📝 Logs:"
echo "   Backend:  tail -f backend.log"
echo "   Frontend: tail -f frontend.log"
echo ""
echo "🛑 To stop the application, run: ./stop.sh"
echo ""
echo "Press Ctrl+C to view logs (servers will continue running)"
echo ""

# Follow logs
tail -f backend.log frontend.log
```

### setup_production_apis.sh

```shell
#!/bin/bash

echo ""
echo "╔══════════════════════════════════════════════════════════════════╗"
echo "║   🧬 Drug Repurposing Platform - Production API Setup          ║"
echo "╚══════════════════════════════════════════════════════════════════╝"
echo ""

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}🔧 Step 1: Checking prerequisites...${NC}"
echo ""

# Check Python
if ! command -v python3 &> /dev/null; then
    echo -e "${RED}❌ Python 3 is not installed${NC}"
    exit 1
fi

PYTHON_VERSION=$(python3 --version | cut -d' ' -f2)
echo -e "${GREEN}✅ Python $PYTHON_VERSION found${NC}"

# Check pip
if ! command -v pip3 &> /dev/null; then
    echo -e "${RED}❌ pip3 is not installed${NC}"
    exit 1
fi

echo -e "${GREEN}✅ pip3 found${NC}"

echo ""
echo -e "${BLUE}📦 Step 2: Installing Python dependencies with SSL support...${NC}"
echo ""

cd backend

# Create virtual environment if it doesn't exist
if [ ! -d "venv" ]; then
    echo "   Creating virtual environment..."
    python3 -m venv venv
fi

# Activate virtual environment
source venv/bin/activate

# Upgrade pip and install wheel
echo "   Upgrading pip..."
pip install --upgrade pip wheel setuptools -q

# Install certifi first (SSL certificates)
echo "   Installing SSL certificates..."
pip install --upgrade certifi

# Install production requirements
echo "   Installing production requirements..."
if [ -f "requirements_production.txt" ]; then
    pip install -r requirements_production.txt
else
    pip install -r requirements.txt
fi

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ Python dependencies installed${NC}"
else
    echo -e "${RED}❌ Failed to install Python dependencies${NC}"
    exit 1
fi

# Verify SSL setup
echo ""
echo -e "${BLUE}🔒 Step 3: Verifying SSL certificate setup...${NC}"
echo ""

python3 << 'PYTHON_CHECK'
import ssl
import certifi

print(f"   OpenSSL version: {ssl.OPENSSL_VERSION}")
print(f"   Certifi CA bundle: {certifi.where()}")
print(f"   ✅ SSL is properly configured")
PYTHON_CHECK

echo ""
echo -e "${BLUE}🧪 Step 4: Testing database connections...${NC}"
echo ""
echo "   This will test: OpenTargets, ChEMBL, DGIdb, ClinicalTrials.gov"
echo "   Expected duration: 30-90 seconds"
echo ""

# Copy production data fetcher if it exists
if [ -f "pipeline/data_fetcher_production.py" ]; then
    echo "   Using production data fetcher..."
    cp pipeline/data_fetcher_production.py pipeline/data_fetcher.py
fi

# Run production API tests
python3 test_production_apis.py

TEST_RESULT=$?

cd ..

if [ $TEST_RESULT -eq 0 ]; then
    echo ""
    echo -e "${GREEN}✅ Database connections working!${NC}"
else
    echo ""
    echo -e "${YELLOW}⚠️  Some tests may have failed${NC}"
    echo "   Check output above for details"
    echo "   The app may still work with partial functionality"
fi

echo ""
echo -e "${BLUE}📦 Step 5: Installing frontend dependencies...${NC}"
echo ""

cd frontend

if [ ! -d "node_modules" ]; then
    echo "   Installing npm packages..."
    npm install -q
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ Frontend dependencies installed${NC}"
    else
        echo -e "${RED}❌ Failed to install frontend dependencies${NC}"
        exit 1
    fi
else
    echo -e "${GREEN}✅ Frontend dependencies already installed${NC}"
fi

cd ..

echo ""
echo "╔══════════════════════════════════════════════════════════════════╗"
echo "║                     ✅ SETUP COMPLETE! 🎉                        ║"
echo "╚══════════════════════════════════════════════════════════════════╝"
echo ""
echo -e "${GREEN}Your production platform is ready with REAL database access!${NC}"
echo ""
echo "📊 Database Coverage:"
echo "   • 25,000+ diseases from OpenTargets"
echo "   • 15,000+ FDA-approved drugs from ChEMBL"
echo "   • 50,000+ drug-gene interactions from DGIdb"
echo "   • Real-time clinical trial data from ClinicalTrials.gov"
echo ""
echo "🚀 To start the platform:"
echo ""
echo "   ./start.sh"
echo ""
echo "   Then open: http://localhost:3000"
echo ""
echo "🔬 Try searching for:"
echo "   • Huntington Disease"
echo "   • Parkinson Disease"
echo "   • Gaucher Disease"
echo "   • Wilson Disease"
echo "   • Duchenne Muscular Dystrophy"
echo ""
echo "💡 Tips:"
echo "   • First query may take 5-10 seconds (building cache)"
echo "   • Subsequent queries will be faster (<2 seconds)"
echo "   • Use min_score = 0.2-0.3 for rare diseases"
echo ""
echo -e "${YELLOW}Note: If you see SSL errors, the fallback local database will be used${NC}"
echo ""
```

### frontend/Postcss.config.js

```javascript
export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}
```

### frontend/tailwind.config.js

```javascript
/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
```

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