|
| 1 | +import subprocess |
| 2 | +import os |
| 3 | +import json |
| 4 | + |
| 5 | +class SyntheaGenerator: |
| 6 | + def __init__(self, state="Massachusetts", gender=None, age=None, patients=1, module=None, synth_path=None): |
| 7 | + if synth_path is None: |
| 8 | + synth_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) |
| 9 | + |
| 10 | + self.state = state |
| 11 | + self.gender = gender |
| 12 | + self.age = age |
| 13 | + self.patients = patients |
| 14 | + self.module = module |
| 15 | + self.synth_path = synth_path |
| 16 | + self.output_path = os.path.join(self.synth_path, "output", "fhir") |
| 17 | + |
| 18 | + def _clear_output(self): |
| 19 | + if os.path.exists(self.output_path): |
| 20 | + for f in os.listdir(self.output_path): |
| 21 | + if f.endswith(".json"): |
| 22 | + os.remove(os.path.join(self.output_path, f)) |
| 23 | + |
| 24 | + def _build_command(self): |
| 25 | + script = "run_synthea.bat" if os.name == "nt" else "./run_synthea" |
| 26 | + cmd = [script, self.state, "-p", str(self.patients)] |
| 27 | + if self.age: |
| 28 | + cmd += ["-a", self.age] |
| 29 | + if self.gender: |
| 30 | + cmd += ["-g", self.gender] |
| 31 | + if self.module: |
| 32 | + cmd += ["-m", self.module] |
| 33 | + return cmd |
| 34 | + |
| 35 | + |
| 36 | + def generate(self): |
| 37 | + self._clear_output() |
| 38 | + cmd = self._build_command() |
| 39 | + try: |
| 40 | + subprocess.run(cmd, cwd=self.synth_path, check=True) |
| 41 | + except subprocess.CalledProcessError as e: |
| 42 | + raise RuntimeError(f"[Synthea Error] CLI failed: {e}") |
| 43 | + |
| 44 | + if not os.path.exists(self.output_path): |
| 45 | + raise RuntimeError("No output folder found.") |
| 46 | + |
| 47 | + json_files = [f for f in os.listdir(self.output_path) if f.endswith(".json")] |
| 48 | + patients = [] |
| 49 | + for file in json_files: |
| 50 | + with open(os.path.join(self.output_path, file), "r") as f: |
| 51 | + data = json.load(f) |
| 52 | + entries = data.get("entry", []) |
| 53 | + has_patient = any( |
| 54 | + e.get("resource", {}).get("resourceType") == "Patient" for e in entries |
| 55 | + ) |
| 56 | + if data.get("resourceType") == "Bundle" and has_patient: |
| 57 | + patients.append(data) |
| 58 | + |
| 59 | + return patients |
| 60 | + |
| 61 | + def save(self, output_dir): |
| 62 | + os.makedirs(output_dir, exist_ok=True) |
| 63 | + for file in os.listdir(self.output_path): |
| 64 | + if file.endswith(".json"): |
| 65 | + src = os.path.join(self.output_path, file) |
| 66 | + dst = os.path.join(output_dir, file) |
| 67 | + with open(src, "r") as f_in, open(dst, "w") as f_out: |
| 68 | + f_out.write(f_in.read()) |
0 commit comments