prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  [datasets] Targets are modified inplace
  ### Bug description
  
  **Targets** are being changed when iterating over some dataset more than one time.
  The reason is storing targets in self.data, and changing them in the `__getitem__` ***in place*** using `pre_transforms`, etc.
  ```python
  # _AbstractDataset
  def __getitem__(
          self,
          index: int
      ) -> Tuple[Any, Any]:
  
          # Read image
          img, target = self._read_sample(index)
          # Pre-transforms (format conversion at run-time etc.)
          if self._pre_transforms is not None:
              img, target = self._pre_transforms(img, target)
  
          if self.img_transforms is not None:
              # typing issue cf. https://github.com/python/mypy/issues/5485
              img = self.img_transforms(img)  # type: ignore[call-arg]
  
          if self.sample_transforms is not None:
              img, target = self.sample_transforms(img, target)
  
          return img, target
  ```
  
  This can be fixed by copying target in the `_read_sample` 
  ```python
  # AbstractDataset
  def _read_sample(self, index: int) -> Tuple[tf.Tensor, Any]:
          img_name, target = self.data[index]
          # Read image
          img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=tf.float32)
  
          return img, target
  ```
  
  **OR** returning a copy of the target in all transform methods.
  ```python
  def convert_target_to_relative(img: ImageTensor, target: Dict[str, Any]) -> Tuple[ImageTensor, Dict[str, Any]]:
  
      target['boxes'] = convert_to_relative_coords(target['boxes'], get_img_shape(img))
      return img, target
  ```
  
  
  ### Code snippet to reproduce the bug
  
  ```python
  def process_image(train_example):
    img, target = train_example
    img_numpy = img.numpy() * 255
    for example in target['boxes']:
        print(example)
        unnormalized_example = [int(example[0]*img.shape[1]), int(example[1]*img.shape[0]),
                                int(example[2]*img.shape[1]), int(example[3]*img.shape[0])]
        cv2.rectangle(img=img_numpy,
                      pt1=(unnormalized_example[0], unnormalized_example[1]),
                      pt2=(unnormalized_example[2], unnormalized_example[3]),
                      color=(0, 0, 255), thickness=2)
    return img_numpy  
  
  
  train_set = SROIE(train=True, download=True)
  
  for i in range(2):
    for j, example in enumerate(train_set):
      if j == 0:    
        print(f"{i} ____")
        img_n = process_image(example)
  ```
  
  P.S. Sorry for not a pretty code style. This snippet is just for an example :) 
  
  ### Error traceback
  
  ~changed target box coordinates
  
  ### Environment
  
  .
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `doctr/datasets/datasets/tensorflow.py`
  Content:
  ```
  1 # Copyright (C) 2021-2022, Mindee.
  2 
  3 # This program is licensed under the Apache License version 2.
  4 # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
  5 
  6 import os
  7 from typing import Any, List, Tuple
  8 
  9 import tensorflow as tf
  10 
  11 from doctr.io import read_img_as_tensor
  12 
  13 from .base import _AbstractDataset, _VisionDataset
  14 
  15 __all__ = ['AbstractDataset', 'VisionDataset']
  16 
  17 
  18 class AbstractDataset(_AbstractDataset):
  19 
  20     def _read_sample(self, index: int) -> Tuple[tf.Tensor, Any]:
  21         img_name, target = self.data[index]
  22         # Read image
  23         img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=tf.float32)
  24 
  25         return img, target
  26 
  27     @staticmethod
  28     def collate_fn(samples: List[Tuple[tf.Tensor, Any]]) -> Tuple[tf.Tensor, List[Any]]:
  29 
  30         images, targets = zip(*samples)
  31         images = tf.stack(images, axis=0)
  32 
  33         return images, list(targets)
  34 
  35 
  36 class VisionDataset(AbstractDataset, _VisionDataset):
  37     pass
  38
  ```
  
  Path: `doctr/datasets/datasets/pytorch.py`
  Content:
  ```
  1 # Copyright (C) 2021-2022, Mindee.
  2 
  3 # This program is licensed under the Apache License version 2.
  4 # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
  5 
  6 import os
  7 from typing import Any, List, Tuple
  8 
  9 import torch
  10 
  11 from doctr.io import read_img_as_tensor
  12 
  13 from .base import _AbstractDataset, _VisionDataset
  14 
  15 __all__ = ['AbstractDataset', 'VisionDataset']
  16 
  17 
  18 class AbstractDataset(_AbstractDataset):
  19 
  20     def _read_sample(self, index: int) -> Tuple[torch.Tensor, Any]:
  21         img_name, target = self.data[index]
  22         # Read image
  23         img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=torch.float32)
  24 
  25         return img, target
  26 
  27     @staticmethod
  28     def collate_fn(samples: List[Tuple[torch.Tensor, Any]]) -> Tuple[torch.Tensor, List[Any]]:
  29 
  30         images, targets = zip(*samples)
  31         images = torch.stack(images, dim=0)
  32 
  33         return images, list(targets)
  34 
  35 
  36 class VisionDataset(AbstractDataset, _VisionDataset):
  37     pass
  38
  ```
  --- 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/doctr/datasets/datasets/pytorch.py b/doctr/datasets/datasets/pytorch.py
  --- a/doctr/datasets/datasets/pytorch.py
  +++ b/doctr/datasets/datasets/pytorch.py
  @@ -4,6 +4,7 @@
   # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
   
   import os
  +from copy import deepcopy
   from typing import Any, List, Tuple
   
   import torch
  @@ -22,7 +23,7 @@
           # Read image
           img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=torch.float32)
   
  -        return img, target
  +        return img, deepcopy(target)
   
       @staticmethod
       def collate_fn(samples: List[Tuple[torch.Tensor, Any]]) -> Tuple[torch.Tensor, List[Any]]:
  diff --git a/doctr/datasets/datasets/tensorflow.py b/doctr/datasets/datasets/tensorflow.py
  --- a/doctr/datasets/datasets/tensorflow.py
  +++ b/doctr/datasets/datasets/tensorflow.py
  @@ -4,6 +4,7 @@
   # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
   
   import os
  +from copy import deepcopy
   from typing import Any, List, Tuple
   
   import tensorflow as tf
  @@ -22,7 +23,7 @@
           # Read image
           img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=tf.float32)
   
  -        return img, target
  +        return img, deepcopy(target)
   
       @staticmethod
       def collate_fn(samples: List[Tuple[tf.Tensor, Any]]) -> Tuple[tf.Tensor, List[Any]]:
  
verification_info: {"golden_diff": "diff --git a/doctr/datasets/datasets/pytorch.py b/doctr/datasets/datasets/pytorch.py\n--- a/doctr/datasets/datasets/pytorch.py\n+++ b/doctr/datasets/datasets/pytorch.py\n@@ -4,6 +4,7 @@\n # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.\n \n import os\n+from copy import deepcopy\n from typing import Any, List, Tuple\n \n import torch\n@@ -22,7 +23,7 @@\n         # Read image\n         img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=torch.float32)\n \n-        return img, target\n+        return img, deepcopy(target)\n \n     @staticmethod\n     def collate_fn(samples: List[Tuple[torch.Tensor, Any]]) -> Tuple[torch.Tensor, List[Any]]:\ndiff --git a/doctr/datasets/datasets/tensorflow.py b/doctr/datasets/datasets/tensorflow.py\n--- a/doctr/datasets/datasets/tensorflow.py\n+++ b/doctr/datasets/datasets/tensorflow.py\n@@ -4,6 +4,7 @@\n # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.\n \n import os\n+from copy import deepcopy\n from typing import Any, List, Tuple\n \n import tensorflow as tf\n@@ -22,7 +23,7 @@\n         # Read image\n         img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=tf.float32)\n \n-        return img, target\n+        return img, deepcopy(target)\n \n     @staticmethod\n     def collate_fn(samples: List[Tuple[tf.Tensor, Any]]) -> Tuple[tf.Tensor, List[Any]]:\n", "issue": "[datasets] Targets are modified inplace\n### Bug description\n\n**Targets** are being changed when iterating over some dataset more than one time.\r\nThe reason is storing targets in self.data, and changing them in the `__getitem__` ***in place*** using `pre_transforms`, etc.\r\n```python\r\n# _AbstractDataset\r\ndef __getitem__(\r\n        self,\r\n        index: int\r\n    ) -> Tuple[Any, Any]:\r\n\r\n        # Read image\r\n        img, target = self._read_sample(index)\r\n        # Pre-transforms (format conversion at run-time etc.)\r\n        if self._pre_transforms is not None:\r\n            img, target = self._pre_transforms(img, target)\r\n\r\n        if self.img_transforms is not None:\r\n            # typing issue cf. https://github.com/python/mypy/issues/5485\r\n            img = self.img_transforms(img)  # type: ignore[call-arg]\r\n\r\n        if self.sample_transforms is not None:\r\n            img, target = self.sample_transforms(img, target)\r\n\r\n        return img, target\r\n```\r\n\r\nThis can be fixed by copying target in the `_read_sample` \r\n```python\r\n# AbstractDataset\r\ndef _read_sample(self, index: int) -> Tuple[tf.Tensor, Any]:\r\n        img_name, target = self.data[index]\r\n        # Read image\r\n        img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=tf.float32)\r\n\r\n        return img, target\r\n```\r\n\r\n**OR** returning a copy of the target in all transform methods.\r\n```python\r\ndef convert_target_to_relative(img: ImageTensor, target: Dict[str, Any]) -> Tuple[ImageTensor, Dict[str, Any]]:\r\n\r\n    target['boxes'] = convert_to_relative_coords(target['boxes'], get_img_shape(img))\r\n    return img, target\r\n```\r\n\n\n### Code snippet to reproduce the bug\n\n```python\r\ndef process_image(train_example):\r\n  img, target = train_example\r\n  img_numpy = img.numpy() * 255\r\n  for example in target['boxes']:\r\n      print(example)\r\n      unnormalized_example = [int(example[0]*img.shape[1]), int(example[1]*img.shape[0]),\r\n                              int(example[2]*img.shape[1]), int(example[3]*img.shape[0])]\r\n      cv2.rectangle(img=img_numpy,\r\n                    pt1=(unnormalized_example[0], unnormalized_example[1]),\r\n                    pt2=(unnormalized_example[2], unnormalized_example[3]),\r\n                    color=(0, 0, 255), thickness=2)\r\n  return img_numpy  \r\n\r\n\r\ntrain_set = SROIE(train=True, download=True)\r\n\r\nfor i in range(2):\r\n  for j, example in enumerate(train_set):\r\n    if j == 0:    \r\n      print(f\"{i} ____\")\r\n      img_n = process_image(example)\r\n```\r\n\r\nP.S. Sorry for not a pretty code style. This snippet is just for an example :) \n\n### Error traceback\n\n~changed target box coordinates\n\n### Environment\n\n.\n", "before_files": [{"content": "# Copyright (C) 2021-2022, Mindee.\n\n# This program is licensed under the Apache License version 2.\n# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.\n\nimport os\nfrom typing import Any, List, Tuple\n\nimport tensorflow as tf\n\nfrom doctr.io import read_img_as_tensor\n\nfrom .base import _AbstractDataset, _VisionDataset\n\n__all__ = ['AbstractDataset', 'VisionDataset']\n\n\nclass AbstractDataset(_AbstractDataset):\n\n    def _read_sample(self, index: int) -> Tuple[tf.Tensor, Any]:\n        img_name, target = self.data[index]\n        # Read image\n        img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=tf.float32)\n\n        return img, target\n\n    @staticmethod\n    def collate_fn(samples: List[Tuple[tf.Tensor, Any]]) -> Tuple[tf.Tensor, List[Any]]:\n\n        images, targets = zip(*samples)\n        images = tf.stack(images, axis=0)\n\n        return images, list(targets)\n\n\nclass VisionDataset(AbstractDataset, _VisionDataset):\n    pass\n", "path": "doctr/datasets/datasets/tensorflow.py"}, {"content": "# Copyright (C) 2021-2022, Mindee.\n\n# This program is licensed under the Apache License version 2.\n# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.\n\nimport os\nfrom typing import Any, List, Tuple\n\nimport torch\n\nfrom doctr.io import read_img_as_tensor\n\nfrom .base import _AbstractDataset, _VisionDataset\n\n__all__ = ['AbstractDataset', 'VisionDataset']\n\n\nclass AbstractDataset(_AbstractDataset):\n\n    def _read_sample(self, index: int) -> Tuple[torch.Tensor, Any]:\n        img_name, target = self.data[index]\n        # Read image\n        img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=torch.float32)\n\n        return img, target\n\n    @staticmethod\n    def collate_fn(samples: List[Tuple[torch.Tensor, Any]]) -> Tuple[torch.Tensor, List[Any]]:\n\n        images, targets = zip(*samples)\n        images = torch.stack(images, dim=0)\n\n        return images, list(targets)\n\n\nclass VisionDataset(AbstractDataset, _VisionDataset):\n    pass\n", "path": "doctr/datasets/datasets/pytorch.py"}], "after_files": [{"content": "# Copyright (C) 2021-2022, Mindee.\n\n# This program is licensed under the Apache License version 2.\n# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.\n\nimport os\nfrom copy import deepcopy\nfrom typing import Any, List, Tuple\n\nimport tensorflow as tf\n\nfrom doctr.io import read_img_as_tensor\n\nfrom .base import _AbstractDataset, _VisionDataset\n\n__all__ = ['AbstractDataset', 'VisionDataset']\n\n\nclass AbstractDataset(_AbstractDataset):\n\n    def _read_sample(self, index: int) -> Tuple[tf.Tensor, Any]:\n        img_name, target = self.data[index]\n        # Read image\n        img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=tf.float32)\n\n        return img, deepcopy(target)\n\n    @staticmethod\n    def collate_fn(samples: List[Tuple[tf.Tensor, Any]]) -> Tuple[tf.Tensor, List[Any]]:\n\n        images, targets = zip(*samples)\n        images = tf.stack(images, axis=0)\n\n        return images, list(targets)\n\n\nclass VisionDataset(AbstractDataset, _VisionDataset):\n    pass\n", "path": "doctr/datasets/datasets/tensorflow.py"}, {"content": "# Copyright (C) 2021-2022, Mindee.\n\n# This program is licensed under the Apache License version 2.\n# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.\n\nimport os\nfrom copy import deepcopy\nfrom typing import Any, List, Tuple\n\nimport torch\n\nfrom doctr.io import read_img_as_tensor\n\nfrom .base import _AbstractDataset, _VisionDataset\n\n__all__ = ['AbstractDataset', 'VisionDataset']\n\n\nclass AbstractDataset(_AbstractDataset):\n\n    def _read_sample(self, index: int) -> Tuple[torch.Tensor, Any]:\n        img_name, target = self.data[index]\n        # Read image\n        img = read_img_as_tensor(os.path.join(self.root, img_name), dtype=torch.float32)\n\n        return img, deepcopy(target)\n\n    @staticmethod\n    def collate_fn(samples: List[Tuple[torch.Tensor, Any]]) -> Tuple[torch.Tensor, List[Any]]:\n\n        images, targets = zip(*samples)\n        images = torch.stack(images, dim=0)\n\n        return images, list(targets)\n\n\nclass VisionDataset(AbstractDataset, _VisionDataset):\n    pass\n", "path": "doctr/datasets/datasets/pytorch.py"}]}