IDKHowToCodeFr/tinyml-backend
1
1import asyncio2import random3from typing import AsyncGenerator4 5class PatientDataSimulator:6 def __init__(self, initial_hr=75.0, initial_spo2=98.0, initial_sys=120.0, initial_dia=80.0, initial_temp=37.0):7 self.hr = initial_hr8 self.spo2 = initial_spo29 self.sys_bp = initial_sys10 self.dia_bp = initial_dia11 self.temp = initial_temp12 13 self.target_hr = self.hr14 self.target_spo2 = self.spo215 self.target_sys = self.sys_bp16 self.target_dia = self.dia_bp17 18 def _shift_state(self):19 # 5% chance every second to shift patient state20 if random.random() < 0.05:21 state = random.choice(["normal", "normal", "normal", "asthma", "hypertension", "heart_disease", "diabetes"])22 if state == "normal":23 self.target_hr, self.target_spo2, self.target_sys, self.target_dia = 75.0, 98.0, 120.0, 80.024 elif state == "asthma":25 self.target_hr, self.target_spo2, self.target_sys, self.target_dia = 115.0, 88.0, 135.0, 85.026 elif state == "hypertension":27 self.target_hr, self.target_spo2, self.target_sys, self.target_dia = 90.0, 97.0, 175.0, 105.028 elif state == "heart_disease":29 self.target_hr, self.target_spo2, self.target_sys, self.target_dia = 135.0, 91.0, 150.0, 95.030 elif state == "diabetes":31 self.target_hr, self.target_spo2, self.target_sys, self.target_dia = 85.0, 96.0, 140.0, 90.032 33 def _step_physics(self):34 # Interpolate towards target with noise35 self.hr += (self.target_hr - self.hr) * 0.1 + random.uniform(-2, 2)36 self.spo2 += (self.target_spo2 - self.spo2) * 0.1 + random.uniform(-0.5, 0.5)37 self.sys_bp += (self.target_sys - self.sys_bp) * 0.1 + random.uniform(-1, 1)38 self.dia_bp += (self.target_dia - self.dia_bp) * 0.1 + random.uniform(-1, 1)39 self.temp = max(36.0, min(39.0, self.temp + random.uniform(-0.1, 0.1)))40 41 # Clamp values42 self.hr = max(50.0, min(180.0, self.hr))43 self.spo2 = max(80.0, min(100.0, self.spo2))44 45 async def run(self) -> AsyncGenerator[dict, None]:46 while True:47 self._shift_state()48 self._step_physics()49 50 yield {51 "Heart_Rate": round(self.hr, 1),52 "SpO2_Level": round(self.spo2, 1),53 "Systolic_BP": round(self.sys_bp, 1),54 "Diastolic_BP": round(self.dia_bp, 1),55 "Body_Temp": round(self.temp, 1)56 }57 await asyncio.sleep(1.0)58 