generated from roboflow/template-python
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
initial commit adding support for from_lmm
and specifically for Pal…
#1221
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
a2195aa
initial commit adding support for `from_lmm` and specifically for Pal…
SkalskiP 36a73f7
clean up
SkalskiP 7eb9182
fix(pre_commit): 🎨 auto format pre-commit hooks
pre-commit-ci[bot] b81c5e8
update to allow multi-word class names
SkalskiP b59d17f
Merge remote-tracking branch 'origin/from_paligemma_support' into fro…
SkalskiP bf43d65
fix(pre_commit): 🎨 auto format pre-commit hooks
pre-commit-ci[bot] 07c36c6
make linter happy
SkalskiP 0115ef8
small fix when `mask` is empty
SkalskiP ad2220b
fix(pre_commit): 🎨 auto format pre-commit hooks
pre-commit-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
import re | ||
from enum import Enum | ||
from typing import Any, Dict, List, Optional, Tuple, Union | ||
|
||
import numpy as np | ||
|
||
|
||
class LMM(Enum): | ||
PALIGEMMA = "paligemma" | ||
|
||
|
||
REQUIRED_ARGUMENTS: Dict[LMM, List[str]] = {LMM.PALIGEMMA: ["resolution_wh"]} | ||
|
||
ALLOWED_ARGUMENTS: Dict[LMM, List[str]] = {LMM.PALIGEMMA: ["resolution_wh", "classes"]} | ||
|
||
|
||
def validate_lmm_and_kwargs(lmm: Union[LMM, str], kwargs: Dict[str, Any]) -> LMM: | ||
if isinstance(lmm, str): | ||
try: | ||
lmm = LMM(lmm.lower()) | ||
except ValueError: | ||
raise ValueError( | ||
f"Invalid lmm value: {lmm}. Must be one of {[e.value for e in LMM]}" | ||
) | ||
|
||
required_args = REQUIRED_ARGUMENTS.get(lmm, []) | ||
for arg in required_args: | ||
if arg not in kwargs: | ||
raise ValueError(f"Missing required argument: {arg}") | ||
|
||
allowed_args = ALLOWED_ARGUMENTS.get(lmm, []) | ||
for arg in kwargs: | ||
if arg not in allowed_args: | ||
raise ValueError(f"Argument {arg} is not allowed for {lmm.name}") | ||
|
||
return lmm | ||
|
||
|
||
def from_paligemma( | ||
result: str, resolution_wh: Tuple[int, int], classes: Optional[List[str]] = None | ||
) -> Tuple[np.ndarray, Optional[np.ndarray], np.ndarray]: | ||
w, h = resolution_wh | ||
pattern = re.compile( | ||
r"(?<!<loc\d{4}>)<loc(\d{4})><loc(\d{4})><loc(\d{4})><loc(\d{4})> ([\w\s]+)" | ||
) | ||
matches = pattern.findall(result) | ||
matches = np.array(matches) if matches else np.empty((0, 5)) | ||
|
||
xyxy, class_name = matches[:, [1, 0, 3, 2]], matches[:, 4] | ||
xyxy = xyxy.astype(int) / 1024 * np.array([w, h, w, h]) | ||
class_name = np.char.strip(class_name.astype(str)) | ||
class_id = None | ||
|
||
if classes is not None: | ||
mask = np.array([name in classes for name in class_name]).astype(bool) | ||
xyxy, class_name = xyxy[mask], class_name[mask] | ||
class_id = np.array([classes.index(name) for name in class_name]) | ||
|
||
return xyxy, class_id, class_name |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
from typing import List, Optional, Tuple | ||
|
||
import numpy as np | ||
import pytest | ||
|
||
from supervision.detection.lmm import from_paligemma | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"result, resolution_wh, classes, expected_results", | ||
[ | ||
( | ||
"", | ||
(1000, 1000), | ||
None, | ||
(np.empty((0, 4)), None, np.empty(0).astype(str)), | ||
), # empty response | ||
( | ||
"", | ||
(1000, 1000), | ||
["cat", "dog"], | ||
(np.empty((0, 4)), None, np.empty(0).astype(str)), | ||
), # empty response with classes | ||
( | ||
"\n", | ||
(1000, 1000), | ||
None, | ||
(np.empty((0, 4)), None, np.empty(0).astype(str)), | ||
), # new line response | ||
( | ||
"the quick brown fox jumps over the lazy dog.", | ||
(1000, 1000), | ||
None, | ||
(np.empty((0, 4)), None, np.empty(0).astype(str)), | ||
), # response with no location | ||
( | ||
"<loc0256><loc0768><loc0768> cat", | ||
(1000, 1000), | ||
None, | ||
(np.empty((0, 4)), None, np.empty(0).astype(str)), | ||
), # response with missing location | ||
( | ||
"<loc0256><loc0256><loc0768><loc0768><loc0768> cat", | ||
(1000, 1000), | ||
None, | ||
(np.empty((0, 4)), None, np.empty(0).astype(str)), | ||
), # response with extra location | ||
( | ||
"<loc0256><loc0256><loc0768><loc0768>", | ||
(1000, 1000), | ||
None, | ||
(np.empty((0, 4)), None, np.empty(0).astype(str)), | ||
), # response with no class | ||
( | ||
"<loc0256><loc0256><loc0768><loc0768> catt", | ||
(1000, 1000), | ||
["cat", "dog"], | ||
(np.empty((0, 4)), np.empty(0), np.empty(0).astype(str)), | ||
), # response with invalid class | ||
( | ||
"<loc0256><loc0256><loc0768><loc0768> cat", | ||
(1000, 1000), | ||
None, | ||
( | ||
np.array([[250.0, 250.0, 750.0, 750.0]]), | ||
None, | ||
np.array(["cat"]).astype(str), | ||
), | ||
), # correct response; no classes | ||
( | ||
"<loc0256><loc0256><loc0768><loc0768> black cat", | ||
(1000, 1000), | ||
None, | ||
( | ||
np.array([[250.0, 250.0, 750.0, 750.0]]), | ||
None, | ||
np.array(["black cat"]).astype(np.dtype("U")), | ||
), | ||
), # correct response; no classes | ||
( | ||
"<loc0256><loc0256><loc0768><loc0768> cat ;", | ||
(1000, 1000), | ||
["cat", "dog"], | ||
( | ||
np.array([[250.0, 250.0, 750.0, 750.0]]), | ||
np.array([0]), | ||
np.array(["cat"]).astype(str), | ||
), | ||
), # correct response; with classes | ||
( | ||
"<loc0256><loc0256><loc0768><loc0768> cat ; <loc0256><loc0256><loc0768><loc0768> dog", # noqa: E501 | ||
(1000, 1000), | ||
["cat", "dog"], | ||
( | ||
np.array([[250.0, 250.0, 750.0, 750.0], [250.0, 250.0, 750.0, 750.0]]), | ||
np.array([0, 1]), | ||
np.array(["cat", "dog"]).astype(np.dtype("U")), | ||
), | ||
), # correct response; with classes | ||
( | ||
"<loc0256><loc0256><loc0768><loc0768> cat ; <loc0256><loc0256><loc0768> cat", # noqa: E501 | ||
(1000, 1000), | ||
["cat", "dog"], | ||
( | ||
np.array([[250.0, 250.0, 750.0, 750.0]]), | ||
np.array([0]), | ||
np.array(["cat"]).astype(str), | ||
), | ||
), # partially correct response; with classes | ||
( | ||
"<loc0256><loc0256><loc0768><loc0768> cat ; <loc0256><loc0256><loc0768><loc0768><loc0768> cat", # noqa: E501 | ||
(1000, 1000), | ||
["cat", "dog"], | ||
( | ||
np.array([[250.0, 250.0, 750.0, 750.0]]), | ||
np.array([0]), | ||
np.array(["cat"]).astype(str), | ||
), | ||
), # partially correct response; with classes | ||
], | ||
) | ||
def test_from_paligemma( | ||
result: str, | ||
resolution_wh: Tuple[int, int], | ||
classes: Optional[List[str]], | ||
expected_results: Tuple[np.ndarray, Optional[np.ndarray], np.ndarray], | ||
) -> None: | ||
result = from_paligemma(result=result, resolution_wh=resolution_wh, classes=classes) | ||
np.testing.assert_array_equal(result[0], expected_results[0]) | ||
np.testing.assert_array_equal(result[1], expected_results[1]) | ||
np.testing.assert_array_equal(result[2], expected_results[2]) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this would be also useful for models like KOSMOS-2 so best to make it very general (this is a trend with VLMs these days) https://huggingface.co/docs/transformers/en/model_doc/kosmos-2#transformers.Kosmos2ForConditionalGeneration.forward.example
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So what I want to do is one
from_lmm
function, providing separate dedicated parsers for each model. :)