import json from fastapi import APIRouter, HTTPException from app.config import BACKGROUND_SNAPSHOT_PATH, BACKGROUND_PATH, energy_axis, NUM_CHANNELS import numpy as np router = APIRouter() @router.get("") async def get_background_info(): """Background metadata: elapsed time, CPS, top peaks.""" if not BACKGROUND_SNAPSHOT_PATH.exists(): raise HTTPException(status_code=404, detail="Background capture not available yet") try: with open(BACKGROUND_SNAPSHOT_PATH) as f: snapshot = json.load(f) except (json.JSONDecodeError, OSError): raise HTTPException(status_code=500, detail="Background snapshot file corrupt") # Check if full background is available full_available = BACKGROUND_PATH.exists() return { "elapsed_hours": snapshot.get("elapsed_hours", 0), "live_time_s": snapshot.get("live_time_s", 0), "total_counts": snapshot.get("total_counts", 0), "cps": snapshot.get("cps", 0), "top_peaks": snapshot.get("top_peaks", []), "full_background_available": full_available, } @router.get("/spectrum") async def get_background_spectrum(): """Full background spectrum with energy axis.""" if not BACKGROUND_SNAPSHOT_PATH.exists(): raise HTTPException(status_code=404, detail="Background capture not available yet") try: with open(BACKGROUND_SNAPSHOT_PATH) as f: snapshot = json.load(f) except (json.JSONDecodeError, OSError): raise HTTPException(status_code=500, detail="Background snapshot file corrupt") counts = snapshot.get("spectrum", [0] * NUM_CHANNELS) # If full background file exists, use it for better data if BACKGROUND_PATH.exists(): try: bg_data = np.load(str(BACKGROUND_PATH), allow_pickle=True).item() counts = [round(float(c), 1) for c in bg_data["counts"]] live_time = float(bg_data["duration"]) except Exception: live_time = snapshot.get("live_time_s", 0) else: live_time = snapshot.get("live_time_s", 0) return { "channels": list(range(NUM_CHANNELS)), "energy_kev": energy_axis(), "counts": counts, "live_time_s": live_time, "cps": snapshot.get("cps", 0), "top_peaks": snapshot.get("top_peaks", []), }