← back to divyamohan1993__janani-suraksha

Function bodies 95 total

All specs Real LLM only Function bodies
set_engines function · python · L44-L48 (5 LOC)
app/api/v1/routes.py
def set_engines(risk_engine, referral_engine, anemia_engine):
    global _risk_engine, _referral_engine, _anemia_engine
    _risk_engine = risk_engine
    _referral_engine = referral_engine
    _anemia_engine = anemia_engine
set_real_facilities function · python · L51-L53 (3 LOC)
app/api/v1/routes.py
def set_real_facilities(finder: RealFacilityFinder):
    global _real_facilities
    _real_facilities = finder
health_check function · python · L57-L66 (10 LOC)
app/api/v1/routes.py
async def health_check():
    return {
        "status": "healthy",
        "version": "1.0.0",
        "engines_loaded": {
            "risk_scoring": _risk_engine.is_loaded if _risk_engine else False,
            "referral_routing": _referral_engine.is_loaded if _referral_engine else False,
            "anemia_prediction": _anemia_engine.is_loaded if _anemia_engine else False,
        }
    }
risk_score function · python · L70-L87 (18 LOC)
app/api/v1/routes.py
async def risk_score(factors: RiskFactors):
    """O(1) Bayesian maternal risk scoring."""
    if not _risk_engine:
        raise HTTPException(status_code=503, detail="Risk engine not loaded")

    result = _risk_engine.score(
        age=factors.age,
        parity=factors.parity,
        hemoglobin=factors.hemoglobin,
        bp_systolic=factors.bp_systolic,
        bp_diastolic=factors.bp_diastolic,
        gestational_weeks=factors.gestational_weeks,
        height_cm=factors.height_cm,
        weight_kg=factors.weight_kg,
        complication_history=factors.complication_history.value,
    )
    result["disclaimer"] = DEMO_DISCLAIMER
    return result
referral_route function · python · L91-L103 (13 LOC)
app/api/v1/routes.py
async def referral_route(request: ReferralRequest):
    """O(1) emergency referral routing."""
    if not _referral_engine:
        raise HTTPException(status_code=503, detail="Referral engine not loaded")

    result = _referral_engine.route(
        latitude=request.latitude,
        longitude=request.longitude,
        capability_required=request.capability_required.value,
        risk_level=request.risk_level.value,
    )
    result["disclaimer"] = DEMO_DISCLAIMER
    return result
anemia_predict function · python · L107-L120 (14 LOC)
app/api/v1/routes.py
async def anemia_predict(input_data: AnemiaInput):
    """O(1) anemia progression prediction."""
    if not _anemia_engine:
        raise HTTPException(status_code=503, detail="Anemia engine not loaded")

    result = _anemia_engine.predict(
        initial_hb=input_data.initial_hb,
        gestational_weeks=input_data.gestational_weeks,
        ifa_compliance=input_data.ifa_compliance,
        dietary_score=input_data.dietary_score,
        prev_anemia=input_data.prev_anemia,
    )
    result["disclaimer"] = DEMO_DISCLAIMER
    return result
full_assessment function · python · L124-L211 (88 LOC)
app/api/v1/routes.py
async def full_assessment(request: AssessmentRequest):
    """Complete ASHA worker assessment flow combining all three engines."""
    if not _risk_engine or not _referral_engine or not _anemia_engine:
        raise HTTPException(status_code=503, detail="Engines not loaded")

    # Step 1: Risk scoring
    risk = _risk_engine.score(
        age=request.risk_factors.age,
        parity=request.risk_factors.parity,
        hemoglobin=request.risk_factors.hemoglobin,
        bp_systolic=request.risk_factors.bp_systolic,
        bp_diastolic=request.risk_factors.bp_diastolic,
        gestational_weeks=request.risk_factors.gestational_weeks,
        height_cm=request.risk_factors.height_cm,
        weight_kg=request.risk_factors.weight_kg,
        complication_history=request.risk_factors.complication_history.value,
    )

    # Step 2: Anemia prediction (if Hb < 11)
    anemia = None
    if request.risk_factors.hemoglobin < 11.0:
        anemia = _anemia_engine.predict(
            initial
Repobility · severity-and-effort ranking · https://repobility.com
list_facilities function · python · L215-L219 (5 LOC)
app/api/v1/routes.py
async def list_facilities():
    """List all facilities for dashboard map."""
    if not _referral_engine:
        raise HTTPException(status_code=503, detail="Referral engine not loaded")
    return {"facilities": _referral_engine.get_all_facilities()}
nearby_facilities function · python · L223-L245 (23 LOC)
app/api/v1/routes.py
async def nearby_facilities(
    lat: float = Query(..., description="Latitude"),
    lon: float = Query(..., description="Longitude"),
    radius_km: float = Query(25.0, description="Search radius in km"),
    type: str = Query("hospital", description="Facility type filter"),
):
    """Find real nearby health facilities using data.gov.in + geocoding."""
    if not _real_facilities:
        raise HTTPException(status_code=503, detail="Real facilities finder not initialized")

    try:
        facilities = await _real_facilities.find_nearby(lat, lon, radius_km)
    except Exception as e:
        raise HTTPException(status_code=502, detail=f"Failed to fetch facility data: {str(e)}")

    return {
        "facilities": facilities,
        "count": len(facilities),
        "search_center": {"lat": lat, "lon": lon},
        "radius_km": radius_km,
        "source": "data.gov.in National Hospital Directory",
        "disclaimer": DEMO_DISCLAIMER,
    }
Settings class · python · L5-L30 (26 LOC)
app/config.py
class Settings(BaseSettings):
    app_name: str = "JananiSuraksha"
    app_version: str = "1.0.0"
    debug: bool = False

    # Security
    allowed_origins: list[str] = ["https://jananisuraksha.dmj.one"]
    rate_limit_per_minute: int = 100
    api_key_header: str = "X-API-Key"
    api_keys: list[str] = []  # Empty = no auth required (demo mode)

    # Risk thresholds (from spec)
    risk_threshold_low: float = 0.01
    risk_threshold_medium: float = 0.05
    risk_threshold_high: float = 0.15

    # Engine paths
    risk_table_path: str = "data/risk_table.json"
    facility_graph_path: str = "data/facility_graph.json"
    hb_trajectories_path: str = "data/hb_trajectories.json"

    # External API keys (loaded from .env)
    google_maps_api_key: str = ""
    data_gov_api_key: str = ""

    model_config = {"env_prefix": "JANANI_", "env_file": ".env"}
AnemiaPredictionEngine class · python · L6-L172 (167 LOC)
app/engines/anemia_prediction.py
class AnemiaPredictionEngine:
    """O(1) anemia progression prediction via learned index on hemoglobin trajectories.

    Maps maternal health features to position in sorted array of historical
    hemoglobin trajectories. Predicts future Hb levels and intervention urgency.
    """

    # WHO pregnancy hemoglobin thresholds
    SEVERE_ANEMIA = 7.0
    MODERATE_ANEMIA = 9.0
    MILD_ANEMIA = 11.0
    NORMAL_HB = 12.0

    def __init__(self):
        self._trajectories: list[dict] = []
        self._index: dict[str, int] = {}  # feature_key -> position in sorted array
        self._loaded = False

    def load(self, path: str) -> None:
        """Load precomputed trajectory array and learned index."""
        with open(path) as f:
            data = json.load(f)
        self._trajectories = data["trajectories"]
        self._index = data["index"]
        self._loaded = True

    @staticmethod
    def _discretize_features(initial_hb: float, gest_weeks: int,
                              
__init__ method · python · L19-L22 (4 LOC)
app/engines/anemia_prediction.py
    def __init__(self):
        self._trajectories: list[dict] = []
        self._index: dict[str, int] = {}  # feature_key -> position in sorted array
        self._loaded = False
load method · python · L24-L30 (7 LOC)
app/engines/anemia_prediction.py
    def load(self, path: str) -> None:
        """Load precomputed trajectory array and learned index."""
        with open(path) as f:
            data = json.load(f)
        self._trajectories = data["trajectories"]
        self._index = data["index"]
        self._loaded = True
_discretize_features method · python · L33-L49 (17 LOC)
app/engines/anemia_prediction.py
    def _discretize_features(initial_hb: float, gest_weeks: int,
                              ifa_compliance: float, dietary_score: float,
                              prev_anemia: bool) -> str:
        """Discretize input features into lookup key."""
        # Discretize each dimension
        hb_bucket = min(int((initial_hb - 3.0) / 1.0), 16)  # 1 g/dL buckets, 3-19
        hb_bucket = max(0, hb_bucket)

        gest_bucket = min(gest_weeks // 4, 10)  # 4-week buckets, 0-40

        ifa_bucket = min(int(ifa_compliance * 4), 4)  # 0, 0.25, 0.5, 0.75, 1.0

        diet_bucket = min(int(dietary_score * 3), 3)  # 0, 0.33, 0.67, 1.0

        anemia_flag = 1 if prev_anemia else 0

        return f"{hb_bucket}:{gest_bucket}:{ifa_bucket}:{diet_bucket}:{anemia_flag}"
predict method · python · L51-L71 (21 LOC)
app/engines/anemia_prediction.py
    def predict(self, initial_hb: float, gestational_weeks: int,
                ifa_compliance: float, dietary_score: float,
                prev_anemia: bool) -> dict:
        """O(1) hemoglobin trajectory prediction.

        Returns dict with: current_hb, predicted_delivery_hb, trajectory,
        risk_level, intervention_urgency, compliance_impact
        """
        key = self._discretize_features(initial_hb, gestational_weeks,
                                         ifa_compliance, dietary_score, prev_anemia)

        # O(1) index lookup
        if key in self._index:
            pos = self._index[key]
            if 0 <= pos < len(self._trajectories):
                traj = self._trajectories[pos]
                return self._format_result(traj, initial_hb, gestational_weeks, ifa_compliance)

        # Fallback: compute trajectory analytically
        return self._compute_trajectory(initial_hb, gestational_weeks,
                                         ifa_compliance, dietary
Repobility — same analyzer, your code, free for public repos · /scan/
_compute_trajectory method · python · L73-L152 (80 LOC)
app/engines/anemia_prediction.py
    def _compute_trajectory(self, initial_hb: float, gest_weeks: int,
                            ifa_compliance: float, dietary_score: float,
                            prev_anemia: bool) -> dict:
        """Compute Hb trajectory analytically (fallback and precomputation base)."""

        # Physiological Hb drop during pregnancy (hemodilution effect)
        # Peak plasma volume expansion at 28-34 weeks causes ~1-2 g/dL Hb drop
        # Recovery begins around 36 weeks

        # Base decline rate (without supplementation)
        base_decline_per_week = 0.05  # g/dL per week

        # IFA supplementation effect (iron folic acid)
        ifa_effect = ifa_compliance * 0.04  # Compliance reduces decline

        # Dietary contribution
        diet_effect = dietary_score * 0.02  # Good diet reduces decline

        # Previous anemia increases vulnerability
        anemia_penalty = 0.02 if prev_anemia else 0.0

        # Net weekly change
        net_decline = base_decline_per_week - i
_format_result method · python · L154-L164 (11 LOC)
app/engines/anemia_prediction.py
    def _format_result(self, traj: dict, initial_hb: float,
                       gest_weeks: int, ifa_compliance: float) -> dict:
        """Format a precomputed trajectory into the standard result."""
        return {
            "current_hb": round(initial_hb, 1),
            "predicted_delivery_hb": traj["predicted_delivery_hb"],
            "trajectory": traj["trajectory"],
            "risk_level": traj["risk_level"],
            "intervention_urgency": traj["intervention_urgency"],
            "compliance_impact": traj["compliance_impact"],
        }
RealFacilityFinder class · python · L34-L199 (166 LOC)
app/engines/real_facilities.py
class RealFacilityFinder:
    """Finds real health facilities from pre-fetched data.gov.in data + Google Maps geocoding."""

    def __init__(self, google_maps_key: str = "", data_gov_key: str = ""):
        self._google_maps_key = google_maps_key
        self._data_gov_key = data_gov_key
        self._facilities: dict[str, list[dict]] = {}
        self._geocode_cache: dict[str, tuple] = {}
        self._loaded = False

    def load(self, path: str) -> None:
        """Load pre-fetched facility data from JSON file."""
        p = Path(path)
        if p.exists():
            with open(p) as f:
                self._facilities = json.load(f)
            total = sum(len(v) for v in self._facilities.values())
            logger.info(f"Loaded {total} real facilities across "
                        f"{len(self._facilities)} states from {p.name}")
            self._loaded = True
        else:
            logger.warning(f"Real facility data not found at {path}")

    @staticmethod
    def _h
__init__ method · python · L37-L42 (6 LOC)
app/engines/real_facilities.py
    def __init__(self, google_maps_key: str = "", data_gov_key: str = ""):
        self._google_maps_key = google_maps_key
        self._data_gov_key = data_gov_key
        self._facilities: dict[str, list[dict]] = {}
        self._geocode_cache: dict[str, tuple] = {}
        self._loaded = False
load method · python · L44-L55 (12 LOC)
app/engines/real_facilities.py
    def load(self, path: str) -> None:
        """Load pre-fetched facility data from JSON file."""
        p = Path(path)
        if p.exists():
            with open(p) as f:
                self._facilities = json.load(f)
            total = sum(len(v) for v in self._facilities.values())
            logger.info(f"Loaded {total} real facilities across "
                        f"{len(self._facilities)} states from {p.name}")
            self._loaded = True
        else:
            logger.warning(f"Real facility data not found at {path}")
_haversine method · python · L58-L65 (8 LOC)
app/engines/real_facilities.py
    def _haversine(lat1, lon1, lat2, lon2):
        R = 6371
        dlat = math.radians(lat2 - lat1)
        dlon = math.radians(lon2 - lon1)
        a = (math.sin(dlat / 2) ** 2 +
             math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *
             math.sin(dlon / 2) ** 2)
        return R * 2 * math.asin(math.sqrt(a))
_guess_state method · python · L67-L75 (9 LOC)
app/engines/real_facilities.py
    def _guess_state(self, lat: float, lon: float) -> str:
        best_dist = float('inf')
        best_state = "Uttar Pradesh"
        for s_lat, s_lon, state in INDIAN_STATES:
            d = self._haversine(lat, lon, s_lat, s_lon)
            if d < best_dist:
                best_dist = d
                best_state = state
        return best_state
_make_navigation_url method · python · L78-L86 (9 LOC)
app/engines/real_facilities.py
    def _make_navigation_url(name: str, address: str, pincode: str,
                              lat: float = None, lon: float = None) -> str:
        if lat and lon:
            return f"https://www.google.com/maps/dir/?api=1&destination={lat},{lon}"
        query = f"{name}, {address}" if address else name
        if pincode:
            query += f", {pincode}"
        query += ", India"
        return f"https://www.google.com/maps/dir/?api=1&destination={urllib.parse.quote(query)}"
Repobility · code-quality intelligence platform · https://repobility.com
_geocode_batch method · python · L88-L136 (49 LOC)
app/engines/real_facilities.py
    async def _geocode_batch(self, facilities: list[dict], state: str,
                              max_count: int = 20) -> int:
        """Geocode facilities missing coordinates using Google Maps API."""
        if not self._google_maps_key:
            return 0

        geocoded = 0
        async with httpx.AsyncClient(timeout=10.0) as client:
            for f in facilities:
                if f.get("latitude") or geocoded >= max_count:
                    continue
                query = f["name"]
                if f.get("address"):
                    query += f", {f['address']}"
                if f.get("district"):
                    query += f", {f['district']}"
                query += f", {state}, India"
                if f.get("pincode"):
                    query += f" {f['pincode']}"

                cache_key = query.lower().strip()
                if cache_key in self._geocode_cache:
                    lat, lon = self._geocode_cache[cache_key]
                    if
find_nearby method · python · L138-L191 (54 LOC)
app/engines/real_facilities.py
    async def find_nearby(self, lat: float, lon: float,
                           radius_km: float = 50.0) -> list[dict]:
        """Find nearby real facilities sorted by distance. Includes PHCs, CHCs, hospitals."""
        state = self._guess_state(lat, lon)
        raw_facilities = self._facilities.get(state, [])

        if not raw_facilities:
            logger.warning(f"No facility data for state: {state}")
            return []

        # Build working copies with navigation URLs
        facilities = []
        for f in raw_facilities:
            fc = {**f, "state": state, "source": "data.gov.in"}
            fc["navigation_url"] = self._make_navigation_url(
                fc["name"], fc.get("address", ""),
                fc.get("pincode", ""),
                fc.get("latitude"), fc.get("longitude"))
            facilities.append(fc)

        # Geocode missing coordinates (up to 20 per request to stay in free tier)
        geocoded = await self._geocode_batch(facilities, stat
ReferralRoutingEngine class · python · L6-L181 (176 LOC)
app/engines/referral_routing.py
class ReferralRoutingEngine:
    """O(1) emergency referral routing via precomputed facility-capability shortest-path trees.

    Models health facility network as directed weighted graph. Precomputed Dijkstra
    shortest-path trees enable instant optimal facility recommendation.
    """

    # Capability levels (hierarchical)
    CAPABILITIES = [
        "basic_emoc",
        "comprehensive_emoc",
        "blood_transfusion",
        "c_section",
        "neonatal_icu",
    ]

    def __init__(self):
        self._facilities: list[dict] = []
        self._spt: dict[str, dict[str, dict]] = {}  # capability -> grid_key -> facility
        self._loaded = False

    def load(self, path: str) -> None:
        """Load precomputed facility graph and SPTs from JSON."""
        with open(path) as f:
            data = json.load(f)
        self._facilities = data["facilities"]
        self._spt = data["shortest_path_trees"]
        self._loaded = True

    @staticmethod
    def _haversine(lat1
__init__ method · python · L22-L25 (4 LOC)
app/engines/referral_routing.py
    def __init__(self):
        self._facilities: list[dict] = []
        self._spt: dict[str, dict[str, dict]] = {}  # capability -> grid_key -> facility
        self._loaded = False
load method · python · L27-L33 (7 LOC)
app/engines/referral_routing.py
    def load(self, path: str) -> None:
        """Load precomputed facility graph and SPTs from JSON."""
        with open(path) as f:
            data = json.load(f)
        self._facilities = data["facilities"]
        self._spt = data["shortest_path_trees"]
        self._loaded = True
_haversine method · python · L36-L47 (12 LOC)
app/engines/referral_routing.py
    def _haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
        """Calculate distance in km between two lat/lon points."""
        R = 6371  # Earth radius in km
        dlat = math.radians(lat2 - lat1)
        dlon = math.radians(lon2 - lon1)
        a = (
            math.sin(dlat / 2) ** 2
            + math.cos(math.radians(lat1))
            * math.cos(math.radians(lat2))
            * math.sin(dlon / 2) ** 2
        )
        return R * 2 * math.asin(math.sqrt(a))
_grid_key method · python · L50-L52 (3 LOC)
app/engines/referral_routing.py
    def _grid_key(lat: float, lon: float) -> str:
        """Convert lat/lon to grid cell key (0.1 degree resolution ~11km cells)."""
        return f"{lat:.1f},{lon:.1f}"
route method · python · L54-L96 (43 LOC)
app/engines/referral_routing.py
    def route(
        self,
        latitude: float,
        longitude: float,
        capability_required: str,
        risk_level: str = "high",
    ) -> dict:
        """O(1) facility lookup via precomputed shortest-path tree.

        Returns dict with: facility_name, facility_type, distance_km, eta_minutes,
        specialist_available, blood_bank_status, has_functional_ot, contact_phone, backup_facility
        """
        grid = self._grid_key(latitude, longitude)

        # O(1) lookup in precomputed SPT
        if capability_required in self._spt and grid in self._spt[capability_required]:
            result = self._spt[capability_required][grid].copy()
            # Recalculate exact distance from actual coordinates
            result["distance_km"] = round(
                self._haversine(
                    latitude, longitude, result["latitude"], result["longitude"]
                ),
                1,
            )
            result["eta_minutes"] = round(
           
Repobility (the analyzer behind this table) · https://repobility.com
_find_nearest method · python · L98-L136 (39 LOC)
app/engines/referral_routing.py
    def _find_nearest(self, lat: float, lon: float, capability: str) -> dict:
        """Linear scan fallback for finding nearest facility with capability."""
        best = None
        best_dist = float("inf")

        for facility in self._facilities:
            if capability not in facility.get("capabilities", []):
                continue
            dist = self._haversine(
                lat, lon, facility["latitude"], facility["longitude"]
            )
            if dist < best_dist:
                best_dist = dist
                best = facility

        if best is None:
            return {
                "facility_name": "No facility available",
                "facility_type": "unknown",
                "distance_km": 0,
                "eta_minutes": 0,
                "specialist_available": False,
                "blood_bank_status": "unavailable",
                "has_functional_ot": False,
                "contact_phone": "108",
                "backup_facility": 
_find_backup method · python · L138-L169 (32 LOC)
app/engines/referral_routing.py
    def _find_backup(
        self,
        lat: float,
        lon: float,
        capability: str,
        exclude_id: Optional[str] = None,
    ) -> Optional[dict]:
        """Find second-nearest facility for backup routing."""
        best = None
        best_dist = float("inf")

        for facility in self._facilities:
            if facility.get("facility_id") == exclude_id:
                continue
            if capability not in facility.get("capabilities", []):
                continue
            dist = self._haversine(
                lat, lon, facility["latitude"], facility["longitude"]
            )
            if dist < best_dist:
                best_dist = dist
                best = facility

        if best is None:
            return None

        return {
            "facility_name": best["name"],
            "facility_type": best["type"],
            "distance_km": round(best_dist, 1),
            "eta_minutes": round(best_dist * 2.0, 0),
        }
get_all_facilities method · python · L171-L173 (3 LOC)
app/engines/referral_routing.py
    def get_all_facilities(self) -> list[dict]:
        """Return all facilities for dashboard display."""
        return self._facilities
RiskScoringEngine class · python · L8-L401 (394 LOC)
app/engines/risk_scoring.py
class RiskScoringEngine:
    """O(1) Bayesian maternal risk scoring via precomputed conjugate posterior tables.

    70,000 entries mapping discretized risk factor combinations to Beta-Binomial
    posterior risk scores. Single hash-indexed lookup at runtime.
    """

    # Discretization buckets (from spec)
    AGE_BUCKETS = [(0, 18), (18, 26), (26, 31), (31, 36), (36, 100)]  # 5 levels
    PARITY_BUCKETS = [(0, 1), (1, 3), (3, 5), (5, 100)]  # 4 levels
    HB_BUCKETS = [(0, 7), (7, 9), (9, 11), (11, 12), (12, 100)]  # 5 levels
    BP_BUCKETS = ["normal", "elevated", "stage1", "stage2", "crisis"]  # 5 levels
    GEST_BUCKETS = [(0, 13), (13, 21), (21, 29), (29, 35), (35, 38), (38, 41), (41, 50)]  # 7 levels
    BMI_BUCKETS = [(0, 18.5), (18.5, 25), (25, 30), (30, 100)]  # 4 levels
    COMP_BUCKETS = ["none", "prev_csection", "prev_pph", "prev_eclampsia", "multiple"]  # 5 levels

    RISK_THRESHOLDS = {
        "low": 0.01,
        "medium": 0.05,
        "high": 0.15,
    }

    def _
__init__ method · python · L30-L32 (3 LOC)
app/engines/risk_scoring.py
    def __init__(self):
        self._table: dict[str, dict] = {}
        self._loaded = False
load method · python · L34-L38 (5 LOC)
app/engines/risk_scoring.py
    def load(self, path: str) -> None:
        """Load precomputed risk table from JSON file."""
        with open(path) as f:
            self._table = json.load(f)
        self._loaded = True
_discretize_age method · python · L41-L50 (10 LOC)
app/engines/risk_scoring.py
    def _discretize_age(age: int) -> int:
        if age < 18:
            return 0
        if age < 26:
            return 1
        if age < 31:
            return 2
        if age < 36:
            return 3
        return 4
_discretize_parity method · python · L53-L60 (8 LOC)
app/engines/risk_scoring.py
    def _discretize_parity(parity: int) -> int:
        if parity == 0:
            return 0
        if parity < 3:
            return 1
        if parity < 5:
            return 2
        return 3
Repobility · severity-and-effort ranking · https://repobility.com
_discretize_hb method · python · L63-L72 (10 LOC)
app/engines/risk_scoring.py
    def _discretize_hb(hb: float) -> int:
        if hb < 7:
            return 0
        if hb < 9:
            return 1
        if hb < 11:
            return 2
        if hb < 12:
            return 3
        return 4
_discretize_bp method · python · L75-L84 (10 LOC)
app/engines/risk_scoring.py
    def _discretize_bp(systolic: int, diastolic: int) -> int:
        if systolic >= 180 or diastolic >= 120:
            return 4  # crisis
        if systolic >= 140 or diastolic >= 90:
            return 3  # stage2
        if systolic >= 130 or diastolic >= 80:
            return 2  # stage1
        if systolic >= 120 and diastolic < 80:
            return 1  # elevated
        return 0  # normal
_discretize_gestational_weeks method · python · L87-L100 (14 LOC)
app/engines/risk_scoring.py
    def _discretize_gestational_weeks(weeks: int) -> int:
        if weeks < 13:
            return 0
        if weeks < 21:
            return 1
        if weeks < 29:
            return 2
        if weeks < 35:
            return 3
        if weeks < 38:
            return 4
        if weeks < 41:
            return 5
        return 6
_discretize_bmi method · python · L103-L111 (9 LOC)
app/engines/risk_scoring.py
    def _discretize_bmi(height_cm: float, weight_kg: float) -> int:
        bmi = weight_kg / ((height_cm / 100) ** 2)
        if bmi < 18.5:
            return 0
        if bmi < 25:
            return 1
        if bmi < 30:
            return 2
        return 3
_discretize_complication method · python · L114-L122 (9 LOC)
app/engines/risk_scoring.py
    def _discretize_complication(comp: str) -> int:
        mapping = {
            "none": 0,
            "prev_csection": 1,
            "prev_pph": 2,
            "prev_eclampsia": 3,
            "multiple": 4,
        }
        return mapping.get(comp, 0)
_compute_hash method · python · L125-L138 (14 LOC)
app/engines/risk_scoring.py
    def _compute_hash(
        age_idx: int,
        parity_idx: int,
        hb_idx: int,
        bp_idx: int,
        gest_idx: int,
        bmi_idx: int,
        comp_idx: int,
    ) -> str:
        """Compute deterministic hash key from discretized indices."""
        key_bytes = struct.pack(
            "7B", age_idx, parity_idx, hb_idx, bp_idx, gest_idx, bmi_idx, comp_idx
        )
        return hashlib.sha256(key_bytes).hexdigest()[:16]
score method · python · L140-L176 (37 LOC)
app/engines/risk_scoring.py
    def score(
        self,
        age: int,
        parity: int,
        hemoglobin: float,
        bp_systolic: int,
        bp_diastolic: int,
        gestational_weeks: int,
        height_cm: float,
        weight_kg: float,
        complication_history: str,
    ) -> dict:
        """O(1) risk scoring via hash table lookup.

        Returns dict with: risk_score, risk_level, alpha, beta, interventions, risk_factors_summary
        """
        # Discretize all 7 factors
        age_idx = self._discretize_age(age)
        parity_idx = self._discretize_parity(parity)
        hb_idx = self._discretize_hb(hemoglobin)
        bp_idx = self._discretize_bp(bp_systolic, bp_diastolic)
        gest_idx = self._discretize_gestational_weeks(gestational_weeks)
        bmi_idx = self._discretize_bmi(height_cm, weight_kg)
        comp_idx = self._discretize_complication(complication_history)

        # O(1) hash lookup
        key = self._compute_hash(
            age_idx, parity_idx, hb_idx, 
_compute_risk method · python · L178-L364 (187 LOC)
app/engines/risk_scoring.py
    def _compute_risk(
        self,
        age_idx: int,
        parity_idx: int,
        hb_idx: int,
        bp_idx: int,
        gest_idx: int,
        bmi_idx: int,
        comp_idx: int,
    ) -> dict:
        """Compute risk score from Beta-Binomial posterior (fallback).

        Uses conjugate Beta prior updated with pseudo-observations derived from
        epidemiological risk-factor weights.  Alpha encodes adverse-outcome
        evidence; beta encodes safe-outcome evidence.  The posterior mean
        alpha / (alpha + beta) is the risk score.
        """
        # Base prior: uninformative but anchored to India SRS maternal
        # mortality ratio (~130 per 100k => ~0.0013 baseline).  We use a
        # weakly informative Beta(1, 99) so the prior mean is 0.01,
        # slightly above baseline to account for the sub-population that
        # actually presents for screening.
        alpha_0 = 1.0
        beta_0 = 99.0

        # --------------------------------------------
Repobility — same analyzer, your code, free for public repos · /scan/
_get_interventions method · python · L367-L393 (27 LOC)
app/engines/risk_scoring.py
    def _get_interventions(
        hb_idx: int, bp_idx: int, comp_idx: int, risk_level: str
    ) -> list[str]:
        interventions = []
        if hb_idx <= 1:
            interventions.append(
                "Ensure daily IFA supplementation — morning, empty stomach"
            )
            if hb_idx == 0:
                interventions.append(
                    "URGENT: Refer for injectable iron / blood transfusion"
                )
        if bp_idx >= 2:
            interventions.append("Monitor BP weekly; refer if BP > 140/90")
            if bp_idx >= 3:
                interventions.append(
                    "URGENT: Refer to facility with MgSO4 and antihypertensive capability"
                )
        if comp_idx >= 2:
            interventions.append(
                "Plan institutional delivery at facility with blood bank and OT"
            )
        if risk_level == "critical":
            interventions.append("EMERGENCY: Arrange immediate facility transfer")
  
lifespan function · python · L34-L84 (51 LOC)
app/main.py
async def lifespan(app: FastAPI):
    """Load all O(1) engines at startup."""
    settings = get_settings()
    data_dir = Path(__file__).parent.parent / "data"

    logger.info("Loading O(1) engines...")

    risk_path = data_dir / "risk_table.json"
    if risk_path.exists():
        risk_engine.load(str(risk_path))
        logger.info(f"Risk scoring engine loaded: {risk_engine.table_size} entries")
    else:
        logger.warning(f"Risk table not found at {risk_path} — using on-the-fly computation")
        risk_engine._loaded = True  # Allow fallback computation

    facility_path = data_dir / "facility_graph.json"
    if facility_path.exists():
        referral_engine.load(str(facility_path))
        logger.info(f"Referral routing engine loaded: {referral_engine.facility_count} facilities")
    else:
        logger.warning(f"Facility graph not found at {facility_path}")
        referral_engine._loaded = True

    hb_path = data_dir / "hb_trajectories.json"
    if hb_path.exists():
home function · python · L122-L126 (5 LOC)
app/main.py
async def home(request: FastAPIRequest):
    return templates.TemplateResponse("index.html", {
        "request": request,
        "google_maps_key": settings.google_maps_api_key,
    })
page 1 / 2next ›