code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def _extract_subscope_rules(rules) -> list[Rule]:
"""
process the given sequence of rules.
for each one, extract any embedded subscope rules into their own rule.
process these recursively.
then return a list of the refactored rules.
note: this operation mutates the rules... |
process the given sequence of rules.
for each one, extract any embedded subscope rules into their own rule.
process these recursively.
then return a list of the refactored rules.
note: this operation mutates the rules passed in - they may now have `match` statements
fo... | _extract_subscope_rules | python | mandiant/capa | capa/rules/__init__.py | https://github.com/mandiant/capa/blob/master/capa/rules/__init__.py | Apache-2.0 |
def filter_rules_by_meta(self, tag: str) -> "RuleSet":
"""
return new rule set with rules filtered based on all meta field values, adds all dependency rules
apply tag-based rule filter assuming that all required rules are loaded
can be used to specify selected rules vs. providing a rules... |
return new rule set with rules filtered based on all meta field values, adds all dependency rules
apply tag-based rule filter assuming that all required rules are loaded
can be used to specify selected rules vs. providing a rules child directory where capa cannot resolve
dependencies fr... | filter_rules_by_meta | python | mandiant/capa | capa/rules/__init__.py | https://github.com/mandiant/capa/blob/master/capa/rules/__init__.py | Apache-2.0 |
def _match(self, scope: Scope, features: FeatureSet, addr: Address) -> tuple[FeatureSet, ceng.MatchResults]:
"""
Match rules from this ruleset at the given scope against the given features.
This routine should act just like `capa.engine.match`, except that it may be more performant.
It ... |
Match rules from this ruleset at the given scope against the given features.
This routine should act just like `capa.engine.match`, except that it may be more performant.
It uses its knowledge of all the rules to evaluate a minimal set of candidate rules for the given features.
| _match | python | mandiant/capa | capa/rules/__init__.py | https://github.com/mandiant/capa/blob/master/capa/rules/__init__.py | Apache-2.0 |
def match(
self, scope: Scope, features: FeatureSet, addr: Address, paranoid=False
) -> tuple[FeatureSet, ceng.MatchResults]:
"""
Match rules from this ruleset at the given scope against the given features.
This wrapper around _match exists so that we can assert it matches precisely... |
Match rules from this ruleset at the given scope against the given features.
This wrapper around _match exists so that we can assert it matches precisely
the same as `capa.engine.match`, just faster.
This matcher does not handle some edge cases:
- top level NOT statements
... | match | python | mandiant/capa | capa/rules/__init__.py | https://github.com/mandiant/capa/blob/master/capa/rules/__init__.py | Apache-2.0 |
def collect_rule_file_paths(rule_paths: list[Path]) -> list[Path]:
"""
collect all rule file paths, including those in subdirectories.
"""
rule_file_paths = []
for rule_path in rule_paths:
if not rule_path.exists():
raise IOError(f"rule path {rule_path} does not exist or cannot b... |
collect all rule file paths, including those in subdirectories.
| collect_rule_file_paths | python | mandiant/capa | capa/rules/__init__.py | https://github.com/mandiant/capa/blob/master/capa/rules/__init__.py | Apache-2.0 |
def get_rules(
rule_paths: list[RulePath],
cache_dir=None,
on_load_rule: Callable[[RulePath, int, int], None] = on_load_rule_default,
enable_cache: bool = True,
) -> RuleSet:
"""
args:
rule_paths: list of paths to rules files or directories containing rules files
cache_dir: directory... |
args:
rule_paths: list of paths to rules files or directories containing rules files
cache_dir: directory to use for caching rules, or will use the default detected cache directory if None
on_load_rule: callback to invoke before a rule is loaded, use for progress or cancellation
enable_cach... | get_rules | python | mandiant/capa | capa/rules/__init__.py | https://github.com/mandiant/capa/blob/master/capa/rules/__init__.py | Apache-2.0 |
def get_capa_results(args):
"""
run capa against the file at the given path, using the given rules.
args is a tuple, containing:
rules, signatures, format, backend, os, input_file
as provided via the CLI arguments.
args is a tuple because i'm not quite sure how to unpack multiple arguments u... |
run capa against the file at the given path, using the given rules.
args is a tuple, containing:
rules, signatures, format, backend, os, input_file
as provided via the CLI arguments.
args is a tuple because i'm not quite sure how to unpack multiple arguments using `map`.
returns an dict wi... | get_capa_results | python | mandiant/capa | scripts/bulk-process.py | https://github.com/mandiant/capa/blob/master/scripts/bulk-process.py | Apache-2.0 |
def render_capabilities(doc: rd.ResultDocument, result):
"""
example::
{'CAPABILITY': {'accept command line arguments': 'host-interaction/cli',
'allocate thread local storage (2 matches)': 'host-interaction/process',
'check for time delay via GetTickCount': 'anti-analysis... |
example::
{'CAPABILITY': {'accept command line arguments': 'host-interaction/cli',
'allocate thread local storage (2 matches)': 'host-interaction/process',
'check for time delay via GetTickCount': 'anti-analysis/anti-debugging/debugger-detection',
'check if p... | render_capabilities | python | mandiant/capa | scripts/capa-as-library.py | https://github.com/mandiant/capa/blob/master/scripts/capa-as-library.py | Apache-2.0 |
def render_attack(doc, result):
"""
example::
{'ATT&CK': {'COLLECTION': ['Input Capture::Keylogging [T1056.001]'],
'DEFENSE EVASION': ['Obfuscated Files or Information [T1027]',
'Virtualization/Sandbox Evasion::System Checks '
'... |
example::
{'ATT&CK': {'COLLECTION': ['Input Capture::Keylogging [T1056.001]'],
'DEFENSE EVASION': ['Obfuscated Files or Information [T1027]',
'Virtualization/Sandbox Evasion::System Checks '
'[T1497.001]'],
'DISCOVERY':... | render_attack | python | mandiant/capa | scripts/capa-as-library.py | https://github.com/mandiant/capa/blob/master/scripts/capa-as-library.py | Apache-2.0 |
def render_mbc(doc, result):
"""
example::
{'MBC': {'ANTI-BEHAVIORAL ANALYSIS': ['Debugger Detection::Timing/Delay Check '
'GetTickCount [B0001.032]',
'Emulator Detection [B0004]',
'Virtual ... |
example::
{'MBC': {'ANTI-BEHAVIORAL ANALYSIS': ['Debugger Detection::Timing/Delay Check '
'GetTickCount [B0001.032]',
'Emulator Detection [B0004]',
'Virtual Machine Detection::Instruction '
... | render_mbc | python | mandiant/capa | scripts/capa-as-library.py | https://github.com/mandiant/capa/blob/master/scripts/capa-as-library.py | Apache-2.0 |
def _populate_artifact(sarif_log: dict, meta_data: dict) -> None:
"""
@param sarif_log: dict - sarif data structure including runs
@param meta_data: dict - Capa meta output
@returns None, updates sarif_log via side-effects
"""
sample = meta_data["sample"]
artifact = {
"location": {"u... |
@param sarif_log: dict - sarif data structure including runs
@param meta_data: dict - Capa meta output
@returns None, updates sarif_log via side-effects
| _populate_artifact | python | mandiant/capa | scripts/capa2sarif.py | https://github.com/mandiant/capa/blob/master/scripts/capa2sarif.py | Apache-2.0 |
def _add_filler_optional(capa_result: dict, sarif_log: dict) -> None:
"""Update sarif file with just enough fields to pass radare tests"""
base_address = capa_result["meta"]["analysis"]["base_address"]["value"]
# Assume there is only one run, and one binary artifact
artifact = sarif_log["runs"][0]["arti... | Update sarif file with just enough fields to pass radare tests | _add_filler_optional | python | mandiant/capa | scripts/capa2sarif.py | https://github.com/mandiant/capa/blob/master/scripts/capa2sarif.py | Apache-2.0 |
def get_features(rule_path: str) -> set[Feature]:
"""
Extracts all features from a given rule file.
Args:
rule_path (str): The path to the rule file to extract features from.
Returns:
set: A set of all feature statements contained within the rule file.
"""
with Path(rule_path).... |
Extracts all features from a given rule file.
Args:
rule_path (str): The path to the rule file to extract features from.
Returns:
set: A set of all feature statements contained within the rule file.
| get_features | python | mandiant/capa | scripts/detect_duplicate_features.py | https://github.com/mandiant/capa/blob/master/scripts/detect_duplicate_features.py | Apache-2.0 |
def append_func_cmt(bv, va, cmt):
"""
add the given comment to the given function,
if it doesn't already exist.
"""
func = bv.get_function_at(va)
if not func:
raise ValueError("not a function")
if cmt in func.comment:
return
func.comment = func.comment + "\n" + cmt |
add the given comment to the given function,
if it doesn't already exist.
| append_func_cmt | python | mandiant/capa | scripts/import-to-bn.py | https://github.com/mandiant/capa/blob/master/scripts/import-to-bn.py | Apache-2.0 |
def _is_static_scope_compatible(parent: Rule, child: Rule) -> bool:
"""
A child rule's scope is compatible if it is equal to or lower than the parent scope.
"""
if parent.scopes.static and not child.scopes.static and child.is_subscope_rule():
# this is ok: the child isn't a ... |
A child rule's scope is compatible if it is equal to or lower than the parent scope.
| _is_static_scope_compatible | python | mandiant/capa | scripts/lint.py | https://github.com/mandiant/capa/blob/master/scripts/lint.py | Apache-2.0 |
def lint(ctx: Context):
"""
Returns: dict[string, tuple(int, int)]
- # lints failed
- # lints warned
"""
ret = {}
source_rules = [rule for rule in ctx.rules.rules.values() if not rule.is_subscope_rule()]
n_rules: int = len(source_rules)
with capa.helpers.CapaProgressBar(transie... |
Returns: dict[string, tuple(int, int)]
- # lints failed
- # lints warned
| lint | python | mandiant/capa | scripts/lint.py | https://github.com/mandiant/capa/blob/master/scripts/lint.py | Apache-2.0 |
def collect_samples(samples_path: Path) -> dict[str, Path]:
"""
recurse through the given path, collecting all file paths, indexed by their content sha256, md5, and filename.
"""
samples = {}
for path in samples_path.rglob("*"):
if path.suffix in [".viv", ".idb", ".i64", ".frz", ".fnames"]:
... |
recurse through the given path, collecting all file paths, indexed by their content sha256, md5, and filename.
| collect_samples | python | mandiant/capa | scripts/lint.py | https://github.com/mandiant/capa/blob/master/scripts/lint.py | Apache-2.0 |
def __init__(self):
"""Download and store in memory the STIX data on instantiation."""
if self.kill_chain_name == "":
raise ValueError(f"Kill chain name not specified in class {self.__class__.__name__}")
if self.url == "":
raise ValueError(f"URL not specified in class {s... | Download and store in memory the STIX data on instantiation. | __init__ | python | mandiant/capa | scripts/setup-linter-dependencies.py | https://github.com/mandiant/capa/blob/master/scripts/setup-linter-dependencies.py | Apache-2.0 |
def _remove_deprecated_objects(stix_objects) -> list[AttackPattern]:
"""Remove any revoked or deprecated objects from queries made to the data source."""
return list(
filter(
lambda x: x.get("x_mitre_deprecated", False) is False and x.get("revoked", False) is False,
... | Remove any revoked or deprecated objects from queries made to the data source. | _remove_deprecated_objects | python | mandiant/capa | scripts/setup-linter-dependencies.py | https://github.com/mandiant/capa/blob/master/scripts/setup-linter-dependencies.py | Apache-2.0 |
def _get_parent_technique_from_subtechnique(self, technique: AttackPattern) -> AttackPattern:
"""Get parent technique of a sub technique using the technique ID TXXXX.YYY"""
sub_id = technique["external_references"][0]["external_id"].split(".")[0]
parent_technique = self._remove_deprecated_object... | Get parent technique of a sub technique using the technique ID TXXXX.YYY | _get_parent_technique_from_subtechnique | python | mandiant/capa | scripts/setup-linter-dependencies.py | https://github.com/mandiant/capa/blob/master/scripts/setup-linter-dependencies.py | Apache-2.0 |
def run(self) -> dict[str, dict[str, str]]:
"""Iterate over every technique over every tactic. If the technique is a sub technique, then
we also search for the parent technique name.
"""
logging.info("Starting extraction...")
data: dict[str, dict[str, str]] = {}
for tacti... | Iterate over every technique over every tactic. If the technique is a sub technique, then
we also search for the parent technique name.
| run | python | mandiant/capa | scripts/setup-linter-dependencies.py | https://github.com/mandiant/capa/blob/master/scripts/setup-linter-dependencies.py | Apache-2.0 |
def _get_tactics(self) -> list[dict]:
"""Override _get_tactics to edit the tactic name for Micro-objective"""
tactics = super()._get_tactics()
# We don't want the Micro-objective string inside objective names
for tactic in tactics:
tactic["name"] = tactic["name"].replace(" Mi... | Override _get_tactics to edit the tactic name for Micro-objective | _get_tactics | python | mandiant/capa | scripts/setup-linter-dependencies.py | https://github.com/mandiant/capa/blob/master/scripts/setup-linter-dependencies.py | Apache-2.0 |
def render_matches_by_function(doc: rd.ResultDocument):
"""
like:
function at 0x1000321a with 33 features:
- get hostname
- initialize Winsock library
function at 0x10003286 with 63 features:
- create thread
- terminate thread
function at 0x100034... |
like:
function at 0x1000321a with 33 features:
- get hostname
- initialize Winsock library
function at 0x10003286 with 63 features:
- create thread
- terminate thread
function at 0x10003415 with 116 features:
- write file
- send d... | render_matches_by_function | python | mandiant/capa | scripts/show-capabilities-by-function.py | https://github.com/mandiant/capa/blob/master/scripts/show-capabilities-by-function.py | Apache-2.0 |
def xfail(condition, reason=None):
"""
context manager that wraps a block that is expected to fail in some cases.
when it does fail (and is expected), then mark this as pytest.xfail.
if its unexpected, raise an exception, so the test fails.
example::
# this test:
# - passes on Lin... |
context manager that wraps a block that is expected to fail in some cases.
when it does fail (and is expected), then mark this as pytest.xfail.
if its unexpected, raise an exception, so the test fails.
example::
# this test:
# - passes on Linux if foo() works
# - fails on L... | xfail | python | mandiant/capa | tests/fixtures.py | https://github.com/mandiant/capa/blob/master/tests/fixtures.py | Apache-2.0 |
def fixup_viv(path: Path, extractor):
"""
vivisect fixups to overcome differences between backends
"""
if "3b13b" in path.name:
# vivisect only recognizes calling thunk function at 0x10001573
extractor.vw.makeFunction(0x10006860)
if "294b8d" in path.name:
# see vivisect/#561
... |
vivisect fixups to overcome differences between backends
| fixup_viv | python | mandiant/capa | tests/fixtures.py | https://github.com/mandiant/capa/blob/master/tests/fixtures.py | Apache-2.0 |
def get_sample_md5_by_name(name):
"""used by IDA tests to ensure the correct IDB is loaded"""
if name == "mimikatz":
return "5f66b82558ca92e54e77f216ef4c066c"
elif name == "kernel32":
return "e80758cf485db142fca1ee03a34ead05"
elif name == "kernel32-64":
return "a8565440629ac87f6f... | used by IDA tests to ensure the correct IDB is loaded | get_sample_md5_by_name | python | mandiant/capa | tests/fixtures.py | https://github.com/mandiant/capa/blob/master/tests/fixtures.py | Apache-2.0 |
def parametrize(params, values, **kwargs):
"""
extend `pytest.mark.parametrize` to pretty-print features.
by default, it renders objects as an opaque value.
ref: https://docs.pytest.org/en/2.9.0/example/parametrize.html#different-options-for-test-ids
rendered ID might look something like:
mi... |
extend `pytest.mark.parametrize` to pretty-print features.
by default, it renders objects as an opaque value.
ref: https://docs.pytest.org/en/2.9.0/example/parametrize.html#different-options-for-test-ids
rendered ID might look something like:
mimikatz-function=0x403BAC-api(CryptDestroyKey)-True... | parametrize | python | mandiant/capa | tests/fixtures.py | https://github.com/mandiant/capa/blob/master/tests/fixtures.py | Apache-2.0 |
def standardize_posix_str(psx_str):
"""fixture test passes the PosixPath to the test data
params: psx_str - PosixPath() to the test data
return: string that matches test-id sample name
"""
if "Practical Malware Analysis Lab" in str(psx_str):
# <PosixPath>/'Practical Malware Analysis Lab 16... | fixture test passes the PosixPath to the test data
params: psx_str - PosixPath() to the test data
return: string that matches test-id sample name
| standardize_posix_str | python | mandiant/capa | tests/test_ghidra_features.py | https://github.com/mandiant/capa/blob/master/tests/test_ghidra_features.py | Apache-2.0 |
def check_input_file(wanted):
"""check that test is running on the loaded sample
params: wanted - PosixPath() passed from test arg
"""
import capa.ghidra.helpers as ghidra_helpers
found = ghidra_helpers.get_file_md5()
sample_name = standardize_posix_str(wanted)
if not found.startswith(fi... | check that test is running on the loaded sample
params: wanted - PosixPath() passed from test arg
| check_input_file | python | mandiant/capa | tests/test_ghidra_features.py | https://github.com/mandiant/capa/blob/master/tests/test_ghidra_features.py | Apache-2.0 |
def nocollect(f):
"don't collect the decorated function as a pytest test"
f.__test__ = False
return f | don't collect the decorated function as a pytest test | nocollect | python | mandiant/capa | tests/test_ida_features.py | https://github.com/mandiant/capa/blob/master/tests/test_ida_features.py | Apache-2.0 |
def match(rules, features, va, scope=Scope.FUNCTION):
"""
use all matching algorithms and verify that they compute the same result.
then, return those results to the caller so they can make their asserts.
"""
features1, matches1 = capa.engine.match(rules, features, va)
ruleset = capa.rules.Rule... |
use all matching algorithms and verify that they compute the same result.
then, return those results to the caller so they can make their asserts.
| match | python | mandiant/capa | tests/test_match.py | https://github.com/mandiant/capa/blob/master/tests/test_match.py | Apache-2.0 |
def test_match_adds_matched_rule_feature():
"""show that using `match` adds a feature for matched rules."""
rule = textwrap.dedent(
"""
rule:
meta:
name: test rule
scopes:
static: function
dynamic: process
... | show that using `match` adds a feature for matched rules. | test_match_adds_matched_rule_feature | python | mandiant/capa | tests/test_match.py | https://github.com/mandiant/capa/blob/master/tests/test_match.py | Apache-2.0 |
def get_labels_length(file_path):
"""
Return labels and their count in a file.
Args:
file_path (str): The path to the file containing the labels.
Returns:
list: labels; int: The number of labels in the file.
"""
with open(file_path, encoding = "UTF-8") as f:
tokens = [t... |
Return labels and their count in a file.
Args:
file_path (str): The path to the file containing the labels.
Returns:
list: labels; int: The number of labels in the file.
| get_labels_length | python | FutureUniant/Tailor | app/src/algorithm/base/emoti_voice/config/config.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/emoti_voice/config/config.py | Apache-2.0 |
def griffin_lim(magnitudes, stft_fn, n_iters=30):
"""
PARAMS
------
magnitudes: spectrogram magnitudes
stft_fn: STFT class with transform (STFT) and inverse (ISTFT) methods
"""
angles = np.angle(np.exp(2j * np.pi * np.random.rand(*magnitudes.size())))
angles = angles.astype(np.float32)
... |
PARAMS
------
magnitudes: spectrogram magnitudes
stft_fn: STFT class with transform (STFT) and inverse (ISTFT) methods
| griffin_lim | python | FutureUniant/Tailor | app/src/algorithm/base/emoti_voice/models/prompt_tts_modified/feats.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/emoti_voice/models/prompt_tts_modified/feats.py | Apache-2.0 |
def flat_accuracy(preds, labels):
"""
Function to calculate the accuracy of our predictions vs labels
"""
pred_flat = np.argmax(preds, axis=1).flatten()
labels_flat = labels.flatten()
return np.sum(pred_flat == labels_flat) / len(labels_flat) |
Function to calculate the accuracy of our predictions vs labels
| flat_accuracy | python | FutureUniant/Tailor | app/src/algorithm/base/emoti_voice/models/prompt_tts_modified/simbert.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/emoti_voice/models/prompt_tts_modified/simbert.py | Apache-2.0 |
def forward(self, xs: torch.Tensor, x_masks: torch.Tensor = None) -> torch.Tensor:
"""Calculate forward propagation.
Args:
xs (Tensor): Batch of input sequences (B, Tmax, idim).
x_masks (ByteTensor): Batch of masks indicating padded part (B, Tmax).
Returns:
... | Calculate forward propagation.
Args:
xs (Tensor): Batch of input sequences (B, Tmax, idim).
x_masks (ByteTensor): Batch of masks indicating padded part (B, Tmax).
Returns:
Tensor: Batch of predicted sequences (B, Tmax, 1).
| forward | python | FutureUniant/Tailor | app/src/algorithm/base/emoti_voice/models/prompt_tts_modified/modules/variance.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/emoti_voice/models/prompt_tts_modified/modules/variance.py | Apache-2.0 |
def kp2gaussian(kp, spatial_size, kp_variance):
"""
Transform a keypoint into gaussian like representation
"""
mean = kp['value']
coordinate_grid = make_coordinate_grid(spatial_size, mean.type())
number_of_leading_dimensions = len(mean.shape) - 1
shape = (1,) * number_of_leading_dimensions ... |
Transform a keypoint into gaussian like representation
| kp2gaussian | python | FutureUniant/Tailor | app/src/algorithm/base/sadtalker/src/facerender/modules/util.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sadtalker/src/facerender/modules/util.py | Apache-2.0 |
def __init__(
self,
model: SAM2Base,
points_per_side: Optional[int] = 32,
points_per_batch: int = 64,
pred_iou_thresh: float = 0.8,
stability_score_thresh: float = 0.95,
stability_score_offset: float = 1.0,
mask_threshold: float = 0.0,
box_nms_thre... |
Using a SAM 2 model, generates masks for the entire image.
Generates a grid of point prompts over the image, then filters
low quality and duplicate masks. The default settings are chosen
for SAM 2 with a HieraL backbone.
Arguments:
model (Sam): The SAM 2 model to use ... | __init__ | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/automatic_mask_generator.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/automatic_mask_generator.py | Apache-2.0 |
def from_pretrained(cls, model_id: str, **kwargs) -> "SAM2AutomaticMaskGenerator":
"""
Load a pretrained model from the Hugging Face hub.
Arguments:
model_id (str): The Hugging Face repository ID.
**kwargs: Additional arguments to pass to the model constructor.
Retu... |
Load a pretrained model from the Hugging Face hub.
Arguments:
model_id (str): The Hugging Face repository ID.
**kwargs: Additional arguments to pass to the model constructor.
Returns:
(SAM2AutomaticMaskGenerator): The loaded model.
| from_pretrained | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/automatic_mask_generator.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/automatic_mask_generator.py | Apache-2.0 |
def generate(self, image: np.ndarray) -> List[Dict[str, Any]]:
"""
Generates masks for the given image.
Arguments:
image (np.ndarray): The image to generate masks for, in HWC uint8 format.
Returns:
list(dict(str, any)): A list over records for masks. Each record is... |
Generates masks for the given image.
Arguments:
image (np.ndarray): The image to generate masks for, in HWC uint8 format.
Returns:
list(dict(str, any)): A list over records for masks. Each record is
a dict containing the following keys:
segment... | generate | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/automatic_mask_generator.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/automatic_mask_generator.py | Apache-2.0 |
def postprocess_small_regions(
mask_data: MaskData, min_area: int, nms_thresh: float
) -> MaskData:
"""
Removes small disconnected regions and holes in masks, then reruns
box NMS to remove any new duplicates.
Edits mask_data in place.
Requires open-cv as a dependenc... |
Removes small disconnected regions and holes in masks, then reruns
box NMS to remove any new duplicates.
Edits mask_data in place.
Requires open-cv as a dependency.
| postprocess_small_regions | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/automatic_mask_generator.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/automatic_mask_generator.py | Apache-2.0 |
def __init__(
self,
sam_model: SAM2Base,
mask_threshold=0.0,
max_hole_area=0.0,
max_sprinkle_area=0.0,
**kwargs,
) -> None:
"""
Uses SAM-2 to calculate the image embedding for an image, and then
allow repeated, efficient mask prediction given p... |
Uses SAM-2 to calculate the image embedding for an image, and then
allow repeated, efficient mask prediction given prompts.
Arguments:
sam_model (Sam-2): The model to use for mask prediction.
mask_threshold (float): The threshold to use when converting mask logits
... | __init__ | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | Apache-2.0 |
def from_pretrained(cls, model_id: str, **kwargs) -> "SAM2ImagePredictor":
"""
Load a pretrained model from the Hugging Face hub.
Arguments:
model_id (str): The Hugging Face repository ID.
**kwargs: Additional arguments to pass to the model constructor.
Returns:
... |
Load a pretrained model from the Hugging Face hub.
Arguments:
model_id (str): The Hugging Face repository ID.
**kwargs: Additional arguments to pass to the model constructor.
Returns:
(SAM2ImagePredictor): The loaded model.
| from_pretrained | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | Apache-2.0 |
def set_image(
self,
image: Union[np.ndarray, Image],
) -> None:
"""
Calculates the image embeddings for the provided image, allowing
masks to be predicted with the 'predict' method.
Arguments:
image (np.ndarray or PIL Image): The input image to embed in RG... |
Calculates the image embeddings for the provided image, allowing
masks to be predicted with the 'predict' method.
Arguments:
image (np.ndarray or PIL Image): The input image to embed in RGB format. The image should be in HWC format if np.ndarray, or WHC format if PIL Image
... | set_image | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | Apache-2.0 |
def set_image_batch(
self,
image_list: List[Union[np.ndarray]],
) -> None:
"""
Calculates the image embeddings for the provided image batch, allowing
masks to be predicted with the 'predict_batch' method.
Arguments:
image_list (List[np.ndarray]): The input ... |
Calculates the image embeddings for the provided image batch, allowing
masks to be predicted with the 'predict_batch' method.
Arguments:
image_list (List[np.ndarray]): The input images to embed in RGB format. The image should be in HWC format if np.ndarray
with pixel values... | set_image_batch | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | Apache-2.0 |
def predict_batch(
self,
point_coords_batch: List[np.ndarray] = None,
point_labels_batch: List[np.ndarray] = None,
box_batch: List[np.ndarray] = None,
mask_input_batch: List[np.ndarray] = None,
multimask_output: bool = True,
return_logits: bool = False,
no... | This function is very similar to predict(...), however it is used for batched mode, when the model is expected to generate predictions on multiple images.
It returns a tuple of lists of masks, ious, and low_res_masks_logits.
| predict_batch | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | Apache-2.0 |
def predict(
self,
point_coords: Optional[np.ndarray] = None,
point_labels: Optional[np.ndarray] = None,
box: Optional[np.ndarray] = None,
mask_input: Optional[np.ndarray] = None,
multimask_output: bool = True,
return_logits: bool = False,
normalize_coords... |
Predict masks for the given input prompts, using the currently set image.
Arguments:
point_coords (np.ndarray or None): A Nx2 array of point prompts to the
model. Each point is in (X,Y) in pixels.
point_labels (np.ndarray or None): A length N array of labels for the
... | predict | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | Apache-2.0 |
def _predict(
self,
point_coords: Optional[torch.Tensor],
point_labels: Optional[torch.Tensor],
boxes: Optional[torch.Tensor] = None,
mask_input: Optional[torch.Tensor] = None,
multimask_output: bool = True,
return_logits: bool = False,
img_idx: int = -1,
... |
Predict masks for the given input prompts, using the currently set image.
Input prompts are batched torch tensors and are expected to already be
transformed to the input frame using SAM2Transforms.
Arguments:
point_coords (torch.Tensor or None): A BxNx2 array of point prompts... | _predict | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | Apache-2.0 |
def get_image_embedding(self) -> torch.Tensor:
"""
Returns the image embeddings for the currently set image, with
shape 1xCxHxW, where C is the embedding dimension and (H,W) are
the embedding spatial dimension of SAM (typically C=256, H=W=64).
"""
if not self._is_image_se... |
Returns the image embeddings for the currently set image, with
shape 1xCxHxW, where C is the embedding dimension and (H,W) are
the embedding spatial dimension of SAM (typically C=256, H=W=64).
| get_image_embedding | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | Apache-2.0 |
def reset_predictor(self) -> None:
"""
Resets the image embeddings and other state variables.
"""
self._is_image_set = False
self._features = None
self._orig_hw = None
self._is_batch = False |
Resets the image embeddings and other state variables.
| reset_predictor | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_image_predictor.py | Apache-2.0 |
def from_pretrained(cls, model_id: str, **kwargs) -> "SAM2VideoPredictor":
"""
Load a pretrained model from the Hugging Face hub.
Arguments:
model_id (str): The Hugging Face repository ID.
**kwargs: Additional arguments to pass to the model constructor.
Returns:
... |
Load a pretrained model from the Hugging Face hub.
Arguments:
model_id (str): The Hugging Face repository ID.
**kwargs: Additional arguments to pass to the model constructor.
Returns:
(SAM2VideoPredictor): The loaded model.
| from_pretrained | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def _obj_id_to_idx(self, inference_state, obj_id):
"""Map client-side object id to model-side object index."""
obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None)
if obj_idx is not None:
return obj_idx
# This is a new object id not sent to the server before. We only... | Map client-side object id to model-side object index. | _obj_id_to_idx | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def _get_orig_video_res_output(self, inference_state, any_res_masks):
"""
Resize the object scores to the original video resolution (video_res_masks)
and apply non-overlapping constraints for final output.
"""
device = inference_state["device"]
video_H = inference_state["... |
Resize the object scores to the original video resolution (video_res_masks)
and apply non-overlapping constraints for final output.
| _get_orig_video_res_output | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def _consolidate_temp_output_across_obj(
self,
inference_state,
frame_idx,
is_cond,
run_mem_encoder,
consolidate_at_video_res=False,
):
"""
Consolidate the per-object temporary outputs in `temp_output_dict_per_obj` on
a frame into a single outp... |
Consolidate the per-object temporary outputs in `temp_output_dict_per_obj` on
a frame into a single output for all objects, including
1) fill any missing objects either from `output_dict_per_obj` (if they exist in
`output_dict_per_obj` for this frame) or leave them as placeholder val... | _consolidate_temp_output_across_obj | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def _get_empty_mask_ptr(self, inference_state, frame_idx):
"""Get a dummy object pointer based on an empty mask on the current frame."""
# A dummy (empty) mask with a single object
batch_size = 1
mask_inputs = torch.zeros(
(batch_size, 1, self.image_size, self.image_size),
... | Get a dummy object pointer based on an empty mask on the current frame. | _get_empty_mask_ptr | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def propagate_in_video_preflight(self, inference_state):
"""Prepare inference_state and consolidate temporary outputs before tracking."""
# Tracking has started and we don't allow adding new objects until session is reset.
inference_state["tracking_has_started"] = True
batch_size = self.... | Prepare inference_state and consolidate temporary outputs before tracking. | propagate_in_video_preflight | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def propagate_in_video(
self,
inference_state,
start_frame_idx=None,
max_frame_num_to_track=None,
reverse=False,
):
"""Propagate the input points across frames to track in the entire video."""
self.propagate_in_video_preflight(inference_state)
output_... | Propagate the input points across frames to track in the entire video. | propagate_in_video | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def _add_output_per_object(
self, inference_state, frame_idx, current_out, storage_key
):
"""
Split a multi-object output into per-object output slices and add them into
`output_dict_per_obj`. The resulting slices share the same tensor storage.
"""
maskmem_features = ... |
Split a multi-object output into per-object output slices and add them into
`output_dict_per_obj`. The resulting slices share the same tensor storage.
| _add_output_per_object | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def reset_state(self, inference_state):
"""Remove all input points or mask in all frames throughout the video."""
self._reset_tracking_results(inference_state)
# Remove all object ids
inference_state["obj_id_to_idx"].clear()
inference_state["obj_idx_to_id"].clear()
infere... | Remove all input points or mask in all frames throughout the video. | reset_state | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def _reset_tracking_results(self, inference_state):
"""Reset all tracking inputs and results across the videos."""
for v in inference_state["point_inputs_per_obj"].values():
v.clear()
for v in inference_state["mask_inputs_per_obj"].values():
v.clear()
for v in inf... | Reset all tracking inputs and results across the videos. | _reset_tracking_results | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def _get_image_feature(self, inference_state, frame_idx, batch_size):
"""Compute the image features on a given frame."""
# Look up in the cache first
image, backbone_out = inference_state["cached_features"].get(
frame_idx, (None, None)
)
if backbone_out is None:
... | Compute the image features on a given frame. | _get_image_feature | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def _run_single_frame_inference(
self,
inference_state,
output_dict,
frame_idx,
batch_size,
is_init_cond_frame,
point_inputs,
mask_inputs,
reverse,
run_mem_encoder,
prev_sam_mask_logits=None,
):
"""Run tracking on a sing... | Run tracking on a single frame based on current inputs and previous memory. | _run_single_frame_inference | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def _run_memory_encoder(
self, inference_state, frame_idx, batch_size, high_res_masks, is_mask_from_pts
):
"""
Run the memory encoder on `high_res_masks`. This is usually after applying
non-overlapping constraints to object scores. Since their scores changed, their
memory als... |
Run the memory encoder on `high_res_masks`. This is usually after applying
non-overlapping constraints to object scores. Since their scores changed, their
memory also need to be computed again with the memory encoder.
| _run_memory_encoder | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def _get_maskmem_pos_enc(self, inference_state, current_out):
"""
`maskmem_pos_enc` is the same across frames and objects, so we cache it as
a constant in the inference session to reduce session storage size.
"""
model_constants = inference_state["constants"]
# "out_maskm... |
`maskmem_pos_enc` is the same across frames and objects, so we cache it as
a constant in the inference session to reduce session storage size.
| _get_maskmem_pos_enc | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def _clear_non_cond_mem_around_input(self, inference_state, frame_idx):
"""
Remove the non-conditioning memory around the input frame. When users provide
correction clicks, the surrounding frames' non-conditioning memories can still
contain outdated object appearance information and coul... |
Remove the non-conditioning memory around the input frame. When users provide
correction clicks, the surrounding frames' non-conditioning memories can still
contain outdated object appearance information and could confuse the model.
This method clears those non-conditioning memories su... | _clear_non_cond_mem_around_input | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/sam2_video_predictor.py | Apache-2.0 |
def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:
"""Positionally encode points that are normalized to [0,1]."""
# assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
coords = 2 * coords - 1
coords = coords @ self.positional_encoding_gaussian_matrix
... | Positionally encode points that are normalized to [0,1]. | _pe_encoding | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/position_encoding.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/position_encoding.py | Apache-2.0 |
def forward(self, size: Tuple[int, int]) -> torch.Tensor:
"""Generate positional encoding for a grid of the specified size."""
h, w = size
device: Any = self.positional_encoding_gaussian_matrix.device
grid = torch.ones((h, w), device=device, dtype=torch.float32)
y_embed = grid.cu... | Generate positional encoding for a grid of the specified size. | forward | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/position_encoding.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/position_encoding.py | Apache-2.0 |
def forward_with_coords(
self, coords_input: torch.Tensor, image_size: Tuple[int, int]
) -> torch.Tensor:
"""Positionally encode points that are not normalized to [0,1]."""
coords = coords_input.clone()
coords[:, :, 0] = coords[:, :, 0] / image_size[1]
coords[:, :, 1] = coord... | Positionally encode points that are not normalized to [0,1]. | forward_with_coords | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/position_encoding.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/position_encoding.py | Apache-2.0 |
def _build_sam_heads(self):
"""Build SAM-style prompt encoder and mask decoder."""
self.sam_prompt_embed_dim = self.hidden_dim
self.sam_image_embedding_size = self.image_size // self.backbone_stride
# build PromptEncoder and MaskDecoder from SAM
# (their hyperparameters like `ma... | Build SAM-style prompt encoder and mask decoder. | _build_sam_heads | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | Apache-2.0 |
def _forward_sam_heads(
self,
backbone_features,
point_inputs=None,
mask_inputs=None,
high_res_features=None,
multimask_output=False,
):
"""
Forward SAM prompt encoders and mask heads.
Inputs:
- backbone_features: image features of [B,... |
Forward SAM prompt encoders and mask heads.
Inputs:
- backbone_features: image features of [B, C, H, W] shape
- point_inputs: a dictionary with "point_coords" and "point_labels", where
1) "point_coords" has [B, P, 2] shape and float32 dtype and contains the
absol... | _forward_sam_heads | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | Apache-2.0 |
def _use_mask_as_output(self, backbone_features, high_res_features, mask_inputs):
"""
Directly turn binary `mask_inputs` into a output mask logits without using SAM.
(same input and output shapes as in _forward_sam_heads above).
"""
# Use -10/+10 as logits for neg/pos pixels (ver... |
Directly turn binary `mask_inputs` into a output mask logits without using SAM.
(same input and output shapes as in _forward_sam_heads above).
| _use_mask_as_output | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | Apache-2.0 |
def forward_image(self, img_batch: torch.Tensor):
"""Get the image feature on the input batch."""
backbone_out = self.image_encoder(img_batch)
if self.use_high_res_features_in_sam:
# precompute projected level 0 and level 1 features in SAM decoder
# to avoid running it ag... | Get the image feature on the input batch. | forward_image | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | Apache-2.0 |
def _prepare_memory_conditioned_features(
self,
frame_idx,
is_init_cond_frame,
current_vision_feats,
current_vision_pos_embeds,
feat_sizes,
output_dict,
num_frames,
track_in_reverse=False, # tracking in reverse time order (for demo usage)
):
... | Fuse the current frame's visual feature map with previous memory. | _prepare_memory_conditioned_features | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | Apache-2.0 |
def _encode_new_memory(
self,
current_vision_feats,
feat_sizes,
pred_masks_high_res,
is_mask_from_pts,
):
"""Encode the current image and its prediction into a memory feature."""
B = current_vision_feats[-1].size(1) # batch size on this frame
C = self... | Encode the current image and its prediction into a memory feature. | _encode_new_memory | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | Apache-2.0 |
def _use_multimask(self, is_init_cond_frame, point_inputs):
"""Whether to use multimask output in the SAM head."""
num_pts = 0 if point_inputs is None else point_inputs["point_labels"].size(1)
multimask_output = (
self.multimask_output_in_sam
and (is_init_cond_frame or se... | Whether to use multimask output in the SAM head. | _use_multimask | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | Apache-2.0 |
def _apply_non_overlapping_constraints(self, pred_masks):
"""
Apply non-overlapping constraints to the object scores in pred_masks. Here we
keep only the highest scoring object at each spatial location in pred_masks.
"""
batch_size = pred_masks.size(0)
if batch_size == 1:... |
Apply non-overlapping constraints to the object scores in pred_masks. Here we
keep only the highest scoring object at each spatial location in pred_masks.
| _apply_non_overlapping_constraints | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam2_base.py | Apache-2.0 |
def select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num):
"""
Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs`
that are temporally closest to the current frame at `frame_idx`. Here, we take
- a) the closest conditioning frame before `frame_idx` (if... |
Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs`
that are temporally closest to the current frame at `frame_idx`. Here, we take
- a) the closest conditioning frame before `frame_idx` (if any);
- b) the closest conditioning frame after `frame_idx` (if any);
- c) any ot... | select_closest_cond_frames | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam2_utils.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam2_utils.py | Apache-2.0 |
def get_1d_sine_pe(pos_inds, dim, temperature=10000):
"""
Get 1D sine positional embedding as in the original Transformer paper.
"""
pe_dim = dim // 2
dim_t = torch.arange(pe_dim, dtype=torch.float32, device=pos_inds.device)
dim_t = temperature ** (2 * (dim_t // 2) / pe_dim)
pos_embed = pos... |
Get 1D sine positional embedding as in the original Transformer paper.
| get_1d_sine_pe | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam2_utils.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam2_utils.py | Apache-2.0 |
def get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == "relu":
return F.relu
if activation == "gelu":
return F.gelu
if activation == "glu":
return F.glu
raise RuntimeError(f"activation should be relu/gelu, not {activation}.") | Return an activation function given a string | get_activation_fn | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam2_utils.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam2_utils.py | Apache-2.0 |
def __init__(
self,
position_encoding: nn.Module,
d_model: int,
backbone_channel_list: List[int],
kernel_size: int = 1,
stride: int = 1,
padding: int = 0,
fpn_interp_model: str = "bilinear",
fuse_type: str = "sum",
fpn_top_down_levels: Opti... | Initialize the neck
:param trunk: the backbone
:param position_encoding: the positional encoding to use
:param d_model: the dimension of the model
:param neck_norm: the normalization to use
| __init__ | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/backbones/image_encoder.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/backbones/image_encoder.py | Apache-2.0 |
def window_partition(x, window_size):
"""
Partition into non-overlapping windows with padding if needed.
Args:
x (tensor): input tokens with [B, H, W, C].
window_size (int): window size.
Returns:
windows: windows after partition with [B * num_windows, window_size, window_size, C]... |
Partition into non-overlapping windows with padding if needed.
Args:
x (tensor): input tokens with [B, H, W, C].
window_size (int): window size.
Returns:
windows: windows after partition with [B * num_windows, window_size, window_size, C].
(Hp, Wp): padded height and width b... | window_partition | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/backbones/utils.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/backbones/utils.py | Apache-2.0 |
def window_unpartition(windows, window_size, pad_hw, hw):
"""
Window unpartition into original sequences and removing padding.
Args:
x (tensor): input tokens with [B * num_windows, window_size, window_size, C].
window_size (int): window size.
pad_hw (Tuple): padded height and width (... |
Window unpartition into original sequences and removing padding.
Args:
x (tensor): input tokens with [B * num_windows, window_size, window_size, C].
window_size (int): window size.
pad_hw (Tuple): padded height and width (Hp, Wp).
hw (Tuple): original height and width (H, W) bef... | window_unpartition | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/backbones/utils.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/backbones/utils.py | Apache-2.0 |
def __init__(
self,
kernel_size: Tuple[int, ...] = (7, 7),
stride: Tuple[int, ...] = (4, 4),
padding: Tuple[int, ...] = (3, 3),
in_chans: int = 3,
embed_dim: int = 768,
):
"""
Args:
kernel_size (Tuple): kernel size of the projection layer.
... |
Args:
kernel_size (Tuple): kernel size of the projection layer.
stride (Tuple): stride of the projection layer.
padding (Tuple): padding size of the projection layer.
in_chans (int): Number of input image channels.
embed_dim (int): embed_dim (int): P... | __init__ | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/backbones/utils.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/backbones/utils.py | Apache-2.0 |
def __init__(
self,
*,
transformer_dim: int,
transformer: nn.Module,
num_multimask_outputs: int = 3,
activation: Type[nn.Module] = nn.GELU,
iou_head_depth: int = 3,
iou_head_hidden_dim: int = 256,
use_high_res_features: bool = False,
iou_pr... |
Predicts masks given an image and prompt embeddings, using a
transformer architecture.
Arguments:
transformer_dim (int): the channel dimension of the transformer
transformer (nn.Module): the transformer used to predict masks
num_multimask_outputs (int): the number... | __init__ | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam/mask_decoder.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam/mask_decoder.py | Apache-2.0 |
def forward(
self,
image_embeddings: torch.Tensor,
image_pe: torch.Tensor,
sparse_prompt_embeddings: torch.Tensor,
dense_prompt_embeddings: torch.Tensor,
multimask_output: bool,
repeat_image: bool,
high_res_features: Optional[List[torch.Tensor]] = None,
... |
Predict masks given image and prompt embeddings.
Arguments:
image_embeddings (torch.Tensor): the embeddings from the image encoder
image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
sparse_prompt_embeddings (torch.Tensor): the embeddings of th... | forward | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam/mask_decoder.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam/mask_decoder.py | Apache-2.0 |
def predict_masks(
self,
image_embeddings: torch.Tensor,
image_pe: torch.Tensor,
sparse_prompt_embeddings: torch.Tensor,
dense_prompt_embeddings: torch.Tensor,
repeat_image: bool,
high_res_features: Optional[List[torch.Tensor]] = None,
) -> Tuple[torch.Tensor,... | Predicts masks. See 'forward' for more details. | predict_masks | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam/mask_decoder.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam/mask_decoder.py | Apache-2.0 |
def _get_stability_scores(self, mask_logits):
"""
Compute stability scores of the mask logits based on the IoU between upper and
lower thresholds, similar to https://github.com/fairinternal/onevision/pull/568.
"""
mask_logits = mask_logits.flatten(-2)
stability_delta = se... |
Compute stability scores of the mask logits based on the IoU between upper and
lower thresholds, similar to https://github.com/fairinternal/onevision/pull/568.
| _get_stability_scores | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam/mask_decoder.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam/mask_decoder.py | Apache-2.0 |
def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores):
"""
When outputting a single mask, if the stability score from the current single-mask
output (based on output token 0) falls below a threshold, we instead select from
multi-mask outputs (based on output token 1... |
When outputting a single mask, if the stability score from the current single-mask
output (based on output token 0) falls below a threshold, we instead select from
multi-mask outputs (based on output token 1~3) the mask with the highest predicted
IoU score. This is intended to ensure a ... | _dynamic_multimask_via_stability | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam/mask_decoder.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam/mask_decoder.py | Apache-2.0 |
def __init__(
self,
embed_dim: int,
image_embedding_size: Tuple[int, int],
input_image_size: Tuple[int, int],
mask_in_chans: int,
activation: Type[nn.Module] = nn.GELU,
) -> None:
"""
Encodes prompts for input to SAM's mask decoder.
Arguments:... |
Encodes prompts for input to SAM's mask decoder.
Arguments:
embed_dim (int): The prompts' embedding dimension
image_embedding_size (tuple(int, int)): The spatial size of the
image embedding, as (H, W).
input_image_size (int): The padded size of the image as in... | __init__ | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam/prompt_encoder.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam/prompt_encoder.py | Apache-2.0 |
def _get_batch_size(
self,
points: Optional[Tuple[torch.Tensor, torch.Tensor]],
boxes: Optional[torch.Tensor],
masks: Optional[torch.Tensor],
) -> int:
"""
Gets the batch size of the output given the batch size of the input prompts.
"""
if points is no... |
Gets the batch size of the output given the batch size of the input prompts.
| _get_batch_size | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam/prompt_encoder.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam/prompt_encoder.py | Apache-2.0 |
def forward(
self,
points: Optional[Tuple[torch.Tensor, torch.Tensor]],
boxes: Optional[torch.Tensor],
masks: Optional[torch.Tensor],
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Embeds different types of prompts, returning both sparse and dense
embeddings.
... |
Embeds different types of prompts, returning both sparse and dense
embeddings.
Arguments:
points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates
and labels to embed.
boxes (torch.Tensor or none): boxes to embed
masks (torch.Tensor or non... | forward | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam/prompt_encoder.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam/prompt_encoder.py | Apache-2.0 |
def sdp_kernel_context(dropout_p):
"""
Get the context for the attention scaled dot-product kernel. We use Flash Attention
by default, but fall back to all available kernels if Flash Attention fails.
"""
if ALLOW_ALL_KERNELS:
return contextlib.nullcontext()
return torch.backends.cuda.sd... |
Get the context for the attention scaled dot-product kernel. We use Flash Attention
by default, but fall back to all available kernels if Flash Attention fails.
| sdp_kernel_context | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam/transformer.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam/transformer.py | Apache-2.0 |
def __init__(
self,
depth: int,
embedding_dim: int,
num_heads: int,
mlp_dim: int,
activation: Type[nn.Module] = nn.ReLU,
attention_downsample_rate: int = 2,
) -> None:
"""
A transformer decoder that attends to an input image using
queri... |
A transformer decoder that attends to an input image using
queries whose positional embedding is supplied.
Args:
depth (int): number of layers in the transformer
embedding_dim (int): the channel dimension for the input embeddings
num_heads (int): the number of hea... | __init__ | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam/transformer.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam/transformer.py | Apache-2.0 |
def forward(
self,
image_embedding: Tensor,
image_pe: Tensor,
point_embedding: Tensor,
) -> Tuple[Tensor, Tensor]:
"""
Args:
image_embedding (torch.Tensor): image to attend to. Should be shape
B x embedding_dim x h x w for any h and w.
... |
Args:
image_embedding (torch.Tensor): image to attend to. Should be shape
B x embedding_dim x h x w for any h and w.
image_pe (torch.Tensor): the positional encoding to add to the image. Must
have the same shape as image_embedding.
point_embedding (torch.Te... | forward | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam/transformer.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam/transformer.py | Apache-2.0 |
def __init__(
self,
embedding_dim: int,
num_heads: int,
mlp_dim: int = 2048,
activation: Type[nn.Module] = nn.ReLU,
attention_downsample_rate: int = 2,
skip_first_layer_pe: bool = False,
) -> None:
"""
A transformer block with four layers: (1) ... |
A transformer block with four layers: (1) self-attention of sparse
inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp
block on sparse inputs, and (4) cross attention of dense inputs to sparse
inputs.
Arguments:
embedding_dim (int): the channel dimen... | __init__ | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/modeling/sam/transformer.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/modeling/sam/transformer.py | Apache-2.0 |
def is_box_near_crop_edge(
boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0
) -> torch.Tensor:
"""Filter masks at the edge of a crop, but not at the edge of the original image."""
crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)
orig_box... | Filter masks at the edge of a crop, but not at the edge of the original image. | is_box_near_crop_edge | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/utils/amg.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/amg.py | Apache-2.0 |
def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]:
"""
Encodes masks to an uncompressed RLE, in the format expected by
pycoco tools.
"""
# Put in fortran order and flatten h,w
b, h, w = tensor.shape
tensor = tensor.permute(0, 2, 1).flatten(1)
# Compute change indices... |
Encodes masks to an uncompressed RLE, in the format expected by
pycoco tools.
| mask_to_rle_pytorch | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/utils/amg.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/amg.py | Apache-2.0 |
def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:
"""Compute a binary mask from an uncompressed RLE."""
h, w = rle["size"]
mask = np.empty(h * w, dtype=bool)
idx = 0
parity = False
for count in rle["counts"]:
mask[idx : idx + count] = parity
idx += count
parity ^= True
... | Compute a binary mask from an uncompressed RLE. | rle_to_mask | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/utils/amg.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/amg.py | Apache-2.0 |
def calculate_stability_score(
masks: torch.Tensor, mask_threshold: float, threshold_offset: float
) -> torch.Tensor:
"""
Computes the stability score for a batch of masks. The stability
score is the IoU between the binary masks obtained by thresholding
the predicted mask logits at high and low valu... |
Computes the stability score for a batch of masks. The stability
score is the IoU between the binary masks obtained by thresholding
the predicted mask logits at high and low values.
| calculate_stability_score | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/utils/amg.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/amg.py | Apache-2.0 |
def build_point_grid(n_per_side: int) -> np.ndarray:
"""Generates a 2D grid of points evenly spaced in [0,1]x[0,1]."""
offset = 1 / (2 * n_per_side)
points_one_side = np.linspace(offset, 1 - offset, n_per_side)
points_x = np.tile(points_one_side[None, :], (n_per_side, 1))
points_y = np.tile(points_o... | Generates a 2D grid of points evenly spaced in [0,1]x[0,1]. | build_point_grid | python | FutureUniant/Tailor | app/src/algorithm/base/sam2/sam2/utils/amg.py | https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/amg.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.