prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  BUG: Too many JSON files error
  https://mne.discourse.group/t/mne-bids-pipeline-too-many-json-files-error/6436
  
  > This is a MEG dataset which I converted to BIDS format using mne-bids. The json files which appear to cause the trouble are [_beh.json] sidecar files for the behavioural data I saved to the beh/ subfolder like so:
  >
  > |MNE-BIDS_data/
  > |— README
  > |— dataset_description.json
  > |— participants.json
  > |— participants.tsv
  > |— sub-01/
  > |------ sub-01_scans.tsv
  > |------ beh/
  > |--------- sub-01_task-main_run-01_beh.json
  > |--------- sub-01_task-main_run-01_beh.tsv
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `mne_bids_pipeline/steps/init/_02_find_empty_room.py`
  Content:
  ```
  1 """Find empty-room data matches."""
  2 
  3 from types import SimpleNamespace
  4 from typing import Dict, Optional
  5 
  6 from mne.utils import _pl
  7 from mne_bids import BIDSPath
  8 
  9 from ..._config_utils import (
  10     get_datatype,
  11     get_task,
  12     get_sessions,
  13     get_subjects,
  14     get_runs,
  15 )
  16 from ..._io import _empty_room_match_path, _write_json
  17 from ..._logging import gen_log_kwargs, logger
  18 from ..._run import _update_for_splits, failsafe_run, save_logs
  19 
  20 
  21 def get_input_fnames_find_empty_room(
  22     *, subject: str, session: Optional[str], run: Optional[str], cfg: SimpleNamespace
  23 ) -> Dict[str, BIDSPath]:
  24     """Get paths of files required by filter_data function."""
  25     bids_path_in = BIDSPath(
  26         subject=subject,
  27         run=run,
  28         session=session,
  29         task=cfg.task,
  30         acquisition=cfg.acq,
  31         recording=cfg.rec,
  32         space=cfg.space,
  33         datatype=cfg.datatype,
  34         processing=cfg.proc,
  35         root=cfg.bids_root,
  36         check=False,
  37     )
  38     in_files: Dict[str, BIDSPath] = dict()
  39     in_files[f"raw_run-{run}"] = bids_path_in
  40     _update_for_splits(in_files, f"raw_run-{run}", single=True)
  41     if hasattr(bids_path_in, "find_matching_sidecar"):
  42         in_files["sidecar"] = (
  43             bids_path_in.copy()
  44             .update(datatype=None)
  45             .find_matching_sidecar(extension=".json")
  46         )
  47     try:
  48         fname = bids_path_in.find_empty_room(use_sidecar_only=True)
  49     except Exception:
  50         fname = None
  51     if fname is None and hasattr(bids_path_in, "get_empty_room_candidates"):
  52         for ci, path in enumerate(bids_path_in.get_empty_room_candidates()):
  53             in_files[f"empty_room_candidate_{ci}"] = path
  54     return in_files
  55 
  56 
  57 @failsafe_run(
  58     get_input_fnames=get_input_fnames_find_empty_room,
  59 )
  60 def find_empty_room(
  61     *,
  62     cfg: SimpleNamespace,
  63     exec_params: SimpleNamespace,
  64     subject: str,
  65     session: Optional[str],
  66     run: Optional[str],
  67     in_files: Dict[str, BIDSPath],
  68 ) -> Dict[str, BIDSPath]:
  69     raw_path = in_files.pop(f"raw_run-{run}")
  70     in_files.pop("sidecar", None)
  71     try:
  72         fname = raw_path.find_empty_room(use_sidecar_only=True)
  73     except (FileNotFoundError, AssertionError, ValueError):
  74         fname = ""
  75     if fname is None:
  76         # sidecar is very fast and checking all can be slow (seconds), so only
  77         # log when actually looking through files
  78         ending = "empty-room files"
  79         if len(in_files):  # MNE-BIDS < 0.12 missing get_empty_room_candidates
  80             ending = f"{len(in_files)} empty-room file{_pl(in_files)}"
  81         msg = f"Nearest-date matching {ending}"
  82         logger.info(**gen_log_kwargs(message=msg))
  83         try:
  84             fname = raw_path.find_empty_room()
  85         except (
  86             ValueError,  # non-MEG data
  87             AssertionError,  # MNE-BIDS check assert exists()
  88             FileNotFoundError,
  89         ):  # MNE-BIDS PR-1080 exists()
  90             fname = None
  91         in_files.clear()  # MNE-BIDS find_empty_room should have looked at all
  92     elif fname == "":
  93         fname = None  # not downloaded, or EEG data
  94     elif not fname.fpath.exists():
  95         fname = None  # path found by sidecar but does not exist
  96     out_files = dict()
  97     out_files["empty_room_match"] = _empty_room_match_path(raw_path, cfg)
  98     _write_json(out_files["empty_room_match"], dict(fname=fname))
  99     return out_files
  100 
  101 
  102 def get_config(
  103     *,
  104     config,
  105 ) -> SimpleNamespace:
  106     cfg = SimpleNamespace(
  107         proc=config.proc,
  108         task=get_task(config),
  109         datatype=get_datatype(config),
  110         acq=config.acq,
  111         rec=config.rec,
  112         space=config.space,
  113         bids_root=config.bids_root,
  114         deriv_root=config.deriv_root,
  115     )
  116     return cfg
  117 
  118 
  119 def main(*, config) -> None:
  120     """Run find_empty_room."""
  121     if not config.process_empty_room:
  122         msg = "Skipping, process_empty_room is set to False …"
  123         logger.info(**gen_log_kwargs(message=msg, emoji="skip"))
  124         return
  125     if get_datatype(config) != "meg":
  126         msg = "Skipping, empty-room data only relevant for MEG …"
  127         logger.info(**gen_log_kwargs(message=msg, emoji="skip"))
  128         return
  129     # This will be I/O bound if the sidecar is not complete, so let's not run
  130     # in parallel.
  131     logs = list()
  132     for subject in get_subjects(config):
  133         if config.use_maxwell_filter:
  134             run = config.mf_reference_run
  135         else:
  136             run = get_runs(config=config, subject=subject)[0]
  137         logs.append(
  138             find_empty_room(
  139                 cfg=get_config(
  140                     config=config,
  141                 ),
  142                 exec_params=config.exec_params,
  143                 subject=subject,
  144                 session=get_sessions(config)[0],
  145                 run=run,
  146             )
  147         )
  148     save_logs(config=config, logs=logs)
  149
  ```
  --- 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()
  
  ```
  
golden_diff: diff --git a/mne_bids_pipeline/steps/init/_02_find_empty_room.py b/mne_bids_pipeline/steps/init/_02_find_empty_room.py
  --- a/mne_bids_pipeline/steps/init/_02_find_empty_room.py
  +++ b/mne_bids_pipeline/steps/init/_02_find_empty_room.py
  @@ -41,7 +41,7 @@
       if hasattr(bids_path_in, "find_matching_sidecar"):
           in_files["sidecar"] = (
               bids_path_in.copy()
  -            .update(datatype=None)
  +            .update(datatype=None, suffix="meg")
               .find_matching_sidecar(extension=".json")
           )
       try:
  
verification_info: {"golden_diff": "diff --git a/mne_bids_pipeline/steps/init/_02_find_empty_room.py b/mne_bids_pipeline/steps/init/_02_find_empty_room.py\n--- a/mne_bids_pipeline/steps/init/_02_find_empty_room.py\n+++ b/mne_bids_pipeline/steps/init/_02_find_empty_room.py\n@@ -41,7 +41,7 @@\n     if hasattr(bids_path_in, \"find_matching_sidecar\"):\n         in_files[\"sidecar\"] = (\n             bids_path_in.copy()\n-            .update(datatype=None)\n+            .update(datatype=None, suffix=\"meg\")\n             .find_matching_sidecar(extension=\".json\")\n         )\n     try:\n", "issue": "BUG: Too many JSON files error\nhttps://mne.discourse.group/t/mne-bids-pipeline-too-many-json-files-error/6436\r\n\r\n> This is a MEG dataset which I converted to BIDS format using mne-bids. The json files which appear to cause the trouble are [_beh.json] sidecar files for the behavioural data I saved to the beh/ subfolder like so:\r\n>\r\n> |MNE-BIDS_data/\r\n> |\u2014 README\r\n> |\u2014 dataset_description.json\r\n> |\u2014 participants.json\r\n> |\u2014 participants.tsv\r\n> |\u2014 sub-01/\r\n> |------ sub-01_scans.tsv\r\n> |------ beh/\r\n> |--------- sub-01_task-main_run-01_beh.json\r\n> |--------- sub-01_task-main_run-01_beh.tsv\n", "before_files": [{"content": "\"\"\"Find empty-room data matches.\"\"\"\n\nfrom types import SimpleNamespace\nfrom typing import Dict, Optional\n\nfrom mne.utils import _pl\nfrom mne_bids import BIDSPath\n\nfrom ..._config_utils import (\n    get_datatype,\n    get_task,\n    get_sessions,\n    get_subjects,\n    get_runs,\n)\nfrom ..._io import _empty_room_match_path, _write_json\nfrom ..._logging import gen_log_kwargs, logger\nfrom ..._run import _update_for_splits, failsafe_run, save_logs\n\n\ndef get_input_fnames_find_empty_room(\n    *, subject: str, session: Optional[str], run: Optional[str], cfg: SimpleNamespace\n) -> Dict[str, BIDSPath]:\n    \"\"\"Get paths of files required by filter_data function.\"\"\"\n    bids_path_in = BIDSPath(\n        subject=subject,\n        run=run,\n        session=session,\n        task=cfg.task,\n        acquisition=cfg.acq,\n        recording=cfg.rec,\n        space=cfg.space,\n        datatype=cfg.datatype,\n        processing=cfg.proc,\n        root=cfg.bids_root,\n        check=False,\n    )\n    in_files: Dict[str, BIDSPath] = dict()\n    in_files[f\"raw_run-{run}\"] = bids_path_in\n    _update_for_splits(in_files, f\"raw_run-{run}\", single=True)\n    if hasattr(bids_path_in, \"find_matching_sidecar\"):\n        in_files[\"sidecar\"] = (\n            bids_path_in.copy()\n            .update(datatype=None)\n            .find_matching_sidecar(extension=\".json\")\n        )\n    try:\n        fname = bids_path_in.find_empty_room(use_sidecar_only=True)\n    except Exception:\n        fname = None\n    if fname is None and hasattr(bids_path_in, \"get_empty_room_candidates\"):\n        for ci, path in enumerate(bids_path_in.get_empty_room_candidates()):\n            in_files[f\"empty_room_candidate_{ci}\"] = path\n    return in_files\n\n\n@failsafe_run(\n    get_input_fnames=get_input_fnames_find_empty_room,\n)\ndef find_empty_room(\n    *,\n    cfg: SimpleNamespace,\n    exec_params: SimpleNamespace,\n    subject: str,\n    session: Optional[str],\n    run: Optional[str],\n    in_files: Dict[str, BIDSPath],\n) -> Dict[str, BIDSPath]:\n    raw_path = in_files.pop(f\"raw_run-{run}\")\n    in_files.pop(\"sidecar\", None)\n    try:\n        fname = raw_path.find_empty_room(use_sidecar_only=True)\n    except (FileNotFoundError, AssertionError, ValueError):\n        fname = \"\"\n    if fname is None:\n        # sidecar is very fast and checking all can be slow (seconds), so only\n        # log when actually looking through files\n        ending = \"empty-room files\"\n        if len(in_files):  # MNE-BIDS < 0.12 missing get_empty_room_candidates\n            ending = f\"{len(in_files)} empty-room file{_pl(in_files)}\"\n        msg = f\"Nearest-date matching {ending}\"\n        logger.info(**gen_log_kwargs(message=msg))\n        try:\n            fname = raw_path.find_empty_room()\n        except (\n            ValueError,  # non-MEG data\n            AssertionError,  # MNE-BIDS check assert exists()\n            FileNotFoundError,\n        ):  # MNE-BIDS PR-1080 exists()\n            fname = None\n        in_files.clear()  # MNE-BIDS find_empty_room should have looked at all\n    elif fname == \"\":\n        fname = None  # not downloaded, or EEG data\n    elif not fname.fpath.exists():\n        fname = None  # path found by sidecar but does not exist\n    out_files = dict()\n    out_files[\"empty_room_match\"] = _empty_room_match_path(raw_path, cfg)\n    _write_json(out_files[\"empty_room_match\"], dict(fname=fname))\n    return out_files\n\n\ndef get_config(\n    *,\n    config,\n) -> SimpleNamespace:\n    cfg = SimpleNamespace(\n        proc=config.proc,\n        task=get_task(config),\n        datatype=get_datatype(config),\n        acq=config.acq,\n        rec=config.rec,\n        space=config.space,\n        bids_root=config.bids_root,\n        deriv_root=config.deriv_root,\n    )\n    return cfg\n\n\ndef main(*, config) -> None:\n    \"\"\"Run find_empty_room.\"\"\"\n    if not config.process_empty_room:\n        msg = \"Skipping, process_empty_room is set to False \u2026\"\n        logger.info(**gen_log_kwargs(message=msg, emoji=\"skip\"))\n        return\n    if get_datatype(config) != \"meg\":\n        msg = \"Skipping, empty-room data only relevant for MEG \u2026\"\n        logger.info(**gen_log_kwargs(message=msg, emoji=\"skip\"))\n        return\n    # This will be I/O bound if the sidecar is not complete, so let's not run\n    # in parallel.\n    logs = list()\n    for subject in get_subjects(config):\n        if config.use_maxwell_filter:\n            run = config.mf_reference_run\n        else:\n            run = get_runs(config=config, subject=subject)[0]\n        logs.append(\n            find_empty_room(\n                cfg=get_config(\n                    config=config,\n                ),\n                exec_params=config.exec_params,\n                subject=subject,\n                session=get_sessions(config)[0],\n                run=run,\n            )\n        )\n    save_logs(config=config, logs=logs)\n", "path": "mne_bids_pipeline/steps/init/_02_find_empty_room.py"}], "after_files": [{"content": "\"\"\"Find empty-room data matches.\"\"\"\n\nfrom types import SimpleNamespace\nfrom typing import Dict, Optional\n\nfrom mne.utils import _pl\nfrom mne_bids import BIDSPath\n\nfrom ..._config_utils import (\n    get_datatype,\n    get_task,\n    get_sessions,\n    get_subjects,\n    get_runs,\n)\nfrom ..._io import _empty_room_match_path, _write_json\nfrom ..._logging import gen_log_kwargs, logger\nfrom ..._run import _update_for_splits, failsafe_run, save_logs\n\n\ndef get_input_fnames_find_empty_room(\n    *, subject: str, session: Optional[str], run: Optional[str], cfg: SimpleNamespace\n) -> Dict[str, BIDSPath]:\n    \"\"\"Get paths of files required by filter_data function.\"\"\"\n    bids_path_in = BIDSPath(\n        subject=subject,\n        run=run,\n        session=session,\n        task=cfg.task,\n        acquisition=cfg.acq,\n        recording=cfg.rec,\n        space=cfg.space,\n        datatype=cfg.datatype,\n        processing=cfg.proc,\n        root=cfg.bids_root,\n        check=False,\n    )\n    in_files: Dict[str, BIDSPath] = dict()\n    in_files[f\"raw_run-{run}\"] = bids_path_in\n    _update_for_splits(in_files, f\"raw_run-{run}\", single=True)\n    if hasattr(bids_path_in, \"find_matching_sidecar\"):\n        in_files[\"sidecar\"] = (\n            bids_path_in.copy()\n            .update(datatype=None, suffix=\"meg\")\n            .find_matching_sidecar(extension=\".json\")\n        )\n    try:\n        fname = bids_path_in.find_empty_room(use_sidecar_only=True)\n    except Exception:\n        fname = None\n    if fname is None and hasattr(bids_path_in, \"get_empty_room_candidates\"):\n        for ci, path in enumerate(bids_path_in.get_empty_room_candidates()):\n            in_files[f\"empty_room_candidate_{ci}\"] = path\n    return in_files\n\n\n@failsafe_run(\n    get_input_fnames=get_input_fnames_find_empty_room,\n)\ndef find_empty_room(\n    *,\n    cfg: SimpleNamespace,\n    exec_params: SimpleNamespace,\n    subject: str,\n    session: Optional[str],\n    run: Optional[str],\n    in_files: Dict[str, BIDSPath],\n) -> Dict[str, BIDSPath]:\n    raw_path = in_files.pop(f\"raw_run-{run}\")\n    in_files.pop(\"sidecar\", None)\n    try:\n        fname = raw_path.find_empty_room(use_sidecar_only=True)\n    except (FileNotFoundError, AssertionError, ValueError):\n        fname = \"\"\n    if fname is None:\n        # sidecar is very fast and checking all can be slow (seconds), so only\n        # log when actually looking through files\n        ending = \"empty-room files\"\n        if len(in_files):  # MNE-BIDS < 0.12 missing get_empty_room_candidates\n            ending = f\"{len(in_files)} empty-room file{_pl(in_files)}\"\n        msg = f\"Nearest-date matching {ending}\"\n        logger.info(**gen_log_kwargs(message=msg))\n        try:\n            fname = raw_path.find_empty_room()\n        except (\n            ValueError,  # non-MEG data\n            AssertionError,  # MNE-BIDS check assert exists()\n            FileNotFoundError,\n        ):  # MNE-BIDS PR-1080 exists()\n            fname = None\n        in_files.clear()  # MNE-BIDS find_empty_room should have looked at all\n    elif fname == \"\":\n        fname = None  # not downloaded, or EEG data\n    elif not fname.fpath.exists():\n        fname = None  # path found by sidecar but does not exist\n    out_files = dict()\n    out_files[\"empty_room_match\"] = _empty_room_match_path(raw_path, cfg)\n    _write_json(out_files[\"empty_room_match\"], dict(fname=fname))\n    return out_files\n\n\ndef get_config(\n    *,\n    config,\n) -> SimpleNamespace:\n    cfg = SimpleNamespace(\n        proc=config.proc,\n        task=get_task(config),\n        datatype=get_datatype(config),\n        acq=config.acq,\n        rec=config.rec,\n        space=config.space,\n        bids_root=config.bids_root,\n        deriv_root=config.deriv_root,\n    )\n    return cfg\n\n\ndef main(*, config) -> None:\n    \"\"\"Run find_empty_room.\"\"\"\n    if not config.process_empty_room:\n        msg = \"Skipping, process_empty_room is set to False \u2026\"\n        logger.info(**gen_log_kwargs(message=msg, emoji=\"skip\"))\n        return\n    if get_datatype(config) != \"meg\":\n        msg = \"Skipping, empty-room data only relevant for MEG \u2026\"\n        logger.info(**gen_log_kwargs(message=msg, emoji=\"skip\"))\n        return\n    # This will be I/O bound if the sidecar is not complete, so let's not run\n    # in parallel.\n    logs = list()\n    for subject in get_subjects(config):\n        if config.use_maxwell_filter:\n            run = config.mf_reference_run\n        else:\n            run = get_runs(config=config, subject=subject)[0]\n        logs.append(\n            find_empty_room(\n                cfg=get_config(\n                    config=config,\n                ),\n                exec_params=config.exec_params,\n                subject=subject,\n                session=get_sessions(config)[0],\n                run=run,\n            )\n        )\n    save_logs(config=config, logs=logs)\n", "path": "mne_bids_pipeline/steps/init/_02_find_empty_room.py"}]}