We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
robust username masking in print_config
https://github.com/Project-MONAI/MONAI/blob/6f5005fddfaf935cc9b723be823f446a09136d11/monai/config/deviceconfig.py#L103-L110
if home directories are in other locations, eg. networked directories, the regex patterns won't match. I'd suggest a more thorough approach is to get the username with `getpass.getuser()` or `os.path.basename(os.path.expanduser("~"))` then replace all instances of that string in the output with "<username>". This will catch more places but will miss paths that might contain other identifying names, but these should be very rare.

_Originally posted by @ericspod in https://github.com/Project-MONAI/MONAI/issues/6913#issuecomment-1699093111_
            

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `monai/config/deviceconfig.py`
Content:
```
1 # Copyright (c) MONAI Consortium
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at
5 #     http://www.apache.org/licenses/LICENSE-2.0
6 # Unless required by applicable law or agreed to in writing, software
7 # distributed under the License is distributed on an "AS IS" BASIS,
8 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9 # See the License for the specific language governing permissions and
10 # limitations under the License.
11 
12 from __future__ import annotations
13 
14 import os
15 import platform
16 import re
17 import sys
18 from collections import OrderedDict
19 from typing import TextIO
20 
21 import numpy as np
22 import torch
23 
24 import monai
25 from monai.utils.module import OptionalImportError, get_package_version, optional_import
26 
27 try:
28     _, HAS_EXT = optional_import("monai._C")
29     USE_COMPILED = HAS_EXT and os.getenv("BUILD_MONAI", "0") == "1"
30 except (OptionalImportError, ImportError, AttributeError):
31     HAS_EXT = USE_COMPILED = False
32 
33 USE_META_DICT = os.environ.get("USE_META_DICT", "0") == "1"  # set to True for compatibility, use meta dict.
34 
35 psutil, has_psutil = optional_import("psutil")
36 psutil_version = psutil.__version__ if has_psutil else "NOT INSTALLED or UNKNOWN VERSION."
37 
38 __all__ = [
39     "print_config",
40     "get_system_info",
41     "print_system_info",
42     "get_gpu_info",
43     "print_gpu_info",
44     "print_debug_info",
45     "USE_COMPILED",
46     "USE_META_DICT",
47     "IgniteInfo",
48 ]
49 
50 
51 def get_config_values():
52     """
53     Read the package versions into a dictionary.
54     """
55     output = OrderedDict()
56 
57     output["MONAI"] = monai.__version__
58     output["Numpy"] = np.version.full_version
59     output["Pytorch"] = torch.__version__
60 
61     return output
62 
63 
64 def get_optional_config_values():
65     """
66     Read the optional package versions into a dictionary.
67     """
68     output = OrderedDict()
69 
70     output["Pytorch Ignite"] = get_package_version("ignite")
71     output["ITK"] = get_package_version("itk")
72     output["Nibabel"] = get_package_version("nibabel")
73     output["scikit-image"] = get_package_version("skimage")
74     output["scipy"] = get_package_version("scipy")
75     output["Pillow"] = get_package_version("PIL")
76     output["Tensorboard"] = get_package_version("tensorboard")
77     output["gdown"] = get_package_version("gdown")
78     output["TorchVision"] = get_package_version("torchvision")
79     output["tqdm"] = get_package_version("tqdm")
80     output["lmdb"] = get_package_version("lmdb")
81     output["psutil"] = psutil_version
82     output["pandas"] = get_package_version("pandas")
83     output["einops"] = get_package_version("einops")
84     output["transformers"] = get_package_version("transformers")
85     output["mlflow"] = get_package_version("mlflow")
86     output["pynrrd"] = get_package_version("nrrd")
87     output["clearml"] = get_package_version("clearml")
88 
89     return output
90 
91 
92 def print_config(file=sys.stdout):
93     """
94     Print the package versions to `file`.
95 
96     Args:
97         file: `print()` text stream file. Defaults to `sys.stdout`.
98     """
99     for k, v in get_config_values().items():
100         print(f"{k} version: {v}", file=file, flush=True)
101     print(f"MONAI flags: HAS_EXT = {HAS_EXT}, USE_COMPILED = {USE_COMPILED}, USE_META_DICT = {USE_META_DICT}")
102     print(f"MONAI rev id: {monai.__revision_id__}")
103     masked_file_path = re.sub(
104         r"/home/\w+/",
105         "/home/<username>/",
106         re.sub(
107             r"/Users/\w+/",
108             "/Users/<username>/",
109             re.sub(r"C:\\Users\\\w+\\", r"C:\\Users\\<username>\\", monai.__file__),
110         ),
111     )
112     print(f"MONAI __file__: {masked_file_path}", file=file, flush=True)
113     print("\nOptional dependencies:", file=file, flush=True)
114     for k, v in get_optional_config_values().items():
115         print(f"{k} version: {v}", file=file, flush=True)
116     print("\nFor details about installing the optional dependencies, please visit:", file=file, flush=True)
117     print(
118         "    https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies\n",
119         file=file,
120         flush=True,
121     )
122 
123 
124 def _dict_append(in_dict, key, fn):
125     try:
126         in_dict[key] = fn() if callable(fn) else fn
127     except BaseException:
128         in_dict[key] = "UNKNOWN for given OS"
129 
130 
131 def get_system_info() -> OrderedDict:
132     """
133     Get system info as an ordered dictionary.
134     """
135     output: OrderedDict = OrderedDict()
136 
137     _dict_append(output, "System", platform.system)
138     if output["System"] == "Windows":
139         _dict_append(output, "Win32 version", platform.win32_ver)
140         if hasattr(platform, "win32_edition"):
141             _dict_append(output, "Win32 edition", platform.win32_edition)
142 
143     elif output["System"] == "Darwin":
144         _dict_append(output, "Mac version", lambda: platform.mac_ver()[0])
145     else:
146         with open("/etc/os-release") as rel_f:
147             linux_ver = re.search(r'PRETTY_NAME="(.*)"', rel_f.read())
148         if linux_ver:
149             _dict_append(output, "Linux version", lambda: linux_ver.group(1))
150 
151     _dict_append(output, "Platform", platform.platform)
152     _dict_append(output, "Processor", platform.processor)
153     _dict_append(output, "Machine", platform.machine)
154     _dict_append(output, "Python version", platform.python_version)
155 
156     if not has_psutil:
157         _dict_append(output, "`psutil` missing", lambda: "run `pip install monai[psutil]`")
158     else:
159         p = psutil.Process()
160         with p.oneshot():
161             _dict_append(output, "Process name", p.name)
162             _dict_append(output, "Command", p.cmdline)
163             _dict_append(output, "Open files", p.open_files)
164             _dict_append(output, "Num physical CPUs", lambda: psutil.cpu_count(logical=False))
165             _dict_append(output, "Num logical CPUs", lambda: psutil.cpu_count(logical=True))
166             _dict_append(output, "Num usable CPUs", lambda: len(psutil.Process().cpu_affinity()))
167             _dict_append(output, "CPU usage (%)", lambda: psutil.cpu_percent(percpu=True))
168             _dict_append(output, "CPU freq. (MHz)", lambda: round(psutil.cpu_freq(percpu=False)[0]))
169             _dict_append(
170                 output,
171                 "Load avg. in last 1, 5, 15 mins (%)",
172                 lambda: [round(x / psutil.cpu_count() * 100, 1) for x in psutil.getloadavg()],
173             )
174             _dict_append(output, "Disk usage (%)", lambda: psutil.disk_usage(os.getcwd()).percent)
175             _dict_append(
176                 output,
177                 "Avg. sensor temp. (Celsius)",
178                 lambda: np.round(
179                     np.mean([item.current for sublist in psutil.sensors_temperatures().values() for item in sublist], 1)
180                 ),
181             )
182             mem = psutil.virtual_memory()
183             _dict_append(output, "Total physical memory (GB)", lambda: round(mem.total / 1024**3, 1))
184             _dict_append(output, "Available memory (GB)", lambda: round(mem.available / 1024**3, 1))
185             _dict_append(output, "Used memory (GB)", lambda: round(mem.used / 1024**3, 1))
186 
187     return output
188 
189 
190 def print_system_info(file: TextIO = sys.stdout) -> None:
191     """
192     Print system info to `file`. Requires the optional library, `psutil`.
193 
194     Args:
195         file: `print()` text stream file. Defaults to `sys.stdout`.
196     """
197     if not has_psutil:
198         print("`psutil` required for `print_system_info`", file=file, flush=True)
199     else:
200         for k, v in get_system_info().items():
201             print(f"{k}: {v}", file=file, flush=True)
202 
203 
204 def get_gpu_info() -> OrderedDict:
205     output: OrderedDict = OrderedDict()
206 
207     num_gpus = torch.cuda.device_count()
208     _dict_append(output, "Num GPUs", lambda: num_gpus)
209 
210     _dict_append(output, "Has CUDA", lambda: bool(torch.cuda.is_available()))
211 
212     if output["Has CUDA"]:
213         _dict_append(output, "CUDA version", lambda: torch.version.cuda)
214     cudnn_ver = torch.backends.cudnn.version()
215     _dict_append(output, "cuDNN enabled", lambda: bool(cudnn_ver))
216     _dict_append(output, "NVIDIA_TF32_OVERRIDE", os.environ.get("NVIDIA_TF32_OVERRIDE"))
217     _dict_append(output, "TORCH_ALLOW_TF32_CUBLAS_OVERRIDE", os.environ.get("TORCH_ALLOW_TF32_CUBLAS_OVERRIDE"))
218 
219     if cudnn_ver:
220         _dict_append(output, "cuDNN version", lambda: cudnn_ver)
221 
222     if num_gpus > 0:
223         _dict_append(output, "Current device", torch.cuda.current_device)
224         _dict_append(output, "Library compiled for CUDA architectures", torch.cuda.get_arch_list)
225 
226     for gpu in range(num_gpus):
227         gpu_info = torch.cuda.get_device_properties(gpu)
228         _dict_append(output, f"GPU {gpu} Name", gpu_info.name)
229         _dict_append(output, f"GPU {gpu} Is integrated", bool(gpu_info.is_integrated))
230         _dict_append(output, f"GPU {gpu} Is multi GPU board", bool(gpu_info.is_multi_gpu_board))
231         _dict_append(output, f"GPU {gpu} Multi processor count", gpu_info.multi_processor_count)
232         _dict_append(output, f"GPU {gpu} Total memory (GB)", round(gpu_info.total_memory / 1024**3, 1))
233         _dict_append(output, f"GPU {gpu} CUDA capability (maj.min)", f"{gpu_info.major}.{gpu_info.minor}")
234 
235     return output
236 
237 
238 def print_gpu_info(file: TextIO = sys.stdout) -> None:
239     """
240     Print GPU info to `file`.
241 
242     Args:
243         file: `print()` text stream file. Defaults to `sys.stdout`.
244     """
245     for k, v in get_gpu_info().items():
246         print(f"{k}: {v}", file=file, flush=True)
247 
248 
249 def print_debug_info(file: TextIO = sys.stdout) -> None:
250     """
251     Print config (installed dependencies, etc.) and system info for debugging.
252 
253     Args:
254         file: `print()` text stream file. Defaults to `sys.stdout`.
255     """
256     print("================================", file=file, flush=True)
257     print("Printing MONAI config...", file=file, flush=True)
258     print("================================", file=file, flush=True)
259     print_config(file)
260     print("\n================================", file=file, flush=True)
261     print("Printing system config...")
262     print("================================", file=file, flush=True)
263     print_system_info(file)
264     print("\n================================", file=file, flush=True)
265     print("Printing GPU config...")
266     print("================================", file=file, flush=True)
267     print_gpu_info(file)
268 
269 
270 class IgniteInfo:
271     """
272     Config information of the PyTorch ignite package.
273 
274     """
275 
276     OPT_IMPORT_VERSION = "0.4.4"
277 
278 
279 if __name__ == "__main__":
280     print_debug_info()
281
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/monai/config/deviceconfig.py b/monai/config/deviceconfig.py
--- a/monai/config/deviceconfig.py
+++ b/monai/config/deviceconfig.py
@@ -11,6 +11,7 @@
 
 from __future__ import annotations
 
+import getpass
 import os
 import platform
 import re
@@ -100,15 +101,8 @@
         print(f"{k} version: {v}", file=file, flush=True)
     print(f"MONAI flags: HAS_EXT = {HAS_EXT}, USE_COMPILED = {USE_COMPILED}, USE_META_DICT = {USE_META_DICT}")
     print(f"MONAI rev id: {monai.__revision_id__}")
-    masked_file_path = re.sub(
-        r"/home/\w+/",
-        "/home/<username>/",
-        re.sub(
-            r"/Users/\w+/",
-            "/Users/<username>/",
-            re.sub(r"C:\\Users\\\w+\\", r"C:\\Users\\<username>\\", monai.__file__),
-        ),
-    )
+    username = getpass.getuser()
+    masked_file_path = re.sub(username, "<username>", monai.__file__)
     print(f"MONAI __file__: {masked_file_path}", file=file, flush=True)
     print("\nOptional dependencies:", file=file, flush=True)
     for k, v in get_optional_config_values().items():

{"golden_diff": "diff --git a/monai/config/deviceconfig.py b/monai/config/deviceconfig.py\n--- a/monai/config/deviceconfig.py\n+++ b/monai/config/deviceconfig.py\n@@ -11,6 +11,7 @@\n \n from __future__ import annotations\n \n+import getpass\n import os\n import platform\n import re\n@@ -100,15 +101,8 @@\n         print(f\"{k} version: {v}\", file=file, flush=True)\n     print(f\"MONAI flags: HAS_EXT = {HAS_EXT}, USE_COMPILED = {USE_COMPILED}, USE_META_DICT = {USE_META_DICT}\")\n     print(f\"MONAI rev id: {monai.__revision_id__}\")\n-    masked_file_path = re.sub(\n-        r\"/home/\\w+/\",\n-        \"/home/<username>/\",\n-        re.sub(\n-            r\"/Users/\\w+/\",\n-            \"/Users/<username>/\",\n-            re.sub(r\"C:\\\\Users\\\\\\w+\\\\\", r\"C:\\\\Users\\\\<username>\\\\\", monai.__file__),\n-        ),\n-    )\n+    username = getpass.getuser()\n+    masked_file_path = re.sub(username, \"<username>\", monai.__file__)\n     print(f\"MONAI __file__: {masked_file_path}\", file=file, flush=True)\n     print(\"\\nOptional dependencies:\", file=file, flush=True)\n     for k, v in get_optional_config_values().items():\n", "issue": "robust username masking in print_config\nhttps://github.com/Project-MONAI/MONAI/blob/6f5005fddfaf935cc9b723be823f446a09136d11/monai/config/deviceconfig.py#L103-L110\r\nif home directories are in other locations, eg. networked directories, the regex patterns won't match. I'd suggest a more thorough approach is to get the username with `getpass.getuser()` or `os.path.basename(os.path.expanduser(\"~\"))` then replace all instances of that string in the output with \"<username>\". This will catch more places but will miss paths that might contain other identifying names, but these should be very rare.\r\n\r\n_Originally posted by @ericspod in https://github.com/Project-MONAI/MONAI/issues/6913#issuecomment-1699093111_\r\n            \n", "before_files": [{"content": "# Copyright (c) MONAI Consortium\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import annotations\n\nimport os\nimport platform\nimport re\nimport sys\nfrom collections import OrderedDict\nfrom typing import TextIO\n\nimport numpy as np\nimport torch\n\nimport monai\nfrom monai.utils.module import OptionalImportError, get_package_version, optional_import\n\ntry:\n    _, HAS_EXT = optional_import(\"monai._C\")\n    USE_COMPILED = HAS_EXT and os.getenv(\"BUILD_MONAI\", \"0\") == \"1\"\nexcept (OptionalImportError, ImportError, AttributeError):\n    HAS_EXT = USE_COMPILED = False\n\nUSE_META_DICT = os.environ.get(\"USE_META_DICT\", \"0\") == \"1\"  # set to True for compatibility, use meta dict.\n\npsutil, has_psutil = optional_import(\"psutil\")\npsutil_version = psutil.__version__ if has_psutil else \"NOT INSTALLED or UNKNOWN VERSION.\"\n\n__all__ = [\n    \"print_config\",\n    \"get_system_info\",\n    \"print_system_info\",\n    \"get_gpu_info\",\n    \"print_gpu_info\",\n    \"print_debug_info\",\n    \"USE_COMPILED\",\n    \"USE_META_DICT\",\n    \"IgniteInfo\",\n]\n\n\ndef get_config_values():\n    \"\"\"\n    Read the package versions into a dictionary.\n    \"\"\"\n    output = OrderedDict()\n\n    output[\"MONAI\"] = monai.__version__\n    output[\"Numpy\"] = np.version.full_version\n    output[\"Pytorch\"] = torch.__version__\n\n    return output\n\n\ndef get_optional_config_values():\n    \"\"\"\n    Read the optional package versions into a dictionary.\n    \"\"\"\n    output = OrderedDict()\n\n    output[\"Pytorch Ignite\"] = get_package_version(\"ignite\")\n    output[\"ITK\"] = get_package_version(\"itk\")\n    output[\"Nibabel\"] = get_package_version(\"nibabel\")\n    output[\"scikit-image\"] = get_package_version(\"skimage\")\n    output[\"scipy\"] = get_package_version(\"scipy\")\n    output[\"Pillow\"] = get_package_version(\"PIL\")\n    output[\"Tensorboard\"] = get_package_version(\"tensorboard\")\n    output[\"gdown\"] = get_package_version(\"gdown\")\n    output[\"TorchVision\"] = get_package_version(\"torchvision\")\n    output[\"tqdm\"] = get_package_version(\"tqdm\")\n    output[\"lmdb\"] = get_package_version(\"lmdb\")\n    output[\"psutil\"] = psutil_version\n    output[\"pandas\"] = get_package_version(\"pandas\")\n    output[\"einops\"] = get_package_version(\"einops\")\n    output[\"transformers\"] = get_package_version(\"transformers\")\n    output[\"mlflow\"] = get_package_version(\"mlflow\")\n    output[\"pynrrd\"] = get_package_version(\"nrrd\")\n    output[\"clearml\"] = get_package_version(\"clearml\")\n\n    return output\n\n\ndef print_config(file=sys.stdout):\n    \"\"\"\n    Print the package versions to `file`.\n\n    Args:\n        file: `print()` text stream file. Defaults to `sys.stdout`.\n    \"\"\"\n    for k, v in get_config_values().items():\n        print(f\"{k} version: {v}\", file=file, flush=True)\n    print(f\"MONAI flags: HAS_EXT = {HAS_EXT}, USE_COMPILED = {USE_COMPILED}, USE_META_DICT = {USE_META_DICT}\")\n    print(f\"MONAI rev id: {monai.__revision_id__}\")\n    masked_file_path = re.sub(\n        r\"/home/\\w+/\",\n        \"/home/<username>/\",\n        re.sub(\n            r\"/Users/\\w+/\",\n            \"/Users/<username>/\",\n            re.sub(r\"C:\\\\Users\\\\\\w+\\\\\", r\"C:\\\\Users\\\\<username>\\\\\", monai.__file__),\n        ),\n    )\n    print(f\"MONAI __file__: {masked_file_path}\", file=file, flush=True)\n    print(\"\\nOptional dependencies:\", file=file, flush=True)\n    for k, v in get_optional_config_values().items():\n        print(f\"{k} version: {v}\", file=file, flush=True)\n    print(\"\\nFor details about installing the optional dependencies, please visit:\", file=file, flush=True)\n    print(\n        \"    https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies\\n\",\n        file=file,\n        flush=True,\n    )\n\n\ndef _dict_append(in_dict, key, fn):\n    try:\n        in_dict[key] = fn() if callable(fn) else fn\n    except BaseException:\n        in_dict[key] = \"UNKNOWN for given OS\"\n\n\ndef get_system_info() -> OrderedDict:\n    \"\"\"\n    Get system info as an ordered dictionary.\n    \"\"\"\n    output: OrderedDict = OrderedDict()\n\n    _dict_append(output, \"System\", platform.system)\n    if output[\"System\"] == \"Windows\":\n        _dict_append(output, \"Win32 version\", platform.win32_ver)\n        if hasattr(platform, \"win32_edition\"):\n            _dict_append(output, \"Win32 edition\", platform.win32_edition)\n\n    elif output[\"System\"] == \"Darwin\":\n        _dict_append(output, \"Mac version\", lambda: platform.mac_ver()[0])\n    else:\n        with open(\"/etc/os-release\") as rel_f:\n            linux_ver = re.search(r'PRETTY_NAME=\"(.*)\"', rel_f.read())\n        if linux_ver:\n            _dict_append(output, \"Linux version\", lambda: linux_ver.group(1))\n\n    _dict_append(output, \"Platform\", platform.platform)\n    _dict_append(output, \"Processor\", platform.processor)\n    _dict_append(output, \"Machine\", platform.machine)\n    _dict_append(output, \"Python version\", platform.python_version)\n\n    if not has_psutil:\n        _dict_append(output, \"`psutil` missing\", lambda: \"run `pip install monai[psutil]`\")\n    else:\n        p = psutil.Process()\n        with p.oneshot():\n            _dict_append(output, \"Process name\", p.name)\n            _dict_append(output, \"Command\", p.cmdline)\n            _dict_append(output, \"Open files\", p.open_files)\n            _dict_append(output, \"Num physical CPUs\", lambda: psutil.cpu_count(logical=False))\n            _dict_append(output, \"Num logical CPUs\", lambda: psutil.cpu_count(logical=True))\n            _dict_append(output, \"Num usable CPUs\", lambda: len(psutil.Process().cpu_affinity()))\n            _dict_append(output, \"CPU usage (%)\", lambda: psutil.cpu_percent(percpu=True))\n            _dict_append(output, \"CPU freq. (MHz)\", lambda: round(psutil.cpu_freq(percpu=False)[0]))\n            _dict_append(\n                output,\n                \"Load avg. in last 1, 5, 15 mins (%)\",\n                lambda: [round(x / psutil.cpu_count() * 100, 1) for x in psutil.getloadavg()],\n            )\n            _dict_append(output, \"Disk usage (%)\", lambda: psutil.disk_usage(os.getcwd()).percent)\n            _dict_append(\n                output,\n                \"Avg. sensor temp. (Celsius)\",\n                lambda: np.round(\n                    np.mean([item.current for sublist in psutil.sensors_temperatures().values() for item in sublist], 1)\n                ),\n            )\n            mem = psutil.virtual_memory()\n            _dict_append(output, \"Total physical memory (GB)\", lambda: round(mem.total / 1024**3, 1))\n            _dict_append(output, \"Available memory (GB)\", lambda: round(mem.available / 1024**3, 1))\n            _dict_append(output, \"Used memory (GB)\", lambda: round(mem.used / 1024**3, 1))\n\n    return output\n\n\ndef print_system_info(file: TextIO = sys.stdout) -> None:\n    \"\"\"\n    Print system info to `file`. Requires the optional library, `psutil`.\n\n    Args:\n        file: `print()` text stream file. Defaults to `sys.stdout`.\n    \"\"\"\n    if not has_psutil:\n        print(\"`psutil` required for `print_system_info`\", file=file, flush=True)\n    else:\n        for k, v in get_system_info().items():\n            print(f\"{k}: {v}\", file=file, flush=True)\n\n\ndef get_gpu_info() -> OrderedDict:\n    output: OrderedDict = OrderedDict()\n\n    num_gpus = torch.cuda.device_count()\n    _dict_append(output, \"Num GPUs\", lambda: num_gpus)\n\n    _dict_append(output, \"Has CUDA\", lambda: bool(torch.cuda.is_available()))\n\n    if output[\"Has CUDA\"]:\n        _dict_append(output, \"CUDA version\", lambda: torch.version.cuda)\n    cudnn_ver = torch.backends.cudnn.version()\n    _dict_append(output, \"cuDNN enabled\", lambda: bool(cudnn_ver))\n    _dict_append(output, \"NVIDIA_TF32_OVERRIDE\", os.environ.get(\"NVIDIA_TF32_OVERRIDE\"))\n    _dict_append(output, \"TORCH_ALLOW_TF32_CUBLAS_OVERRIDE\", os.environ.get(\"TORCH_ALLOW_TF32_CUBLAS_OVERRIDE\"))\n\n    if cudnn_ver:\n        _dict_append(output, \"cuDNN version\", lambda: cudnn_ver)\n\n    if num_gpus > 0:\n        _dict_append(output, \"Current device\", torch.cuda.current_device)\n        _dict_append(output, \"Library compiled for CUDA architectures\", torch.cuda.get_arch_list)\n\n    for gpu in range(num_gpus):\n        gpu_info = torch.cuda.get_device_properties(gpu)\n        _dict_append(output, f\"GPU {gpu} Name\", gpu_info.name)\n        _dict_append(output, f\"GPU {gpu} Is integrated\", bool(gpu_info.is_integrated))\n        _dict_append(output, f\"GPU {gpu} Is multi GPU board\", bool(gpu_info.is_multi_gpu_board))\n        _dict_append(output, f\"GPU {gpu} Multi processor count\", gpu_info.multi_processor_count)\n        _dict_append(output, f\"GPU {gpu} Total memory (GB)\", round(gpu_info.total_memory / 1024**3, 1))\n        _dict_append(output, f\"GPU {gpu} CUDA capability (maj.min)\", f\"{gpu_info.major}.{gpu_info.minor}\")\n\n    return output\n\n\ndef print_gpu_info(file: TextIO = sys.stdout) -> None:\n    \"\"\"\n    Print GPU info to `file`.\n\n    Args:\n        file: `print()` text stream file. Defaults to `sys.stdout`.\n    \"\"\"\n    for k, v in get_gpu_info().items():\n        print(f\"{k}: {v}\", file=file, flush=True)\n\n\ndef print_debug_info(file: TextIO = sys.stdout) -> None:\n    \"\"\"\n    Print config (installed dependencies, etc.) and system info for debugging.\n\n    Args:\n        file: `print()` text stream file. Defaults to `sys.stdout`.\n    \"\"\"\n    print(\"================================\", file=file, flush=True)\n    print(\"Printing MONAI config...\", file=file, flush=True)\n    print(\"================================\", file=file, flush=True)\n    print_config(file)\n    print(\"\\n================================\", file=file, flush=True)\n    print(\"Printing system config...\")\n    print(\"================================\", file=file, flush=True)\n    print_system_info(file)\n    print(\"\\n================================\", file=file, flush=True)\n    print(\"Printing GPU config...\")\n    print(\"================================\", file=file, flush=True)\n    print_gpu_info(file)\n\n\nclass IgniteInfo:\n    \"\"\"\n    Config information of the PyTorch ignite package.\n\n    \"\"\"\n\n    OPT_IMPORT_VERSION = \"0.4.4\"\n\n\nif __name__ == \"__main__\":\n    print_debug_info()\n", "path": "monai/config/deviceconfig.py"}], "after_files": [{"content": "# Copyright (c) MONAI Consortium\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import annotations\n\nimport getpass\nimport os\nimport platform\nimport re\nimport sys\nfrom collections import OrderedDict\nfrom typing import TextIO\n\nimport numpy as np\nimport torch\n\nimport monai\nfrom monai.utils.module import OptionalImportError, get_package_version, optional_import\n\ntry:\n    _, HAS_EXT = optional_import(\"monai._C\")\n    USE_COMPILED = HAS_EXT and os.getenv(\"BUILD_MONAI\", \"0\") == \"1\"\nexcept (OptionalImportError, ImportError, AttributeError):\n    HAS_EXT = USE_COMPILED = False\n\nUSE_META_DICT = os.environ.get(\"USE_META_DICT\", \"0\") == \"1\"  # set to True for compatibility, use meta dict.\n\npsutil, has_psutil = optional_import(\"psutil\")\npsutil_version = psutil.__version__ if has_psutil else \"NOT INSTALLED or UNKNOWN VERSION.\"\n\n__all__ = [\n    \"print_config\",\n    \"get_system_info\",\n    \"print_system_info\",\n    \"get_gpu_info\",\n    \"print_gpu_info\",\n    \"print_debug_info\",\n    \"USE_COMPILED\",\n    \"USE_META_DICT\",\n    \"IgniteInfo\",\n]\n\n\ndef get_config_values():\n    \"\"\"\n    Read the package versions into a dictionary.\n    \"\"\"\n    output = OrderedDict()\n\n    output[\"MONAI\"] = monai.__version__\n    output[\"Numpy\"] = np.version.full_version\n    output[\"Pytorch\"] = torch.__version__\n\n    return output\n\n\ndef get_optional_config_values():\n    \"\"\"\n    Read the optional package versions into a dictionary.\n    \"\"\"\n    output = OrderedDict()\n\n    output[\"Pytorch Ignite\"] = get_package_version(\"ignite\")\n    output[\"ITK\"] = get_package_version(\"itk\")\n    output[\"Nibabel\"] = get_package_version(\"nibabel\")\n    output[\"scikit-image\"] = get_package_version(\"skimage\")\n    output[\"scipy\"] = get_package_version(\"scipy\")\n    output[\"Pillow\"] = get_package_version(\"PIL\")\n    output[\"Tensorboard\"] = get_package_version(\"tensorboard\")\n    output[\"gdown\"] = get_package_version(\"gdown\")\n    output[\"TorchVision\"] = get_package_version(\"torchvision\")\n    output[\"tqdm\"] = get_package_version(\"tqdm\")\n    output[\"lmdb\"] = get_package_version(\"lmdb\")\n    output[\"psutil\"] = psutil_version\n    output[\"pandas\"] = get_package_version(\"pandas\")\n    output[\"einops\"] = get_package_version(\"einops\")\n    output[\"transformers\"] = get_package_version(\"transformers\")\n    output[\"mlflow\"] = get_package_version(\"mlflow\")\n    output[\"pynrrd\"] = get_package_version(\"nrrd\")\n    output[\"clearml\"] = get_package_version(\"clearml\")\n\n    return output\n\n\ndef print_config(file=sys.stdout):\n    \"\"\"\n    Print the package versions to `file`.\n\n    Args:\n        file: `print()` text stream file. Defaults to `sys.stdout`.\n    \"\"\"\n    for k, v in get_config_values().items():\n        print(f\"{k} version: {v}\", file=file, flush=True)\n    print(f\"MONAI flags: HAS_EXT = {HAS_EXT}, USE_COMPILED = {USE_COMPILED}, USE_META_DICT = {USE_META_DICT}\")\n    print(f\"MONAI rev id: {monai.__revision_id__}\")\n    username = getpass.getuser()\n    masked_file_path = re.sub(username, \"<username>\", monai.__file__)\n    print(f\"MONAI __file__: {masked_file_path}\", file=file, flush=True)\n    print(\"\\nOptional dependencies:\", file=file, flush=True)\n    for k, v in get_optional_config_values().items():\n        print(f\"{k} version: {v}\", file=file, flush=True)\n    print(\"\\nFor details about installing the optional dependencies, please visit:\", file=file, flush=True)\n    print(\n        \"    https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies\\n\",\n        file=file,\n        flush=True,\n    )\n\n\ndef _dict_append(in_dict, key, fn):\n    try:\n        in_dict[key] = fn() if callable(fn) else fn\n    except BaseException:\n        in_dict[key] = \"UNKNOWN for given OS\"\n\n\ndef get_system_info() -> OrderedDict:\n    \"\"\"\n    Get system info as an ordered dictionary.\n    \"\"\"\n    output: OrderedDict = OrderedDict()\n\n    _dict_append(output, \"System\", platform.system)\n    if output[\"System\"] == \"Windows\":\n        _dict_append(output, \"Win32 version\", platform.win32_ver)\n        if hasattr(platform, \"win32_edition\"):\n            _dict_append(output, \"Win32 edition\", platform.win32_edition)\n\n    elif output[\"System\"] == \"Darwin\":\n        _dict_append(output, \"Mac version\", lambda: platform.mac_ver()[0])\n    else:\n        with open(\"/etc/os-release\") as rel_f:\n            linux_ver = re.search(r'PRETTY_NAME=\"(.*)\"', rel_f.read())\n        if linux_ver:\n            _dict_append(output, \"Linux version\", lambda: linux_ver.group(1))\n\n    _dict_append(output, \"Platform\", platform.platform)\n    _dict_append(output, \"Processor\", platform.processor)\n    _dict_append(output, \"Machine\", platform.machine)\n    _dict_append(output, \"Python version\", platform.python_version)\n\n    if not has_psutil:\n        _dict_append(output, \"`psutil` missing\", lambda: \"run `pip install monai[psutil]`\")\n    else:\n        p = psutil.Process()\n        with p.oneshot():\n            _dict_append(output, \"Process name\", p.name)\n            _dict_append(output, \"Command\", p.cmdline)\n            _dict_append(output, \"Open files\", p.open_files)\n            _dict_append(output, \"Num physical CPUs\", lambda: psutil.cpu_count(logical=False))\n            _dict_append(output, \"Num logical CPUs\", lambda: psutil.cpu_count(logical=True))\n            _dict_append(output, \"Num usable CPUs\", lambda: len(psutil.Process().cpu_affinity()))\n            _dict_append(output, \"CPU usage (%)\", lambda: psutil.cpu_percent(percpu=True))\n            _dict_append(output, \"CPU freq. (MHz)\", lambda: round(psutil.cpu_freq(percpu=False)[0]))\n            _dict_append(\n                output,\n                \"Load avg. in last 1, 5, 15 mins (%)\",\n                lambda: [round(x / psutil.cpu_count() * 100, 1) for x in psutil.getloadavg()],\n            )\n            _dict_append(output, \"Disk usage (%)\", lambda: psutil.disk_usage(os.getcwd()).percent)\n            _dict_append(\n                output,\n                \"Avg. sensor temp. (Celsius)\",\n                lambda: np.round(\n                    np.mean([item.current for sublist in psutil.sensors_temperatures().values() for item in sublist], 1)\n                ),\n            )\n            mem = psutil.virtual_memory()\n            _dict_append(output, \"Total physical memory (GB)\", lambda: round(mem.total / 1024**3, 1))\n            _dict_append(output, \"Available memory (GB)\", lambda: round(mem.available / 1024**3, 1))\n            _dict_append(output, \"Used memory (GB)\", lambda: round(mem.used / 1024**3, 1))\n\n    return output\n\n\ndef print_system_info(file: TextIO = sys.stdout) -> None:\n    \"\"\"\n    Print system info to `file`. Requires the optional library, `psutil`.\n\n    Args:\n        file: `print()` text stream file. Defaults to `sys.stdout`.\n    \"\"\"\n    if not has_psutil:\n        print(\"`psutil` required for `print_system_info`\", file=file, flush=True)\n    else:\n        for k, v in get_system_info().items():\n            print(f\"{k}: {v}\", file=file, flush=True)\n\n\ndef get_gpu_info() -> OrderedDict:\n    output: OrderedDict = OrderedDict()\n\n    num_gpus = torch.cuda.device_count()\n    _dict_append(output, \"Num GPUs\", lambda: num_gpus)\n\n    _dict_append(output, \"Has CUDA\", lambda: bool(torch.cuda.is_available()))\n\n    if output[\"Has CUDA\"]:\n        _dict_append(output, \"CUDA version\", lambda: torch.version.cuda)\n    cudnn_ver = torch.backends.cudnn.version()\n    _dict_append(output, \"cuDNN enabled\", lambda: bool(cudnn_ver))\n    _dict_append(output, \"NVIDIA_TF32_OVERRIDE\", os.environ.get(\"NVIDIA_TF32_OVERRIDE\"))\n    _dict_append(output, \"TORCH_ALLOW_TF32_CUBLAS_OVERRIDE\", os.environ.get(\"TORCH_ALLOW_TF32_CUBLAS_OVERRIDE\"))\n\n    if cudnn_ver:\n        _dict_append(output, \"cuDNN version\", lambda: cudnn_ver)\n\n    if num_gpus > 0:\n        _dict_append(output, \"Current device\", torch.cuda.current_device)\n        _dict_append(output, \"Library compiled for CUDA architectures\", torch.cuda.get_arch_list)\n\n    for gpu in range(num_gpus):\n        gpu_info = torch.cuda.get_device_properties(gpu)\n        _dict_append(output, f\"GPU {gpu} Name\", gpu_info.name)\n        _dict_append(output, f\"GPU {gpu} Is integrated\", bool(gpu_info.is_integrated))\n        _dict_append(output, f\"GPU {gpu} Is multi GPU board\", bool(gpu_info.is_multi_gpu_board))\n        _dict_append(output, f\"GPU {gpu} Multi processor count\", gpu_info.multi_processor_count)\n        _dict_append(output, f\"GPU {gpu} Total memory (GB)\", round(gpu_info.total_memory / 1024**3, 1))\n        _dict_append(output, f\"GPU {gpu} CUDA capability (maj.min)\", f\"{gpu_info.major}.{gpu_info.minor}\")\n\n    return output\n\n\ndef print_gpu_info(file: TextIO = sys.stdout) -> None:\n    \"\"\"\n    Print GPU info to `file`.\n\n    Args:\n        file: `print()` text stream file. Defaults to `sys.stdout`.\n    \"\"\"\n    for k, v in get_gpu_info().items():\n        print(f\"{k}: {v}\", file=file, flush=True)\n\n\ndef print_debug_info(file: TextIO = sys.stdout) -> None:\n    \"\"\"\n    Print config (installed dependencies, etc.) and system info for debugging.\n\n    Args:\n        file: `print()` text stream file. Defaults to `sys.stdout`.\n    \"\"\"\n    print(\"================================\", file=file, flush=True)\n    print(\"Printing MONAI config...\", file=file, flush=True)\n    print(\"================================\", file=file, flush=True)\n    print_config(file)\n    print(\"\\n================================\", file=file, flush=True)\n    print(\"Printing system config...\")\n    print(\"================================\", file=file, flush=True)\n    print_system_info(file)\n    print(\"\\n================================\", file=file, flush=True)\n    print(\"Printing GPU config...\")\n    print(\"================================\", file=file, flush=True)\n    print_gpu_info(file)\n\n\nclass IgniteInfo:\n    \"\"\"\n    Config information of the PyTorch ignite package.\n\n    \"\"\"\n\n    OPT_IMPORT_VERSION = \"0.4.4\"\n\n\nif __name__ == \"__main__\":\n    print_debug_info()\n", "path": "monai/config/deviceconfig.py"}]}