internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: lightly-ai/lightly

Issue:
VICReg Loss De-Means Twice?
https://github.com/lightly-ai/lightly/blob/66ad1b40ebf3b53512703c774988211ce283211f/lightly/loss/vicreg_loss.py#L128-L129

I think the VICReg loss removes the mean, then calls `.var()` which also de-means (see: https://pytorch.org/docs/stable/generated/torch.var.html). 

If I understand correctly, that seems unnecessary?


Discussion:
Hi @RylanSchaeffer, thank you for bringing this up. I think you are right, the de-mean is only necessary for the covariance term.

Resolving patch:
diff --git a/lightly/loss/vicreg_loss.py b/lightly/loss/vicreg_loss.py
--- a/lightly/loss/vicreg_loss.py
+++ b/lightly/loss/vicreg_loss.py
@@ -125,7 +125,6 @@ def variance_loss(x: Tensor, eps: float = 0.0001) -> Tensor:
         eps:
             Epsilon for numerical stability.
     """
-    x = x - x.mean(dim=0)
     std = torch.sqrt(x.var(dim=0) + eps)
     loss = torch.mean(F.relu(1.0 - std))
     return loss


Test patch:
Repository: lightly-ai/lightly

Issue:
Tutorial 3: small typo "strcture" -> "structure"
In [this section](https://docs.lightly.ai/self-supervised-learning/tutorials/package/tutorial_simclr_clothing.html#setup-data-augmentations-and-loaders), the first paragraph has the following typo:

"strcture" -> "structure"



Discussion:
Thanks! Let's quickly fix this.

Resolving patch:
diff --git a/docs/source/tutorials_source/package/tutorial_simclr_clothing.py b/docs/source/tutorials_source/package/tutorial_simclr_clothing.py
--- a/docs/source/tutorials_source/package/tutorial_simclr_clothing.py
+++ b/docs/source/tutorials_source/package/tutorial_simclr_clothing.py
@@ -84,7 +84,7 @@
 # such as vertical flip or random rotation (90 degrees).
 # By adding these augmentations we learn our model invariance regarding the
 # orientation of the clothing piece. E.g. we don't care if a shirt is upside down
-# but more about the strcture which make it a shirt.
+# but more about the structure which make it a shirt.
 #
 # You can learn more about the different augmentations and learned invariances
 # here: :ref:`lightly-advanced`.


Test patch:
Repository: roboflow/supervision

Issue:
Better handling of wrong data types of mask for sv.PolygonZone()
### Search before asking

- [X] I have searched the Supervision [issues](https://github.com/roboflow/supervision/issues) and found no similar feature requests.


### Description

<img width="898" alt="image" src="https://github.com/roboflow/supervision/assets/47161914/6eebe556-97f1-452b-8757-17062548ca12">

OpenCV errors out with an uninformative error when the dtype of the mask is wrong. 

Would be good to add catch if dtype != np.int32 and raise an Exception.

### Use case

I was trying to create a mask in CVAT, the exported segmentation had decimal places, np.array(coords) did not convert to np.int32, and I was confused by the bad error message.

This is likely to happen to other users too .

### Additional

Happy to submit PR

### Are you willing to submit a PR?

- [X] Yes I'd like to help by submitting a PR!


Discussion:
Hello there, thank you for opening an Issue ! 🙏🏻 The team was notified and they will get back to you asap.
Hi, @GeorgePearse 👋🏻! I think it would be even better if we tried to cast `dtype` to `int`. If the only thing that was wrong was the type we will fix it for you. What do you think about it?
Yep, better idea
I'll try to make it happen with next release :) 

Resolving patch:
diff --git a/supervision/detection/tools/polygon_zone.py b/supervision/detection/tools/polygon_zone.py
--- a/supervision/detection/tools/polygon_zone.py
+++ b/supervision/detection/tools/polygon_zone.py
@@ -17,7 +17,7 @@ class PolygonZone:
     A class for defining a polygon-shaped zone within a frame for detecting objects.
 
     Attributes:
-        polygon (np.ndarray): A numpy array defining the polygon vertices
+        polygon (np.ndarray): A polygon represented by a numpy array of shape `(N, 2)`, containing the `x`, `y` coordinates of the points.
         frame_resolution_wh (Tuple[int, int]): The frame resolution (width, height)
         triggering_position (Position): The position within the bounding box that triggers the zone (default: Position.BOTTOM_CENTER)
         current_count (int): The current count of detected objects within the zone
@@ -30,7 +30,7 @@ def __init__(
         frame_resolution_wh: Tuple[int, int],
         triggering_position: Position = Position.BOTTOM_CENTER,
     ):
-        self.polygon = polygon
+        self.polygon = polygon.astype(int)
         self.frame_resolution_wh = frame_resolution_wh
         self.triggering_position = triggering_position
         self.current_count = 0


Test patch:
Repository: roboflow/supervision

Issue:
Developement - version issue
### Search before asking

- [X] I have searched the Supervision [issues](https://github.com/roboflow/supervision/issues) and found no similar bug report.


### Bug

I have not installed `supervision` but running directly for developement purpose.

But I got an following error when I import supervision code:

```
    raise PackageNotFoundError(name)
importlib.metadata.PackageNotFoundError: supervision
```

After a quick investigation, it is found that `__init__.py` of `supervision` where version information used. It is creating an issue. If I comment this line and the bug is gone.

@onuralpszr Can you take a look?


I think it should be ignorable, if valid version is not found then use `development` version. Though, I do not have concret idea, how to tackle it.





### Environment

_No response_

### Minimal Reproducible Example

_No response_

### Additional

_No response_

### Are you willing to submit a PR?

- [X] Yes I'd like to help by submitting a PR!


Discussion:
@onuralpszr we could really use your assistance here 🙏🏻 

Resolving patch:
diff --git a/supervision/__init__.py b/supervision/__init__.py
--- a/supervision/__init__.py
+++ b/supervision/__init__.py
@@ -1,6 +1,10 @@
 import importlib.metadata as importlib_metadata
 
-__version__ = importlib_metadata.version(__package__)
+try:
+    # This will read version from pyproject.toml
+    __version__ = importlib_metadata.version(__package__ or __name__)
+except importlib_metadata.PackageNotFoundError:
+    __version__ = "development"
 
 
 from supervision.classification.core import Classifications


Test patch:
Repository: roboflow/supervision

Issue:
feature/FpsMonitor
### Search before asking

- [X] I have searched the Supervision [issues](https://github.com/roboflow/supervision/issues) and found no similar feature requests.


### Description

Computer vision practice often requires to monitor the speed of the algorithm to check the performance. The latency performance is measure with the help of `FPS-Monitor` which measures the processing time for defined steps.

### Use case

- Latency measurement for general case.

### Additional

```python
class FPSMonitor:	
	
	def __init__(self):
		self.last_tick = None
		self.fps = 0
	
	def tick(self)->None:
		pass
		
	def get_average_fps(self) -> float
		return self.fps
```

### Are you willing to submit a PR?

- [X] Yes I'd like to help by submitting a PR!


Discussion:
@SkalskiP Please mark it for `version-0.14.0` but it is already ready for review.

Resolving patch:
diff --git a/supervision/__init__.py b/supervision/__init__.py
--- a/supervision/__init__.py
+++ b/supervision/__init__.py
@@ -41,6 +41,7 @@
 from supervision.metrics.detection import ConfusionMatrix, MeanAveragePrecision
 from supervision.tracker.byte_tracker.core import ByteTrack
 from supervision.utils.file import list_files_with_extensions
+from supervision.utils.fps import FpsMonitor
 from supervision.utils.image import ImageSink, crop_image
 from supervision.utils.notebook import plot_image, plot_images_grid
 from supervision.utils.video import (
diff --git a/supervision/utils/fps.py b/supervision/utils/fps.py
new file mode 100644
--- /dev/null
+++ b/supervision/utils/fps.py
@@ -0,0 +1,34 @@
+import time
+from collections import deque
+
+
+class FpsMonitor:
+    def __init__(self, sample_size: int = 30):
+        """
+        Initialize class to measure Frame per second for latency benchmark.
+        Args:
+            sample_size (int): Maximum observation to measure latency benchmark
+        Examples:
+            ```python
+            >>> import supervision as sv
+
+            >>> fps_monitor = sv.FpsMonitor()
+            >>> while True:
+            ...      (...)
+            ...      fps_monitor.tick()
+            ...      fps = fps_monitor()
+            ```
+        """
+        self.all_timestamps = deque(maxlen=sample_size)
+
+    def __call__(self) -> float:
+        if not self.all_timestamps:
+            return 0.0
+        taken_time = self.all_timestamps[-1] - self.all_timestamps[0]
+        return (len(self.all_timestamps)) / taken_time if taken_time != 0 else 0.0
+
+    def tick(self) -> None:
+        self.all_timestamps.append(time.monotonic())
+
+    def reset(self) -> None:
+        self.all_timestamps.clear()


Test patch:
Repository: roboflow/supervision

Issue:
Fix `sv.ByteTrack.tracker_id` return value when `sv.Detections` is empty
### Bug

When `sv.Detections` is empty (`len(detections) == 0`) `sv.ByteTrack` returns `tracker_id` equal `None`. Correct that behavior, make it more consistent, and return `np.array([], dtype=int)`.

### Fix

Add `else` statement here: https://github.com/roboflow/supervision/blob/89c1b63979d43f8ed651a9701ca8333034d0bc07/supervision/tracker/byte_tracker/core.py#L239


Discussion:
Working on it

Resolving patch:
diff --git a/supervision/tracker/byte_tracker/core.py b/supervision/tracker/byte_tracker/core.py
--- a/supervision/tracker/byte_tracker/core.py
+++ b/supervision/tracker/byte_tracker/core.py
@@ -249,6 +249,8 @@ def update_with_detections(self, detections: Detections) -> Detections:
             detections.confidence = np.array(
                 [t.score for t in tracks], dtype=np.float32
             )
+        else:
+            detections.tracker_id = np.array([], dtype=int)
 
         return detections
 


Test patch:
Repository: roboflow/supervision

Issue:
[LineZone] - flip in/out line crossing directions
## Description

Between `supervision-0.17.0` and `supervision-0.18.0`, releases in/out of the direction of the crossing were accidentally changed. Given that `LineZone` is one of the oldest features we have we do not want to make life difficult for users and want to restore the previous behavior. The change made in this [PR](https://github.com/roboflow/supervision/pull/735), most likely in this [line](https://github.com/roboflow/supervision/blob/0ccb0b85adee4202f5fe96834a374a057bbbd9da/supervision/detection/line_counter.py#L140), is responsible for the change in behavior.

https://github.com/roboflow/supervision/blob/0ccb0b85adee4202f5fe96834a374a057bbbd9da/supervision/detection/line_counter.py#L140

### Minimal Reproducible Example

You can easily confirm the crossing direction change between `supervision-0.17.0` and `supervision-0.18.0` releases using this [notebook](https://colab.research.google.com/github/roboflow-ai/notebooks/blob/main/notebooks/how-to-track-and-count-vehicles-with-yolov8-and-supervison.ipynb). Here are example results.

__supervision-0.17.0__

https://github.com/roboflow/supervision/assets/26109316/32e0f95c-9204-4703-ab25-c2255a597720

__supervision-0.18.0__

https://github.com/roboflow/supervision/assets/26109316/af6db77e-24f8-4338-9925-3c80afe178f8

### Additional

- Note: Please share a Google Colab with minimal code to test the new feature. We know it's additional work, but it will speed up the review process. The reviewer must test each change. Setting up a local environment to do this is time-consuming. Please ensure that Google Colab can be accessed without any issues (make it public). Thank you! 🙏🏻 


Discussion:
Hi @harshaneo17 👋🏻 Thanks for your interest in supervision. I just confirmed. You are right. Let me update the task title and description.
Hi, I am interesting with this task. Can you assign me
@Kadermiyanyedi you already have experience with linezones it should be easy for you handle it, good luck 👍 😉 
Good luck, @Kadermiyanyedi 🤞🏻 Most likely, you need to change `>` into `<`. But that's just my guess. 

Resolving patch:
diff --git a/supervision/detection/line_counter.py b/supervision/detection/line_counter.py
--- a/supervision/detection/line_counter.py
+++ b/supervision/detection/line_counter.py
@@ -137,7 +137,7 @@ def trigger(self, detections: Detections) -> Tuple[np.ndarray, np.ndarray]:
                 continue
 
             triggers = [
-                self.vector.cross_product(point=anchor) > 0 for anchor in box_anchors
+                self.vector.cross_product(point=anchor) < 0 for anchor in box_anchors
             ]
 
             if len(set(triggers)) == 2:


Test patch:
Repository: roboflow/supervision

Issue:
[Detections] - `from_inference` should include `'class_name'` key in `Detections.data` even if result is empty
### Bug

[`from_inference`](https://github.com/roboflow/supervision/blob/0ccb0b85adee4202f5fe96834a374a057bbbd9da/supervision/detection/core.py#L448) should include `'class_name'` key in `Detections.data` even if `roboflow` inference result is empty.

### Environment

- Latest version of supervision
- macOS

### Minimal Reproducible Example

```python
import cv2
import roboflow
import numpy as np
import supervision as sv
from tempfile import NamedTemporaryFile

roboflow.login()

rf = roboflow.Roboflow()
project = rf.workspace().project("people-detection-general")
model = project.version(5).model

x = np.zeros((1000, 1000, 3), dtype=np.uint8)
with NamedTemporaryFile(suffix=".jpeg") as f:
    cv2.imwrite(f.name, x)
    result = model.predict(f.name).json()

    detections = sv.Detections.from_inference(result)
    print(detections)
```

Here is the result:

```
Detections(xyxy=array([], shape=(0, 4), dtype=float32), mask=None, confidence=array([], dtype=float32), class_id=array([], dtype=int64), tracker_id=None, data={})
```

Note `data={}` and it should be `data={'class_name': []}`.

### Additional

- Note: Please share a Google Colab with minimal code to test the new feature. We know it's additional work, but it will speed up the review process. The reviewer must test each change. Setting up a local environment to do this is time-consuming. Please ensure that Google Colab can be accessed without any issues (make it public). Thank you! 🙏🏻 


Discussion:
Hello, I am interesting the task can you assign me ?
@Kadermiyanyedi  task yours good luck 

Resolving patch:
diff --git a/supervision/detection/core.py b/supervision/detection/core.py
--- a/supervision/detection/core.py
+++ b/supervision/detection/core.py
@@ -487,7 +487,9 @@ def from_inference(cls, roboflow_result: Union[dict, Any]) -> Detections:
         )
 
         if np.asarray(xyxy).shape[0] == 0:
-            return cls.empty()
+            empty_detection = cls.empty()
+            empty_detection.data = {CLASS_NAME_DATA_FIELD: np.empty(0)}
+            return empty_detection
 
         return cls(
             xyxy=xyxy,


Test patch:
Repository: roboflow/supervision

Issue:
Loading OBB detection from ultralytics fails
### Search before asking

- [X] I have searched the Supervision [issues](https://github.com/roboflow/supervision/issues) and found no similar bug report.


### Bug

When passing in the results from ultralytics yolov8 OBB model to from_ultralytics it will fail and give the following: 

AttributeError: 'NoneType' object has no attribute 'cls'

due to:

class_id = ultralytics_results.boxes.cls.cpu().numpy().astype(int)

 

### Environment

- Supervision 0.20.0
- Ultralytics 8.2.18

### Minimal Reproducible Example


```python
from typing import List

import cv2
from ultralytics import YOLO
from supervision import Detections
from ultralytics.engine.results import Results
from supervision.tracker.byte_tracker.core import ByteTrack

yolo = YOLO("yolov8n-obb.pt", task="obb")

tracker = ByteTrack(track_activation_threshold=0.8,
                    minimum_matching_threshold=0.8,
                    lost_track_buffer=30,
                    frame_rate=30)

video_feed = cv2.VideoCapture("test_rgb.mp4")

status, frame = video_feed.read()

while status:
    results: List[Results] = yolo(frame,
                                  show=False,
                                  verbose=False,
                                  imgsz=[736, 1280])
    result: Results = results[0]

    inference_detections: Detections = Detections.from_ultralytics(result)
    detections = tracker.update_with_detections(inference_detections)

    for (xyxy, mask, conf, class_id, tracker_id, data) in detections:
        print("xyxy:", xyxy)

    status, frame = video_feed.read()
```

### Additional

_No response_

### Are you willing to submit a PR?

- [ ] Yes I'd like to help by submitting a PR!


Discussion:
Hi @dbestPacksol 👋🏻 Thanks for your interest in `supervision`. Could you install `ultralytics==8.1` and check if the code works or fails? 
@SkalskiP Even when running on ultralytics==8.1 it still has the same failure
Same problem here and I have tried both version.
Hi, @onuralpszr. 👋🏻 Is there any chance you could take a look? If you are busy, no problem we can try to debug ourselves. 
@SkalskiP I took it, let me debug quickly and open PR based on that (If needed)
@onuralpszr thanks a lot for the help 🙏🏻 

Resolving patch:
diff --git a/supervision/detection/core.py b/supervision/detection/core.py
--- a/supervision/detection/core.py
+++ b/supervision/detection/core.py
@@ -240,7 +240,7 @@ def from_ultralytics(cls, ultralytics_results) -> Detections:
             Class names values can be accessed using `detections["class_name"]`.
         """  # noqa: E501 // docs
 
-        if "obb" in ultralytics_results and ultralytics_results.obb is not None:
+        if hasattr(ultralytics_results, "obb") and ultralytics_results.obb is not None:
             class_id = ultralytics_results.obb.cls.cpu().numpy().astype(int)
             class_names = np.array([ultralytics_results.names[i] for i in class_id])
             oriented_box_coordinates = ultralytics_results.obb.xyxyxyxy.cpu().numpy()


Test patch:
Repository: codespell-project/codespell

Issue:
Any change of adding this to PyPi?
Our project installs tools via pip to keep things nice and clean and virtualenv friendly--It would be great if codespell was added to Pypi.



Discussion:
yes, it'd be nice. Can you send a patch for proper integration?

Sure, I'll give it a shot.

On Tue, Jul 28, 2015 at 2:39 PM Lucas De Marchi notifications@github.com
wrote:

> yes, it'd be nice. Can you send a patch for proper integration?
> 
> —
> Reply to this email directly or view it on GitHub
> https://github.com/lucasdemarchi/codespell/issues/38#issuecomment-125708336
> .


Resolving patch:
diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py
--- a/codespell_lib/_codespell.py
+++ b/codespell_lib/_codespell.py
@@ -30,7 +30,7 @@
 USAGE = """
 \t%prog [OPTIONS] [file1 file2 ... fileN]
 """
-VERSION = '1.9'
+VERSION = '1.9.0'
 
 misspellings = {}
 exclude_lines = set()
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -20,7 +20,7 @@
 URL = 'https://github.com/lucasdemarchi/codespell/'
 LICENSE = 'GPL v2'
 DOWNLOAD_URL = 'https://github.com/lucasdemarchi/codespell/'
-with open('README.md', 'r') as f:
+with open('README.rst', 'r') as f:
     LONG_DESCRIPTION = f.read()
 
 if __name__ == "__main__":


Test patch:
Repository: codespell-project/codespell

Issue:
codespell.py does nothng if [fileN] is not specified
Previously running `codespell` without file parameter starts the check. Now `codespell.py` does nothing. The behavior should stay the same as before - if file/dir argument is not specefied then current directory should be used as a default parameter.



Discussion:
Can you open a PR to fix it?

Although I'm not sure if that is really the "principle of least surprise" behavior, if it was the default before, I suppose it should stay that way. WDYT @lucasdemarchi?

We could display the help message or maintain the previous behavior. Doing nothing is the worst. @anatol do you think it would be ok to change the default behavior, requiring an argument? Otherwise let's just go back and do what we were doing.

I prefer previous implementation. When I call codespell I expect it checks files in the current context (current directory).

Looking at the `codespell_lib/_codespell.py` it still does the same

```
    (o, args) = parser.parse_args(list(args))

    if not args:
        args.append('.')
```

It should append current directory by default. Maybe recent refactoring changed argument count here?

`args` in the code snippet above became `['/usr/bin/codespell.py']`. Before it was an empty array if called like `codespell`. Eric, please fix it.


Resolving patch:
diff --git a/bin/codespell.py b/bin/codespell.py
--- a/bin/codespell.py
+++ b/bin/codespell.py
@@ -4,4 +4,4 @@
 
 if __name__ == '__main__':
     import codespell_lib
-    sys.exit(codespell_lib.main(*sys.argv))
+    sys.exit(codespell_lib.main(*sys.argv[1:]))


Test patch:
diff --git a/codespell_lib/tests/test_basic.py b/codespell_lib/tests/test_basic.py
--- a/codespell_lib/tests/test_basic.py
+++ b/codespell_lib/tests/test_basic.py
@@ -5,6 +5,7 @@
 import contextlib
 import os
 import os.path as op
+import subprocess
 import sys
 import tempfile
 import warnings
@@ -14,6 +15,23 @@
 from codespell_lib import main
 
 
+def run_codespell(args=(), cwd=None):
+    """Helper to run codespell"""
+    return subprocess.Popen(
+        ['codespell.py'] + list(args), cwd=cwd,
+        stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait()
+
+
+def test_command():
+    """Test running codespell.py"""
+    # With no arguments does "."
+    with TemporaryDirectory() as d:
+        assert_equal(run_codespell(cwd=d), 0)
+        with open(op.join(d, 'bad.txt'), 'w') as f:
+            f.write('abandonned\nAbandonned\nABANDONNED\nAbAnDoNnEd')
+        assert_equal(run_codespell(cwd=d), 4)
+
+
 def test_basic():
     """Test some basic functionality"""
     assert_equal(main('_does_not_exist_'), 0)