repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/atest/TestCases/custom_reader/custom_reader.py
atest/TestCases/custom_reader/custom_reader.py
# Copyright 2018- René Rohner # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from DataDriver.AbstractReaderClass import ( AbstractReaderClass, ) # inherit class from AbstractReaderClass from DataDriver.ReaderConfig import ( TestCaseData, ) # return list of TestCaseData to DataDriver class custom_reader(AbstractReaderClass): # This method will be called from DataDriver to get the TestCaseData list. def get_data_from_source(self): test_data = [] for i in range(int(self.min), int(self.max)): # Dummy code to just generate some data args = { "${var_1}": i, "${var_2}": str(i), } # args is a dictionary. Variable name is the key, value is value. test_data.append( TestCaseData(f"test {i}", args, ["tag"]) ) # add a TestCaseData object to the list of tests. return test_data # return the list of TestCaseData to DataDriver
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/ReaderConfig.py
src/DataDriver/ReaderConfig.py
# Copyright 2018- René Rohner # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Any, Dict, List, Optional from robot.utils import DotDict # type: ignore from .utils import PabotOpt, TagHandling class ReaderConfig: TEST_CASE_TABLE_NAME = "*** Test Cases ***" def __init__( self, file: Optional[str] = None, encoding: Optional[str] = None, dialect: Optional[str] = None, delimiter: Optional[str] = None, quotechar: Optional[str] = None, escapechar: Optional[str] = None, doublequote: Optional[bool] = None, skipinitialspace: Optional[bool] = None, lineterminator: Optional[str] = None, sheet_name: Any = None, reader_class: Any = None, file_search_strategy: str = "path", file_regex: Optional[str] = None, include: Optional[str] = None, exclude: Optional[str] = None, handle_template_tags: TagHandling = TagHandling.UnsetTags, list_separator: Optional[str] = ",", config_keyword: Optional[str] = None, optimize_pabot: PabotOpt = PabotOpt.Equal, **kwargs, ): self.file = file self.encoding = encoding self.dialect = dialect self.delimiter = delimiter self.quotechar = quotechar self.escapechar = escapechar self.doublequote = doublequote self.skipinitialspace = skipinitialspace self.lineterminator = lineterminator self.sheet_name = sheet_name self.reader_class = reader_class self.file_search_strategy = file_search_strategy self.file_regex = file_regex self.include = include self.exclude = exclude self.handle_template_tags = handle_template_tags self.list_separator = list_separator self.config_keyword = config_keyword self.optimize_pabot = optimize_pabot self.kwargs = kwargs class TestCaseData(DotDict): def __init__( self, test_case_name: str = "", arguments: Optional[Dict] = None, tags: Optional[List] = None, documentation: Optional[str] = None, ): super().__init__() self.test_case_name = test_case_name self.arguments = arguments if arguments else {} self.tags = tags self.documentation = documentation
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/xls_reader.py
src/DataDriver/xls_reader.py
# Copyright 2018- René Rohner # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .xlsx_reader import nan, pd, xlsx_reader class xls_reader(xlsx_reader): def read_data_frame_from_file(self, dtype): return pd.read_excel(self.file, sheet_name=self.sheet_name, dtype=dtype).replace( nan, "", regex=True )
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/AbstractReaderClass.py
src/DataDriver/AbstractReaderClass.py
# Copyright 2018- René Rohner # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from abc import ABC, abstractmethod from re import compile from typing import List from robot.libraries.BuiltIn import BuiltIn # type: ignore from robot.utils import DotDict # type: ignore from .ReaderConfig import ReaderConfig, TestCaseData from .search import search_variable built_in = BuiltIn() class AbstractReaderClass(ABC): def __init__(self, reader_config: ReaderConfig): self.reader_config = reader_config self.file = reader_config.file self.csv_encoding = reader_config.encoding self.csv_dialect = reader_config.dialect self.delimiter = reader_config.delimiter self.quotechar = reader_config.quotechar self.escapechar = reader_config.escapechar self.doublequote = reader_config.doublequote self.skipinitialspace = reader_config.skipinitialspace self.lineterminator = reader_config.lineterminator self.sheet_name = reader_config.sheet_name self.list_separator = reader_config.list_separator self.handle_template_tags = reader_config.handle_template_tags self.kwargs = reader_config.kwargs for key, value in reader_config.kwargs.items(): setattr(self, key, value) self.test_case_column_id = None self.arguments_column_ids: List = [] self.tags_column_id = None self.documentation_column_id = None self.header: List = [] self.data_table: List[TestCaseData] = [] self.TESTCASE_TABLE_NAME = ReaderConfig.TEST_CASE_TABLE_NAME self.TEST_CASE_TABLE_PATTERN = compile(r"(?i)^(\*+\s*test ?cases?[\s*].*)") self.TASK_TABLE_PATTERN = compile(r"(?i)^(\*+\s*tasks?[\s*].*)") self.VARIABLE_PATTERN = compile(r"([$@&e]\{)(.*?)(\})") self.TAGS_PATTERN = compile(r"(?i)(\[)(tags)(\])") self.DOCUMENTATION_PATTERN = compile(r"(?i)(\[)(documentation)(\])") self.LIT_EVAL_PATTERN = compile(r"e\{(.+)\}") @abstractmethod def get_data_from_source(self) -> List[TestCaseData]: """This method must be implemented and return self.data_table ( a List[TestCaseData] ).""" def _is_test_case_header(self, header_string: str): return self.TEST_CASE_TABLE_PATTERN.fullmatch( header_string ) or self.TASK_TABLE_PATTERN.fullmatch(header_string) def _is_variable(self, header_string: str): return self.VARIABLE_PATTERN.match(header_string) def _is_tags(self, header_string: str): return self.TAGS_PATTERN.match(header_string) def _is_documentation(self, header_string: str): return self.DOCUMENTATION_PATTERN.match(header_string) def _analyse_header(self, header_cells): self.header = header_cells for cell_index, cell in enumerate(self.header): naked_cell = cell.strip() if self._is_test_case_header(naked_cell): self.test_case_column_id = cell_index elif self._is_variable(naked_cell): self.arguments_column_ids.append(cell_index) elif self._is_tags(naked_cell): self.tags_column_id = cell_index elif self._is_documentation(naked_cell): self.documentation_column_id = cell_index def _read_data_from_table(self, row): test_case_name = ( row[self.test_case_column_id] if self.test_case_column_id is not None else "" ) arguments = {} for arguments_column_id in self.arguments_column_ids: variable_string = str(self.header[arguments_column_id]).strip() variable_value = row[arguments_column_id] if self.LIT_EVAL_PATTERN.fullmatch(variable_string): variable_string = f"${variable_string[1:]}" variable_value = built_in.replace_variables(variable_value) variable_value = built_in.evaluate(variable_value) variable_match = search_variable(variable_string) if variable_match.is_variable: arguments.update( self._get_arguments_entry(variable_match, variable_value, arguments) ) tags = ( [t.strip() for t in row[self.tags_column_id].split(",")] if self.tags_column_id else None ) documentation = row[self.documentation_column_id] if self.documentation_column_id else None self.data_table.append(TestCaseData(test_case_name, arguments, tags, documentation)) def _get_arguments_entry(self, variable_match, variable_value, arguments): base = variable_match.base items = variable_match.items if variable_match.is_list_variable: if not variable_value: variable_value = [] else: variable_value = [ built_in.replace_variables(var) for var in (str(variable_value).split(self.list_separator)) ] elif variable_match.is_dict_variable: variable_value = built_in.create_dictionary( *(str(variable_value).split(self.list_separator)) ) if "." in base: # is dot notated advanced variable dictionary ${dict.key.subkey} base, *items = base.split(".") variable_value = self._update_argument_dict(arguments, base, items, variable_value) elif items: # is dictionary syntax ${dict}[key][subkey] variable_value = self._update_argument_dict(arguments, base, items, variable_value) return {self._as_var(base): variable_value} def _update_argument_dict(self, arguments, base, items, value): if self._as_var(base) not in arguments: arguments[self._as_var(base)] = built_in.create_dictionary() argument = arguments[self._as_var(base)] if isinstance(argument, DotDict): selected_key = argument for key in items: if key != items[-1]: if key not in selected_key or not isinstance(selected_key[key], DotDict): selected_key[key] = built_in.create_dictionary() selected_key = selected_key[key] selected_key[items[-1]] = built_in.replace_variables(value) return argument raise TypeError(f"{self._as_var(base)} is defined with a wrong type. Not defaultdict.") def _as_var(self, base): return f"${{{base}}}"
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/argument_utils.py
src/DataDriver/argument_utils.py
import sys from enum import IntEnum from robot.libraries.BuiltIn import BuiltIn # type: ignore from robot.run import USAGE # type: ignore from robot.utils.argumentparser import ArgumentParser # type: ignore SINGLE_ARG_CHARACTERS = ".?hTX" class ArgumentState(IntEnum): ANALYZE_NEXT = 0 ONE_KNOWN = 1 TWO_KNOWN = 2 def robot_options(): arg_parser = ArgumentParser( USAGE, auto_argumentfile=True, env_options="ROBOT_OPTIONS", ) cli_args = arg_parser.parse_args(filter_args(arg_parser))[0] try: options = BuiltIn().get_variable_value(name="${options}") if options is not None: cli_args["include"] = options["include"] cli_args["exclude"] = options["exclude"] except Exception: pass return cli_args def filter_args(arg_parser): short_opts = arg_parser._short_opts long_opts = arg_parser._long_opts arg_state = ArgumentState.ANALYZE_NEXT valid_robot_args = [] for arg in sys.argv[1:]: if arg_state == ArgumentState.ANALYZE_NEXT: arg_state = get_argument_state(arg, short_opts, long_opts) if arg_state >= ArgumentState.ONE_KNOWN: valid_robot_args.append(arg) arg_state -= 1 return valid_robot_args def get_argument_state(arg, short_opts, long_opts): param_opt = [l_opt[:-1] for l_opt in long_opts if l_opt[-1:] == "="] arg_state = 0 if is_short_option(arg): if arg[1] in SINGLE_ARG_CHARACTERS: arg_state = ArgumentState.ONE_KNOWN elif arg[1] in short_opts: arg_state = ArgumentState.TWO_KNOWN elif is_long_option(arg): if arg[2:] in param_opt: arg_state = ArgumentState.TWO_KNOWN elif arg[2:] in long_opts: arg_state = ArgumentState.ONE_KNOWN return arg_state def is_short_option(arg): return len(arg) == 2 and arg[0] == "-" # noqa: PLR2004 def is_long_option(arg): return len(arg) > 2 and arg[:2] == "--" # noqa: PLR2004 def is_pabot_testlevelsplit(): return "--testlevelsplit" in sys.argv
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/search.py
src/DataDriver/search.py
# Copyright 2008-2015 Nokia Networks # Copyright 2016- Robot Framework Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from robot.errors import VariableError # type: ignore def search_variable(string, identifiers="$@&%*", ignore_errors=False): if not (isinstance(string, str) and "{" in string): return VariableMatch(string) return VariableSearcher(identifiers, ignore_errors).search(string) class VariableMatch: def __init__(self, string, identifier=None, base=None, items=(), start=-1, end=-1): self.string = string self.identifier = identifier self.base = base self.items = items self.start = start self.end = end def resolve_base(self, variables, ignore_errors=False): if self.identifier: internal = search_variable(self.base) self.base = variables.replace_string( internal, custom_unescaper=unescape_variable_syntax, ignore_errors=ignore_errors, ) @property def name(self): return f"{self.identifier}{{{self.base}}}" if self else None @property def before(self): return self.string[: self.start] if self.identifier else self.string @property def match(self): return self.string[self.start : self.end] if self.identifier else None @property def after(self): return self.string[self.end :] if self.identifier else None @property def is_variable(self): return bool( self.identifier and self.base and self.start == 0 and self.end == len(self.string) ) @property def is_list_variable(self): return bool(self.is_variable and self.identifier == "@" and not self.items) @property def is_dict_variable(self): return bool(self.is_variable and self.identifier == "&" and not self.items) def __bool__(self): return self.identifier is not None def __str__(self): if not self: return "<no match>" items = "".join("[%s]" % i for i in self.item) if self.items else "" return f"{self.identifier}{{{self.base}}}{items}" class VariableSearcher: def __init__(self, identifiers, ignore_errors=False): self.identifiers = identifiers self._ignore_errors = ignore_errors self.start = -1 self.variable_chars = [] self.item_chars = [] self.items = [] self._open_brackets = 0 # Used both with curly and square brackets self._escaped = False def search(self, string): if not self._search(string): return VariableMatch(string) match = VariableMatch( string=string, identifier=self.variable_chars[0], base="".join(self.variable_chars[2:-1]), start=self.start, end=self.start + len(self.variable_chars), ) if self.items: match.items = tuple(self.items) match.end += sum(len(i) for i in self.items) + 2 * len(self.items) return match def _search(self, string, offset=0): start = self._find_variable_start(string) if start == -1: return False self.start = start + offset self._open_brackets += 1 self.variable_chars = [string[start], "{"] start += 2 state = self.variable_state for char in string[start:]: state = state(char) self._escaped = False if char != "\\" else not self._escaped if state is None: break if state: try: self._validate_end_state(state) except VariableError: if self._ignore_errors: return False raise return True def _find_variable_start(self, string): start = 1 while True: start = string.find("{", start) - 1 if start < 0: return -1 if self._start_index_is_ok(string, start): return start start += 2 def _start_index_is_ok(self, string, index): return string[index] in self.identifiers and not self._is_escaped(string, index) def _is_escaped(self, string, index): escaped = False while index > 0 and string[index - 1] == "\\": index -= 1 escaped = not escaped return escaped def variable_state(self, char): self.variable_chars.append(char) if char == "}" and not self._escaped: self._open_brackets -= 1 if self._open_brackets == 0: if not self._can_have_items(): return None return self.waiting_item_state elif char == "{" and not self._escaped: self._open_brackets += 1 return self.variable_state def _can_have_items(self): return self.variable_chars[0] in "$@&" def waiting_item_state(self, char): if char == "[": self._open_brackets += 1 return self.item_state return None def item_state(self, char): if char == "]" and not self._escaped: self._open_brackets -= 1 if self._open_brackets == 0: self.items.append("".join(self.item_chars)) self.item_chars = [] # Don't support chained item access with old @ and & syntax. # The old syntax was deprecated in RF 3.2 and in RF 3.3 it'll # be reassigned to mean using item in list/dict context. if self.variable_chars[0] in "@&": return None return self.waiting_item_state elif char == "[" and not self._escaped: self._open_brackets += 1 self.item_chars.append(char) return self.item_state def _validate_end_state(self, state): if state == self.variable_state: incomplete = "".join(self.variable_chars) raise VariableError("Variable '%s' was not closed properly." % incomplete) if state == self.item_state: variable = "".join(self.variable_chars) items = "".join("[%s]" % i for i in self.items) incomplete = "".join(self.item_chars) raise VariableError( f"Variable item '{variable}{items}[{incomplete}' was not closed properly." ) def unescape_variable_syntax(item): def handle_escapes(match): escapes, text = match.groups() if len(escapes) % 2 == 1 and starts_with_variable_or_curly(text): return escapes[1:] return escapes def starts_with_variable_or_curly(text): if text[0] in "{}": return True match = search_variable(text, ignore_errors=True) return match and match.start == 0 return re.sub(r"(\\+)(?=(.+))", handle_escapes, item) # TODO: This is pretty odd/ugly and used only in two places. Implement # something better or just remove altogether. class VariableIterator: def __init__(self, string, identifiers="$@&%*"): self._string = string self._identifiers = identifiers def __iter__(self): remaining = self._string while True: match = search_variable(remaining, self._identifiers) if not match: break remaining = match.after yield match.before, match.match, remaining def __len__(self): return sum(1 for _ in self) def __bool__(self): try: next(iter(self)) except StopIteration: return False else: return True
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/xlsx_reader.py
src/DataDriver/xlsx_reader.py
# Copyright 2018- René Rohner # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: from math import nan # type: ignore import openpyxl # type: ignore # noqa: F401 import pandas as pd # type: ignore except ImportError as err: raise ImportError( """Requirements (pandas, openpyxl) for XLSX support are not installed. Use 'pip install -U robotframework-datadriver[XLS]' to install XLSX support.""" ) from err from robot.utils import is_truthy # type: ignore from .AbstractReaderClass import AbstractReaderClass class xlsx_reader(AbstractReaderClass): def get_data_from_source(self): dtype = object if is_truthy(getattr(self, "preserve_xls_types", False)) else str data_frame = self.read_data_frame_from_file(dtype) self._analyse_header(list(data_frame)) for row_index, row in enumerate(data_frame.values.tolist()): try: self._read_data_from_table(row) except Exception as e: e.row = row_index + 1 raise e return self.data_table def read_data_frame_from_file(self, dtype): return pd.read_excel( self.file, sheet_name=self.sheet_name, dtype=dtype, engine="openpyxl", na_filter=False ).replace(nan, "", regex=True)
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/csv_reader.py
src/DataDriver/csv_reader.py
# Copyright 2018- René Rohner # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import csv from pathlib import Path from DataDriver.AbstractReaderClass import AbstractReaderClass class csv_reader(AbstractReaderClass): def get_data_from_source(self): self._register_dialects() self._read_file_to_data_table() return self.data_table def _register_dialects(self): if self.csv_dialect.lower() == "userdefined": csv.register_dialect( self.csv_dialect, delimiter=self.delimiter, quotechar=self.quotechar, escapechar=self.escapechar, doublequote=self.doublequote, skipinitialspace=self.skipinitialspace, lineterminator=self.lineterminator, quoting=csv.QUOTE_ALL, ) elif self.csv_dialect == "Excel-EU": csv.register_dialect( self.csv_dialect, delimiter=";", quotechar='"', escapechar="\\", doublequote=True, skipinitialspace=False, lineterminator="\r\n", quoting=csv.QUOTE_ALL, ) def _read_file_to_data_table(self): with Path(self.file).open(encoding=self.csv_encoding) as csvfile: reader = csv.reader(csvfile, self.csv_dialect) for row_index, row in enumerate(reader): try: if row_index == 0: self._analyse_header(row) else: self._read_data_from_table(row) except Exception as e: e.row = row_index + 1 raise e
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/generic_csv_reader.py
src/DataDriver/generic_csv_reader.py
# Copyright 2018- René Rohner # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import csv from pathlib import Path from DataDriver.AbstractReaderClass import AbstractReaderClass class generic_csv_reader(AbstractReaderClass): def get_data_from_source(self): self._register_dialects() self._read_file_to_data_table() return self.data_table def _register_dialects(self): if self.csv_dialect.lower() == "userdefined": csv.register_dialect( self.csv_dialect, delimiter=self.delimiter, quotechar=self.quotechar, escapechar=self.escapechar, doublequote=self.doublequote, skipinitialspace=self.skipinitialspace, lineterminator=self.lineterminator, quoting=csv.QUOTE_ALL, ) elif self.csv_dialect == "Excel-EU": csv.register_dialect( self.csv_dialect, delimiter=";", quotechar='"', escapechar="\\", doublequote=True, skipinitialspace=False, lineterminator="\r\n", quoting=csv.QUOTE_ALL, ) def _read_file_to_data_table(self): with Path(self.file).open(encoding=self.csv_encoding) as csvfile: reader = csv.reader(csvfile, self.csv_dialect) for row_index, row in enumerate(reader): if row_index == 0: row_of_variables = [] for cell in row: row_of_variables.append(f"${{{cell.strip()}}}") self._analyse_header(row_of_variables) else: self._read_data_from_table(row)
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/DataDriver.py
src/DataDriver/DataDriver.py
# Copyright 2018- René Rohner # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import importlib import inspect import re import traceback from glob import glob from pathlib import Path from typing import Any, Dict, List, Optional, Union # type: ignore from robot.api.logger import console # type: ignore from robot.libraries.BuiltIn import BuiltIn # type: ignore from robot.model.tags import Tags # type: ignore from robot.model.testsuite import TestSuite # type: ignore from robot.running import ArgumentSpec # type: ignore from robot.running.model import TestCase # type: ignore from robot.utils.dotdict import DotDict # type: ignore from robot.utils.importer import Importer # type: ignore from .AbstractReaderClass import AbstractReaderClass # type: ignore from .argument_utils import robot_options # type: ignore from .ReaderConfig import ( ReaderConfig, # type: ignore TestCaseData, # type: ignore ) from .search import search_variable # type: ignore from .utils import ( # type: ignore Encodings, PabotOpt, TagHandling, binary_partition_test_list, debug, equally_partition_test_list, error, get_filter_dynamic_test_names, get_variable_value, is_pabot_dry_run, is_same_keyword, warn, ) __version__ = "1.11.1" class DataDriver: # region: docstring """ =================================================== DataDriver for Robot Framework® =================================================== DataDriver is a Data-Driven extension for Robot Framework®. This document explains how to use the DataDriver library listener. For information about installation, support, and more, please visit the `project page <https://github.com/Snooz82/robotframework-datadriver>`_ For more information about Robot Framework®, see https://robotframework.org. DataDriver is used/imported as Library but does not provide keywords which can be used in a test. DataDriver uses the Listener Interface Version 3 to manipulate the test cases and creates new test cases based on a Data-File that contains the data for Data-Driven Testing. These data file may be .csv , .xls or .xlsx files. Data Driver is also able to cooperate with Microsoft PICT. An Open Source Windows tool for data combination testing. Pict is able to generate data combinations based on textual model definitions. https://github.com/Microsoft/pict It is also possible to implement own DataReaders in Python to read your test data from some other sources, like databases or json files. Installation ------------ If you already have Python >= 3.6 with pip installed, you can simply run: ``pip install --upgrade robotframework-datadriver`` Excel Support ~~~~~~~~~~~~~ For file support of ``xls`` or ``xlsx`` file you need to install the extra XLS or the dependencies. It contains the dependencies of pandas, numpy and xlrd. Just add [XLS] to your installation. New since version 3.6. ``pip install --upgrade robotframework-datadriver[XLS]`` Python 2 ~~~~~~~~ or if you have Python 2 and 3 installed in parallel you may use ``pip3 install --upgrade robotframework-datadriver`` DataDriver is compatible with Python 2.7 only in Version 0.2.7. ``pip install --upgrade robotframework-datadriver==0.2.7`` Because Python 2.7 is deprecated, there are no new feature to python 2.7 compatible version. Table of contents ----------------- - `What DataDriver Does`_ - `How DataDriver Works`_ - `Usage`_ - `Structure of Test Suite`_ - `Structure of data file`_ - `Accessing Test Data From Robot Variables`_ - `Data Sources`_ - `File Encoding and CSV Dialect`_ - `Custom DataReader Classes`_ - `Selection of Test Cases to Execute`_ - `Configure DataDriver by Pre-Run Keyword`_ - `Pabot and DataDriver`_ What DataDriver Does -------------------- DataDriver is an alternative approach to create Data-Driven Tests with Robot Framework®. DataDriver creates multiple test cases based on a test template and data content of a csv or Excel file. All created tests share the same test sequence (keywords) and differ in the test data. Because these tests are created on runtime only the template has to be specified within the robot test specification and the used data are specified in an external data file. RoboCon 2020 Talk ~~~~~~~~~~~~~~~~~ .. image:: https://img.youtube.com/vi/RtEUr1i4x3s/0.jpg :target: https://www.youtube.com/watch?v=RtEUr1i4x3s Brief overview what DataDriver is and how it works at the RoboCon 2020 in Helsiki. Alternative approach ~~~~~~~~~~~~~~~~~~~~ DataDriver gives an alternative to the build in data driven approach like: .. code :: robotframework *** Settings *** Resource login_resources.robot Suite Setup Open my Browser Suite Teardown Close Browsers Test Setup Open Login Page Test Template Invalid login *** Test Cases *** User Passwort Right user empty pass demo ${EMPTY} Right user wrong pass demo FooBar Empty user right pass ${EMPTY} mode Empty user empty pass ${EMPTY} ${EMPTY} Empty user wrong pass ${EMPTY} FooBar Wrong user right pass FooBar mode Wrong user empty pass FooBar ${EMPTY} Wrong user wrong pass FooBar FooBar *** Keywords *** Invalid login [Arguments] ${username} ${password} Input username ${username} Input pwd ${password} click login button Error page should be visible This inbuilt approach is fine for a hand full of data and a hand full of test cases. If you have generated or calculated data and specially if you have a variable amount of test case / combinations these robot files become quite a pain. With DataDriver you may write the same test case syntax but only once and deliver the data from en external data file. One of the rare reasons when Microsoft® Excel or LibreOffice Calc may be used in testing… ;-) `See example test suite <#example-suite>`__ `See example csv table <#example-csv>`__ How DataDriver Works -------------------- When the DataDriver is used in a test suite it will be activated before the test suite starts. It uses the Listener Interface Version 3 of Robot Framework® to read and modify the test specification objects. After activation it searches for the ``Test Template`` -Keyword to analyze the ``[Arguments]`` it has. As a second step, it loads the data from the specified data source. Based on the ``Test Template`` -Keyword, DataDriver creates as much test cases as data sets are in the data source. In the case that data source is csv (Default) As values for the arguments of the ``Test Template`` -Keyword, DataDriver reads values from the column of the CSV file with the matching name of the ``[Arguments]``. For each line of the CSV data table, one test case will be created. It is also possible to specify test case names, tags and documentation for each test case in the specific test suite related CSV file. Usage ----- Data Driver is a "Library Listener" but does not provide keywords. Because Data Driver is a listener and a library at the same time it sets itself as a listener when this library is imported into a test suite. To use it, just use it as Library in your suite. You may use the first argument (option) which may set the file name or path to the data file. Without any options set, it loads a .csv file which has the same name and path like the test suite .robot . **Example:** .. code :: robotframework *** Settings *** Library DataDriver Test Template Invalid Logins *** Keywords *** Invalid Logins ... Structure of Test Suite ----------------------- Requirements ~~~~~~~~~~~~ In the Moment there are some requirements how a test suite must be structured so that the DataDriver can get all the information it needs. - only the first test case will be used as a template. All other test cases will be deleted. - Test cases have to be defined with a ``Test Template`` in Settings secion. Reason for this is, that the DataDriver needs to know the names of the test case arguments. Test cases do not have named arguments. Keywords do. - The keyword which is used as ``Test Template`` must be defined within the test suite (in the same \*.robot file). If the keyword which is used as ``Test Template`` is defined in a ``Resource`` the DataDriver has no access to its arguments names. Example Test Suite ~~~~~~~~~~~~~~~~~~ .. code :: robotframework ***Settings*** Library DataDriver Resource login_resources.robot Suite Setup Open my Browser Suite Teardown Close Browsers Test Setup Open Login Page Test Template Invalid Login *** Test Case *** Login with user ${username} and password ${password} Default UserData ***** *Keywords* ***** Invalid login [Arguments] ${username} ${password} Input username ${username} Input pwd ${password} click login button Error page should be visible In this example, the DataDriver is activated by using it as a Library. It is used with default settings. As ``Test Template`` the keyword ``Invalid Login`` is used. This keyword has two arguments. Argument names are ``${username}`` and ``${password}``. These names have to be in the CSV file as column header. The test case has two variable names included in its name, which does not have any functionality in Robot Framework®. However, the Data Driver will use the test case name as a template name and replaces the variables with the specific value of the single generated test case. This template test will only be used as a template. The specified data ``Default`` and ``UserData`` would only be used if no CSV file has been found. Structure of data file ---------------------- min. required columns ~~~~~~~~~~~~~~~~~~~~~ - ``*** Test Cases ***`` column has to be the first one. - *Argument columns:* For each argument of the ``Test Template`` keyword one column must be existing in the data file as data source. The name of this column must match the variable name and syntax. optional columns ~~~~~~~~~~~~~~~~ - *[Tags]* column may be used to add specific tags to a test case. Tags may be comma separated. - *[Documentation]* column may be used to add specific test case documentation. Example Data file ~~~~~~~~~~~~~~~~~ +-------------+-------------+-------------+-------------+------------------+ | \**\* Test | ${username} | ${password} | [Tags] | [Documentation] | | Cases \**\* | | | | | | | | | | | +=============+=============+=============+=============+==================+ | Right user | demo | ${EMPTY} | 1 | This is a test | | empty pass | | | | case | | | | | | documentation of | | | | | | the first one. | +-------------+-------------+-------------+-------------+------------------+ | Right user | demo | FooBar | 2,3,foo | This test | | wrong pass | | | | case has | | | | | | the Tags | | | | | | 2,3 and foo | | | | | | assigned. | +-------------+-------------+-------------+-------------+------------------+ | | ${EMPTY} | mode | 1,2,3,4 | This test | | | | | | case has a | | | | | | generated | | | | | | name based | | | | | | on template | | | | | | name. | +-------------+-------------+-------------+-------------+------------------+ | | ${EMPTY} | ${EMPTY} | | | +-------------+-------------+-------------+-------------+------------------+ | | ${EMPTY} | FooBar | | | +-------------+-------------+-------------+-------------+------------------+ | | FooBar | mode | | | +-------------+-------------+-------------+-------------+------------------+ | | FooBar | ${EMPTY} | | | +-------------+-------------+-------------+-------------+------------------+ | | FooBar | FooBar | | | +-------------+-------------+-------------+-------------+------------------+ In this data file, eight test cases are defined. Each line specifies one test case. The first two test cases have specific names. The other six test cases will generate names based on template test cases name with the replacement of variables in this name. The order of columns is irrelevant except the first column, ``*** Test Cases ***`` Supported Data Types ~~~~~~~~~~~~~~~~~~~~ In general DataDriver supports any Object that is handed over from the DataReader. However the text based readers for csv, excel and so do support different types as well. DataDriver supports Robot Framework® Scalar variables as well as Dictionaries and Lists. It also support python literal evaluations. Scalar Variables ^^^^^^^^^^^^^^^^ The Prefix ``$`` defines that the value in the cell is taken as in Robot Framework® Syntax. ``String`` is ``str``, ``${1}`` is ``int`` and ``${None}`` is NoneType. The Prefix only defines the value typ. It can also be used to assign a scalar to a dictionary key. See example table: ``${user}[id]`` Dictionary Variables ^^^^^^^^^^^^^^^^^^^^ Dictionaries can be created in different ways. One option is, to use the prefix ``&``. If a variable is defined that was (i.e. ``&{dict}``) the cell value is interpreted the same way, the BuiltIn keyword `Create Dictionary <https://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Create%20Dictionary>`_ would do. The arguments here are comma (``,``) separated. See example table: ``&{dict}`` The other option is to define scalar variables in dictionary syntax like ``${user}[name]`` or ``${user.name}`` That can be also nested dictionaries. DataDriver will create Robot Framework® (DotDict) Dictionaries, that can be accessed with ``${user.name.first}`` See example table: ``${user}[name][first]`` List Variables ^^^^^^^^^^^^^^ Lists can be created with the prefix ``@`` as comma (``,``) separated list. See example table: ``@{list}`` Be aware that a list with an empty string has to be the cell content `${Empty}`. Python Literals ^^^^^^^^^^^^^^^ DataDriver can evaluate Literals. It uses the prefix ``e`` for that. (i.e. ``e{list_eval}``) For that it uses `BuiltIn Evaluate <https://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Evaluate>`_ See example table: ``e{user.chk}`` +--------------------------+-----------------------+---------------+-------------------------+-----------------------------+------------------------------------------+--------------------------+-------------------+-------------------+----------------------------+-------------------------+------------------------------------------------------------------+ | ``*** Test Cases ***`` | ``${scalar}`` | ``@{list}`` | ``e{list_eval}`` | ``&{dict}`` | ``e{dict_eval}`` | ``e{eval}`` | ``${exp_eval}`` | ``${user}[id]`` | ``${user}[name][first]`` | ``${user.name.last}`` | ``e{user.chk}`` | +--------------------------+-----------------------+---------------+-------------------------+-----------------------------+------------------------------------------+--------------------------+-------------------+-------------------+----------------------------+-------------------------+------------------------------------------------------------------+ | ``One`` | ``Sum List`` | ``1,2,3,4`` | ``["1","2","3","4"]`` | ``key=value`` | ``{'key': 'value'}`` | ``[1,2,3,4]`` | ``10`` | ``1`` | ``Pekka`` | ``Klärck`` | ``{'id': '1', 'name': {'first': 'Pekka', 'last': 'Klärck'}}`` | +--------------------------+-----------------------+---------------+-------------------------+-----------------------------+------------------------------------------+--------------------------+-------------------+-------------------+----------------------------+-------------------------+------------------------------------------------------------------+ | ``Two`` | ``Should be Equal`` | ``a,b,c,d`` | ``["a","b","c","d"]`` | ``key,value`` | ``{'key': 'value'}`` | ``True`` | ``${true}`` | ``2`` | ``Ed`` | ``Manlove`` | ``{'id': '2', 'name': {'first': 'Ed', 'last': 'Manlove'}}`` | +--------------------------+-----------------------+---------------+-------------------------+-----------------------------+------------------------------------------+--------------------------+-------------------+-------------------+----------------------------+-------------------------+------------------------------------------------------------------+ | ``Three`` | ``Whos your Daddy`` | ``!,",',$`` | ``["!",'"',"'","$"]`` | ``z,value,a,value2`` | ``{'a': 'value2', 'z': 'value'}`` | ``{'Daddy' : 'René'}`` | ``René`` | ``3`` | ``Tatu`` | ``Aalto`` | ``{'id': '3', 'name': {'first': 'Tatu', 'last': 'Aalto'}}`` | +--------------------------+-----------------------+---------------+-------------------------+-----------------------------+------------------------------------------+--------------------------+-------------------+-------------------+----------------------------+-------------------------+------------------------------------------------------------------+ | ``4`` | ``Should be Equal`` | ``1`` | ``["1"]`` | ``key=value`` | ``{'key': 'value'}`` | ``1`` | ``${1}`` | ``4`` | ``Jani`` | ``Mikkonen`` | ``{'id': '4', 'name': {'first': 'Jani', 'last': 'Mikkonen'}}`` | +--------------------------+-----------------------+---------------+-------------------------+-----------------------------+------------------------------------------+--------------------------+-------------------+-------------------+----------------------------+-------------------------+------------------------------------------------------------------+ | ``5`` | ``Should be Equal`` | | ``[]`` | ``a=${2}`` | ``{'a':2}`` | ``"string"`` | ``string`` | ``5`` | ``Mikko`` | ``Korpela`` | ``{'id': '5', 'name': {'first': 'Mikko', 'last': 'Korpela'}}`` | +--------------------------+-----------------------+---------------+-------------------------+-----------------------------+------------------------------------------+--------------------------+-------------------+-------------------+----------------------------+-------------------------+------------------------------------------------------------------+ | ``6`` | ``Should be Equal`` | ``[1,2]`` | ``["[1","2]"]`` | ``key=value,key2=value2`` | ``{'key': 'value', 'key2': 'value2'}`` | ``None`` | ``${none}`` | ``6`` | ``Ismo`` | ``Aro`` | ``{'id': '6', 'name': {'first': 'Ismo', 'last': 'Aro'}}`` | +--------------------------+-----------------------+---------------+-------------------------+-----------------------------+------------------------------------------+--------------------------+-------------------+-------------------+----------------------------+-------------------------+------------------------------------------------------------------+ Accessing Test Data From Robot Variables ---------------------------------------- If neccesary it is possible to access the fetched data tables directly from a Robot Framework® variable. This could be helpfull in Test Setup or in Suite Setup. There are three variables available within the Data-Driven Suite: @{DataDriver_DATA_LIST} ~~~~~~~~~~~~~~~~~~~~~~~ A list as suite variable containing a robot dictionary for each test case that is selected for execution. .. code :: json [ { "test_case_name": "Right user empty pass", "arguments": { "${username}": "demo", "${password}": "${EMPTY}" }, "tags": [ "1" ], "documentation": "This is a test case documentation of the first one." }, { "test_case_name": "Right user wrong pass", "arguments": { "${username}": "demo", "${password}": "FooBar" }, "tags": [ "2", "3", "foo" ], "documentation": "This test case has the Tags 2,3 and foo" }, { "test_case_name": "Login with user '${EMPTY}' and password 'mode'", "arguments": { "${username}": "${EMPTY}", "${password}": "mode" }, "tags": [ "1", "2", "3", "4" ], "documentation": "This test case has a generated name based on template name." }, { "test_case_name": "Login with user '${EMPTY}' and password '${EMPTY}'", "arguments": { "${username}": "${EMPTY}", "${password}": "${EMPTY}" }, "tags": [ "" ], "documentation": "" }, { "test_case_name": "Login with user '${EMPTY}' and password 'FooBar'", "arguments": { "${username}": "${EMPTY}", "${password}": "FooBar" }, "tags": [ "" ], "documentation": "" }, { "test_case_name": "Login with user 'FooBar' and password 'mode'", "arguments": { "${username}": "FooBar", "${password}": "mode" }, "tags": [ "foo", "1" ], "documentation": "" }, { "test_case_name": "Login with user 'FooBar' and password '${EMPTY}'", "arguments": { "${username}": "FooBar", "${password}": "${EMPTY}" }, "tags": [ "foo" ], "documentation": "" }, { "test_case_name": "Login with user 'FooBar' and password 'FooBar'", "arguments": { "${username}": "FooBar", "${password}": "FooBar" }, "tags": [ "foo", "2" ], "documentation": "" } ] This can be accessed as usual in Robot Framework®. ``${DataDriver_DATA_LIST}[2][arguments][\${password}]`` would result in ``mode`` . &{DataDriver_DATA_DICT} ~~~~~~~~~~~~~~~~~~~~~~~ A dictionary as suite variable that contains the same data as the list, with the test names as keys. .. code :: json { "Right user empty pass": { "test_case_name": "Right user empty pass", "arguments": { "${username}": "demo", "${password}": "${EMPTY}" }, "tags": [ "1" ], "documentation": "This is a test case documentation of the first one." }, "Right user wrong pass": { "test_case_name": "Right user wrong pass", "arguments": { "${username}": "demo", "${password}": "FooBar" }, "tags": [ "2", "3", "foo" ], "documentation": "This test case has the Tags 2,3 and foo" }, "Login with user '${EMPTY}' and password 'mode'": { "test_case_name": "Login with user '${EMPTY}' and password 'mode'", "arguments": { "${username}": "${EMPTY}", "${password}": "mode" }, "tags": [ "1", "2", "3", "4" ], "documentation": "This test case has a generated name based on template name." }, "Login with user '${EMPTY}' and password '${EMPTY}'": { "test_case_name": "Login with user '${EMPTY}' and password '${EMPTY}'", "arguments": { "${username}": "${EMPTY}", "${password}": "${EMPTY}" }, "tags": [ "" ], "documentation": "" }, "Login with user '${EMPTY}' and password 'FooBar'": { "test_case_name": "Login with user '${EMPTY}' and password 'FooBar'", "arguments": { "${username}": "${EMPTY}", "${password}": "FooBar" }, "tags": [ "" ], "documentation": "" }, "Login with user 'FooBar' and password 'mode'": { "test_case_name": "Login with user 'FooBar' and password 'mode'", "arguments": { "${username}": "FooBar", "${password}": "mode" }, "tags": [ "foo", "1" ], "documentation": "" }, "Login with user 'FooBar' and password '${EMPTY}'": { "test_case_name": "Login with user 'FooBar' and password '${EMPTY}'", "arguments": { "${username}": "FooBar", "${password}": "${EMPTY}" }, "tags": [ "foo" ], "documentation": "" }, "Login with user 'FooBar' and password 'FooBar'": { "test_case_name": "Login with user 'FooBar' and password 'FooBar'", "arguments": { "${username}": "FooBar", "${password}": "FooBar" }, "tags": [ "foo", "2" ], "documentation": "" } } &{DataDriver_TEST_DATA} ~~~~~~~~~~~~~~~~~~~~~~~ A dictionary as test variable that contains the test data of the current test case. This dictionary does also contain arguments that are not used in the ``Test Template`` keyword. This can be used in Test Setup and within a test case. .. code :: json { "test_case_name": "Right user wrong pass", "arguments": { "${username}": "demo", "${password}": "FooBar" }, "tags": [ "2", "3", "foo" ], "documentation": "This test case has the Tags 2,3 and foo" } Data Sources ------------ CSV / TSV (Character-separated values) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ By default DataDriver reads csv files. With the `Encoding and CSV Dialect <#file-encoding-and-csv-dialect>`__ settings you may configure which structure your data source has. XLS / XLSX Files ~~~~~~~~~~~~~~~~ To use Excel file types, you have to install DataDriver with the Extra XLS. If you want to use Excel based data sources, you may just set the file to the extention or you may point to the correct file. If the extention is ".xls" or ".xlsx" DataDriver will interpret it as Excel file. You may select the sheet which will be read by the option ``sheet_name``. By default it is set to 0 which will be the first table sheet. You may use sheet index (0 is first sheet) or sheet name(case sensitive). XLS interpreter will ignore all other options like encoding, delimiters etc. .. code :: robotframework *** Settings *** Library DataDriver .xlsx or: .. code :: robotframework *** Settings *** Library DataDriver file=my_data_source.xlsx sheet_name=2nd Sheet MS Excel and typed cells ^^^^^^^^^^^^^^^^^^^^^^^^ Microsoft Excel xls or xlsx file have the possibility to type thair data cells. Numbers are typically of the type float. If these data are not explicitly defined as text in Excel, pandas will read it as the type that is has in excel. Because we have to work with strings in Robot Framework® these data are converted to string. This leads to the situation that a European time value like "04.02.2019" (4th January 2019) is handed over to Robot Framework® in Iso time "2019-01-04 00:00:00". This may cause unwanted behavior. To mitigate this risk you should define Excel based files explicitly as text within Excel. Alternatively you may deactivate that string conversion. To do so, you have to add the option ``preserve_xls_types`` to ``True``. In that case, you will get str, float, boolean, int, datetime.time, datetime.datetime and some others. .. code :: robotframework *** Settings *** Library DataDriver file=my_data_source.xlsx preserve_xls_types=True PICT (Pairwise Independent Combinatorial Testing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pict is able to generate data files based on a model file. https://github.com/Microsoft/pict Documentation: https://github.com/Microsoft/pict/blob/master/doc/pict.md Requirements of PICT ^^^^^^^^^^^^^^^^^^^^ - Path to pict.exe must be set in the %PATH% environment variable. - Data model file has the file extention ".pict" - Pict model file must be encoded in UTF-8 How it works ^^^^^^^^^^^^ If the file option is set to a file with the extention pict, DataDriver will hand over this file to pict.exe and let it automatically generates
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
true
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/json_reader.py
src/DataDriver/json_reader.py
# Copyright 2018- René Rohner # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ [ { "test_case_name": "first", "arguments": { "${username}": "demo", "${password}": "mode" }, "tags": [ "tag1", "tag2", "smoke" ], "documentation": "This is the doc" }, { "test_case_name": "second", "arguments": { "${username}": "${EMPTY}", "${password}": "mode" }, "tags": [ "tag1", "smoke" ], "documentation": "This is the doc" } ] """ from json import load from pathlib import Path from .AbstractReaderClass import AbstractReaderClass from .ReaderConfig import TestCaseData class json_reader(AbstractReaderClass): def get_data_from_source(self): with Path(self.file).open(encoding="utf-8") as json_file: return [TestCaseData(**test) for test in load(json_file)]
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/glob_reader.py
src/DataDriver/glob_reader.py
# Copyright 2021- René Rohner # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This Reader has initialy been created by Samual Montgomery-Blinn (https://github.com/montsamu) # Thanks for this contribution from glob import glob from pathlib import Path from DataDriver.AbstractReaderClass import AbstractReaderClass class glob_reader(AbstractReaderClass): def get_data_from_source(self): self._read_glob_to_data_table() return self.data_table def _read_glob_to_data_table(self): self._analyse_header(["*** Test Cases ***", self.kwargs.get("arg_name", "${file_name}")]) for match_path in sorted(glob(self.file)): path = Path(match_path).resolve() path_as_posix = path.as_posix() if path.is_file(): test_case_name = path.stem elif path.is_dir(): test_case_name = path.name else: test_case_name = str(path_as_posix) self._read_data_from_table([test_case_name, str(path_as_posix)])
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/utils.py
src/DataDriver/utils.py
import math import re from enum import Enum, auto from typing import Any, List from robot.api import logger # type: ignore from robot.libraries.BuiltIn import BuiltIn # type: ignore from .argument_utils import is_pabot_testlevelsplit class Encodings(Enum): """ Python comes with a number of codecs built-in, either implemented as C functions or with dictionaries as mapping tables. The following table lists the codecs by name, together with a few common aliases, and the languages for which the encoding is likely used. Neither the list of aliases nor the list of languages is meant to be exhaustive. Notice that spelling alternatives that only differ in case or use a hyphen instead of an underscore are also valid aliases; therefore, e.g. ``utf-8` is a valid alias for the ``utf_8`` codec. *CPython implementation detail:* Some common encodings can bypass the codecs lookup machinery to improve performance. These optimization opportunities are only recognized by CPython for a limited set of (case insensitive) aliases: utf-8, utf8, latin-1, latin1, iso-8859-1, iso8859-1, mbcs (Windows only), ascii, us-ascii, utf-16, utf16, utf-32, utf32, and the same using underscores instead of dashes. Using alternative aliases for these encodings may result in slower execution. Changed in version 3.6: Optimization opportunity recognized for us-ascii. Many of the character sets support the same languages. They vary in individual characters (e.g. whether the EURO SIGN is supported or not), and in the assignment of characters to code positions. For the European languages in particular, the following variants typically exist: - utf-8 - cp1252 - an ISO 8859 codeset - a Microsoft Windows code page, which is typically derived from an 8859 codeset, but replaces control characters with additional graphic characters - an IBM EBCDIC code page - an IBM PC code page, which is ASCII compatible """ ascii = auto() big5 = auto() big5hkscs = auto() cp037 = auto() cp273 = auto() cp424 = auto() cp437 = auto() cp500 = auto() cp720 = auto() cp737 = auto() cp775 = auto() cp850 = auto() cp852 = auto() cp855 = auto() cp856 = auto() cp857 = auto() cp858 = auto() cp860 = auto() cp861 = auto() cp862 = auto() cp863 = auto() cp864 = auto() cp865 = auto() cp866 = auto() cp869 = auto() cp874 = auto() cp875 = auto() cp932 = auto() cp949 = auto() cp950 = auto() cp1006 = auto() cp1026 = auto() cp1125 = auto() cp1140 = auto() cp1250 = auto() cp1251 = auto() cp1252 = auto() cp1253 = auto() cp1254 = auto() cp1255 = auto() cp1256 = auto() cp1257 = auto() cp1258 = auto() euc_jp = auto() euc_jis_2004 = auto() euc_jisx0213 = auto() euc_kr = auto() gb2312 = auto() gbk = auto() gb18030 = auto() hz = auto() iso2022_jp = auto() iso2022_jp_1 = auto() iso2022_jp_2 = auto() iso2022_jp_2004 = auto() iso2022_jp_3 = auto() iso2022_jp_ext = auto() iso2022_kr = auto() latin_1 = auto() iso8859_2 = auto() iso8859_3 = auto() iso8859_4 = auto() iso8859_5 = auto() iso8859_6 = auto() iso8859_7 = auto() iso8859_8 = auto() iso8859_9 = auto() iso8859_10 = auto() iso8859_11 = auto() iso8859_13 = auto() iso8859_14 = auto() iso8859_15 = auto() iso8859_16 = auto() johab = auto() koi8_r = auto() koi8_t = auto() koi8_u = auto() kz1048 = auto() mac_cyrillic = auto() mac_greek = auto() mac_iceland = auto() mac_latin2 = auto() mac_roman = auto() mac_turkish = auto() ptcp154 = auto() shift_jis = auto() shift_jis_2004 = auto() shift_jisx0213 = auto() utf_32 = auto() utf_32_be = auto() utf_32_le = auto() utf_16 = auto() utf_16_be = auto() utf_16_le = auto() utf_7 = auto() utf_8 = auto() utf_8_sig = auto() class PabotOpt(Enum): """ You can switch Pabot --testlevelsplit between three modes: - Equal: means it creates equal sizes groups - Binary: is more complex. it created a decreasing size of containers to support better balancing. - Atomic: it does not group tests at all and runs really each test case in a separate thread. See `Pabot and DataDriver <#pabot-and-datadriver>`__ for more details. This can be set by ``optimize_pabot`` in Library import. """ Equal = auto() Binary = auto() Atomic = auto() class TagHandling(Enum): """ You can configure how to handle tags from the template in generated tests: - ForceTags: Will add all tags of the template test to all data-driven test cases. - UnsetTags: Will add only these tags from template test to the tests, that are not assigned to any of the test cases. - DefaultTags: Will only add tags to data-driven test if no tag is set on that test. - NoTags: Will not add any tags from the template to date-driven tests. """ ForceTags = auto() UnsetTags = auto() DefaultTags = auto() NoTags = auto() def debug(msg: Any, newline: bool = True, stream: str = "stdout"): if get_variable_value("${LOG LEVEL}") in ["DEBUG", "TRACE"]: logger.console(msg, newline, stream) def console(msg: Any, newline: bool = True, stream: str = "stdout"): logger.console(msg, newline, stream) def warn(msg: Any, html: bool = False): logger.warn(msg, html) def error(msg: Any, html: bool = False): logger.error(msg, html) def get_filter_dynamic_test_names(): dynamic_test_list = get_variable_value("${DYNAMICTESTS}") if isinstance(dynamic_test_list, str): test_names_esc = re.split(r"(?<!\\)(?:\\\\)*\|", dynamic_test_list) return [name.replace("\\|", "|").replace("\\\\", "\\") for name in test_names_esc] if isinstance(dynamic_test_list, list): return dynamic_test_list dynamic_test_name = get_variable_value("${DYNAMICTEST}") if dynamic_test_name: BuiltIn().set_suite_metadata("DataDriver", dynamic_test_name, True) return [dynamic_test_name] return None def is_pabot_dry_run(): return is_pabot_testlevelsplit() and get_variable_value("${PABOTQUEUEINDEX}") == "-1" def get_variable_value(name: str): return BuiltIn().get_variable_value(name) def is_same_keyword(first: str, second: str): return _get_normalized_keyword(first) == _get_normalized_keyword(second) def _get_normalized_keyword(keyword: str): return keyword.lower().replace(" ", "").replace("_", "") def binary_partition_test_list(test_list: List, process_count: int): fractions = equally_partition_test_list(test_list, process_count) return_list = [] for _i in range(int(math.sqrt(len(test_list) // process_count))): first, second = _partition_second_half(fractions) return_list.extend(first) fractions = second return_list.extend(fractions) return [test_name for test_name in return_list if test_name] def _partition_second_half(fractions): first = fractions[: len(fractions) // 2] second = [] for sub_list in fractions[len(fractions) // 2 :]: sub_sub_list = equally_partition_test_list(sub_list, 2) second.extend(sub_sub_list) return first, second def equally_partition_test_list(test_list: List, fraction_count: int): quotient, remainder = divmod(len(test_list), fraction_count) return [ test_list[i * quotient + min(i, remainder) : (i + 1) * quotient + min(i + 1, remainder)] for i in range(fraction_count) ]
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/rerunfailed.py
src/DataDriver/rerunfailed.py
"""Pre-run modifier that excludes tests that run PASS last time. """ import re from pathlib import Path from robot.api import ExecutionResult, ResultVisitor, SuiteVisitor # type: ignore try: from robot.running.model import Variable # type: ignore except ImportError: from robot.running.resourcemodel import Variable # type: ignore / robotframework>=7.0 class rerunfailed(SuiteVisitor): def __init__(self, original_output_xml): if not Path(original_output_xml).is_file(): raise FileNotFoundError(f"{original_output_xml} is no file") result = ExecutionResult(original_output_xml) results_visitor = DataDriverResultsVisitor() result.visit(results_visitor) self._failed_tests = results_visitor.failed_tests def start_suite(self, suite): """Remove tests that match the given pattern.""" if self.has_no_tests(suite.name): suite.tests.clear() return if self._suite_is_data_driven(suite): dynamic_tests = Variable("${DYNAMICTESTS}", self._failed_tests, suite.source) suite.resource.variables.append(dynamic_tests) else: suite.tests = [ t for t in suite.tests if f"{t.parent.name}.{t.name}" in self._failed_tests ] def has_no_tests(self, name): r = re.compile(f'^{re.escape(f"{name}.")}.*$') return not bool(list(filter(r.match, self._failed_tests))) def _suite_is_data_driven(self, suite): for resource in suite.resource.imports: if resource.name == "DataDriver": return True return None def end_suite(self, suite): """Remove suites that are empty after removing tests.""" suite.suites = [s for s in suite.suites if s.test_count > 0] def visit_test(self, test): """Avoid visiting tests and their keywords to save a little time.""" class DataDriverResultsVisitor(ResultVisitor): def __init__(self): self.failed_tests = [] def start_test(self, test): if test.status == "FAIL": self.failed_tests.append(f"{test.parent.name}.{test.name}")
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/pict_reader.py
src/DataDriver/pict_reader.py
# Copyright 2018- René Rohner # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import csv import os import time from pathlib import Path from DataDriver.utils import debug from .AbstractReaderClass import AbstractReaderClass, ReaderConfig class pict_reader(AbstractReaderClass): def __init__(self, reader_config: ReaderConfig): super().__init__(reader_config) file = self.file or "" self.pictout_file = f"{Path(file).stem}{time.monotonic()}.pictout" def get_data_from_source(self): self._register_dialect() self._create_generated_file_from_model_file() self._read_generated_file_to_dictionaries() return self.data_table @staticmethod def _register_dialect(): csv.register_dialect( "PICT", delimiter="\t", skipinitialspace=False, lineterminator="\r\n", quoting=csv.QUOTE_NONE, ) def _create_generated_file_from_model_file(self): args = self.pict_options if hasattr(self, "pict_options") else "" debug(f'pict "{self.file}" {args} > "{self.pictout_file}"') os.system(f'pict "{self.file}" {args} > "{self.pictout_file}"') def _read_generated_file_to_dictionaries(self): with Path(self.pictout_file).open(encoding="utf_8") as csvfile: reader = csv.reader(csvfile, "PICT") for row_index, row in enumerate(reader): if row_index == 0: row_of_variables = [] for cell in row: row_of_variables.append(f"${{{cell}}}") self._analyse_header(row_of_variables) else: self._read_data_from_table(row) Path(self.pictout_file).unlink()
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/src/DataDriver/__init__.py
src/DataDriver/__init__.py
from .DataDriver import DataDriver # noqa: F401
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
Snooz82/robotframework-datadriver
https://github.com/Snooz82/robotframework-datadriver/blob/d2d519666250324478bdccd7ccd65206a9110bf4/example/demo_web_server/server.py
example/demo_web_server/server.py
#!/usr/bin/env python """Simple HTTP server for Robot Framework web testing demo. Usage: server.py [port] This server serves HTML pages under `html` directory. Server is started simply by running this script from the command line or double-clicking it in a file manager. In the former case the server can be shut down with Ctrl-C and in the latter case by closing the opened window. By default the server uses port 7272, but a custom port can be given as an argument from the command line. """ from os import chdir from os.path import abspath, dirname, join from socketserver import TCPServer from http.server import SimpleHTTPRequestHandler ROOT = join(dirname(abspath(__file__)), "html") PORT = 7272 class DemoServer(TCPServer): allow_reuse_address = True def __init__(self, port=PORT): TCPServer.__init__(self, ("localhost", int(port)), SimpleHTTPRequestHandler) def serve(self, directory=ROOT): chdir(directory) print("Demo server starting on port %d." % self.server_address[1]) try: server.serve_forever() except KeyboardInterrupt: server.server_close() print("Demo server stopped.") if __name__ == "__main__": import sys try: server = DemoServer(*sys.argv[1:]) except (TypeError, ValueError): print(__doc__) else: server.serve()
python
Apache-2.0
d2d519666250324478bdccd7ccd65206a9110bf4
2026-01-05T07:13:20.041560Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/main.py
main.py
import os import sys import torch from tools import train_net, test_net from utils import parser os.environ["CUDA_VISIBLE_DEVICES"] = '0,1' def main(): args = parser.get_args() parser.setup(args) print(args) if args.test: test_net(args) else: train_net(args) if __name__ == '__main__': main()
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/tools/runner.py
tools/runner.py
import numpy as np import torch import torch.nn as nn from scipy import stats from tools import builder, helper from utils import misc import time import pickle def train_net(args): print('Trainer start ... ') # build dataset train_dataset, test_dataset = builder.dataset_builder(args) train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=args.bs_train, shuffle=True, num_workers=int(args.workers), pin_memory=True, worker_init_fn=misc.worker_init_fn) test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=args.bs_test, shuffle=False, num_workers=int(args.workers), pin_memory=True) # build model base_model, psnet_model, decoder, regressor_delta = builder.model_builder(args) # CUDA global use_gpu use_gpu = torch.cuda.is_available() if use_gpu: base_model = base_model.cuda() psnet_model = psnet_model.cuda() decoder = decoder.cuda() regressor_delta = regressor_delta.cuda() torch.backends.cudnn.benchmark = True optimizer, scheduler = builder.build_opti_sche(base_model, psnet_model, decoder, regressor_delta, args) start_epoch = 0 global epoch_best_tas, pred_tious_best_5, pred_tious_best_75, epoch_best_aqa, rho_best, L2_min, RL2_min epoch_best_tas = 0 pred_tious_best_5 = 0 pred_tious_best_75 = 0 epoch_best_aqa = 0 rho_best = 0 L2_min = 1000 RL2_min = 1000 # resume ckpts if args.resume: start_epoch, epoch_best_aqa, rho_best, L2_min, RL2_min = builder.resume_train(base_model, psnet_model, decoder, regressor_delta, optimizer, args) print('resume ckpts @ %d epoch(rho = %.4f, L2 = %.4f , RL2 = %.4f)' % (start_epoch - 1, rho_best, L2_min, RL2_min)) # DP base_model = nn.DataParallel(base_model) psnet_model = nn.DataParallel(psnet_model) decoder = nn.DataParallel(decoder) regressor_delta = nn.DataParallel(regressor_delta) # loss mse = nn.MSELoss().cuda() bce = nn.BCELoss().cuda() # training phase for epoch in range(start_epoch, args.max_epoch): pred_tious_5 = [] pred_tious_75 = [] true_scores = [] pred_scores = [] base_model.train() psnet_model.train() decoder.train() regressor_delta.train() if args.fix_bn: base_model.apply(misc.fix_bn) for idx, (data, target) in enumerate(train_dataloader): # num_iter += 1 opti_flag = True # video_1 is query and video_2 is exemplar video_1 = data['video'].float().cuda() video_2 = target['video'].float().cuda() label_1_tas = data['transits'].float().cuda() + 1 label_2_tas = target['transits'].float().cuda() + 1 label_1_score = data['final_score'].float().reshape(-1, 1).cuda() label_2_score = target['final_score'].float().reshape(-1, 1).cuda() # forward helper.network_forward_train(base_model, psnet_model, decoder, regressor_delta, pred_scores, video_1, label_1_score, video_2, label_2_score, mse, optimizer, opti_flag, epoch, idx+1, len(train_dataloader), args, label_1_tas, label_2_tas, bce, pred_tious_5, pred_tious_75) true_scores.extend(data['final_score'].numpy()) # evaluation results pred_scores = np.array(pred_scores) true_scores = np.array(true_scores) rho, p = stats.spearmanr(pred_scores, true_scores) L2 = np.power(pred_scores - true_scores, 2).sum() / true_scores.shape[0] RL2 = np.power((pred_scores - true_scores) / (true_scores.max() - true_scores.min()), 2).sum() / true_scores.shape[0] pred_tious_mean_5 = sum(pred_tious_5) / len(train_dataset) pred_tious_mean_75 = sum(pred_tious_75) / len(train_dataset) print('[Training] EPOCH: %d, tIoU_5: %.4f, tIoU_75: %.4f' % (epoch, pred_tious_mean_5, pred_tious_mean_75)) print('[Training] EPOCH: %d, correlation: %.4f, L2: %.4f, RL2: %.4f, lr1: %.4f, lr2: %.4f'%(epoch, rho, L2, RL2, optimizer.param_groups[0]['lr'], optimizer.param_groups[1]['lr'])) validate(base_model, psnet_model, decoder, regressor_delta, test_dataloader, epoch, optimizer, args) helper.save_checkpoint(base_model, psnet_model, decoder, regressor_delta, optimizer, epoch, epoch_best_aqa, rho_best, L2_min, RL2_min, 'last', args) print('[TEST] EPOCH: %d, best correlation: %.6f, best L2: %.6f, best RL2: %.6f' % (epoch_best_aqa, rho_best, L2_min, RL2_min)) print('[TEST] EPOCH: %d, best tIoU_5: %.6f, best tIoU_75: %.6f' % (epoch_best_tas, pred_tious_best_5, pred_tious_best_75)) # scheduler lr if scheduler is not None: scheduler.step() def validate(base_model, psnet_model, decoder, regressor_delta, test_dataloader, epoch, optimizer, args): print("Start validating epoch {}".format(epoch)) global use_gpu global epoch_best_aqa, rho_best, L2_min, RL2_min, epoch_best_tas, pred_tious_best_5, pred_tious_best_75 true_scores = [] pred_scores = [] pred_tious_test_5 = [] pred_tious_test_75 = [] base_model.eval() psnet_model.eval() decoder.eval() regressor_delta.eval() batch_num = len(test_dataloader) with torch.no_grad(): datatime_start = time.time() for batch_idx, (data, target) in enumerate(test_dataloader, 0): datatime = time.time() - datatime_start start = time.time() video_1 = data['video'].float().cuda() video_2_list = [item['video'].float().cuda() for item in target] label_1_tas = data['transits'].float().cuda() + 1 label_2_tas_list = [item['transits'].float().cuda() + 1 for item in target] label_2_score_list = [item['final_score'].float().reshape(-1, 1).cuda() for item in target] helper.network_forward_test(base_model, psnet_model, decoder, regressor_delta, pred_scores, video_1, video_2_list, label_2_score_list, args, label_1_tas, label_2_tas_list, pred_tious_test_5, pred_tious_test_75) batch_time = time.time() - start if batch_idx % args.print_freq == 0: print('[TEST][%d/%d][%d/%d] \t Batch_time %.2f \t Data_time %.2f' % (epoch, args.max_epoch, batch_idx, batch_num, batch_time, datatime)) datatime_start = time.time() true_scores.extend(data['final_score'].numpy()) # evaluation results pred_scores = np.array(pred_scores) true_scores = np.array(true_scores) rho, p = stats.spearmanr(pred_scores, true_scores) L2 = np.power(pred_scores - true_scores, 2).sum() / true_scores.shape[0] RL2 = np.power((pred_scores - true_scores) / (true_scores.max() - true_scores.min()), 2).sum() / true_scores.shape[0] pred_tious_test_mean_5 = sum(pred_tious_test_5) / (len(test_dataloader) * args.bs_test) pred_tious_test_mean_75 = sum(pred_tious_test_75) / (len(test_dataloader) * args.bs_test) if pred_tious_test_mean_5 > pred_tious_best_5: pred_tious_best_5 = pred_tious_test_mean_5 if pred_tious_test_mean_75 > pred_tious_best_75: pred_tious_best_75 = pred_tious_test_mean_75 epoch_best_tas = epoch print('[TEST] EPOCH: %d, tIoU_5: %.6f, tIoU_75: %.6f' % (epoch, pred_tious_best_5, pred_tious_best_75)) if L2_min > L2: L2_min = L2 if RL2_min > RL2: RL2_min = RL2 if rho > rho_best: rho_best = rho epoch_best_aqa = epoch print('-----New best found!-----') helper.save_outputs(pred_scores, true_scores, args) helper.save_checkpoint(base_model, psnet_model, decoder, regressor_delta, optimizer, epoch, epoch_best_aqa, rho_best, L2_min, RL2_min, 'last', args) print('[TEST] EPOCH: %d, correlation: %.6f, L2: %.6f, RL2: %.6f' % (epoch, rho, L2, RL2)) def test_net(args): print('Tester start ... ') train_dataset, test_dataset = builder.dataset_builder(args) test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=args.bs_test, shuffle=False, num_workers=int(args.workers), pin_memory=True) # build model base_model, psnet_model, decoder, regressor_delta = builder.model_builder(args) # load checkpoints builder.load_model(base_model, psnet_model, decoder, regressor_delta, args) # CUDA global use_gpu use_gpu = torch.cuda.is_available() if use_gpu: base_model = base_model.cuda() psnet_model = psnet_model.cuda() decoder = decoder.cuda() regressor_delta = regressor_delta.cuda() torch.backends.cudnn.benchmark = True # DP base_model = nn.DataParallel(base_model) psnet_model = nn.DataParallel(psnet_model) decoder = nn.DataParallel(decoder) regressor_delta = nn.DataParallel(regressor_delta) test(base_model, psnet_model, decoder, regressor_delta, test_dataloader, args) def test(base_model, psnet_model, decoder, regressor_delta, test_dataloader, args): global use_gpu global epoch_best_aqa, rho_best, L2_min, RL2_min global epoch_best_tas, pred_tious_best_5, pred_tious_best_75 true_scores = [] pred_scores = [] pred_tious_test_5 = [] pred_tious_test_75 = [] base_model.eval() psnet_model.eval() decoder.eval() regressor_delta.eval() batch_num = len(test_dataloader) with torch.no_grad(): datatime_start = time.time() for batch_idx, (data, target) in enumerate(test_dataloader, 0): datatime = time.time() - datatime_start start = time.time() video_1 = data['video'].float().cuda() video_2_list = [item['video'].float().cuda() for item in target] label_1_tas = data['transits'].float().cuda() + 1 label_2_tas_list = [item['transits'].float().cuda() + 1 for item in target] label_2_score_list = [item['final_score'].float().reshape(-1, 1).cuda() for item in target] helper.network_forward_test(base_model, psnet_model, decoder, regressor_delta, pred_scores, video_1, video_2_list, label_2_score_list, args, label_1_tas, label_2_tas_list, pred_tious_test_5, pred_tious_test_75) batch_time = time.time() - start if batch_idx % args.print_freq == 0: print('[TEST][%d/%d] \t Batch_time %.2f \t Data_time %.2f' % (batch_idx, batch_num, batch_time, datatime)) datatime_start = time.time() true_scores.extend(data['final_score'].numpy()) # evaluation results pred_scores = np.array(pred_scores) true_scores = np.array(true_scores) rho, p = stats.spearmanr(pred_scores, true_scores) L2 = np.power(pred_scores - true_scores, 2).sum() / true_scores.shape[0] RL2 = np.power((pred_scores - true_scores) / (true_scores.max() - true_scores.min()), 2).sum() / \ true_scores.shape[0] pred_tious_test_mean_5 = sum(pred_tious_test_5) / (len(test_dataloader) * args.bs_test) pred_tious_test_mean_75 = sum(pred_tious_test_75) / (len(test_dataloader) * args.bs_test) print('[TEST] tIoU_5: %.6f, tIoU_75: %.6f' % (pred_tious_test_mean_5, pred_tious_test_mean_75)) print('[TEST] correlation: %.6f, L2: %.6f, RL2: %.6f' % (rho, L2, RL2))
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/tools/helper.py
tools/helper.py
import os, sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR, "../")) import torch import torch.nn as nn import time import numpy as np from utils.misc import segment_iou, cal_tiou, seg_pool_1d, seg_pool_3d def network_forward_train(base_model, psnet_model, decoder, regressor_delta, pred_scores, video_1, label_1_score, video_2, label_2_score, mse, optimizer, opti_flag, epoch, batch_idx, batch_num, args, label_1_tas, label_2_tas, bce, pred_tious_5, pred_tious_75): start = time.time() optimizer.zero_grad() ############# I3D featrue ############# com_feature_12, com_feamap_12 = base_model(video_1, video_2) video_1_fea = com_feature_12[:,:,:com_feature_12.shape[2] // 2] video_2_fea = com_feature_12[:,:,com_feature_12.shape[2] // 2:] video_1_feamap = com_feamap_12[:,:,:com_feature_12.shape[2] // 2] video_2_feamap = com_feamap_12[:,:,com_feature_12.shape[2] // 2:] N,T,C,T_t,H_t,W_t = video_1_feamap.size() video_1_feamap = video_1_feamap.mean(-3) video_2_feamap = video_2_feamap.mean(-3) video_1_feamap_re = video_1_feamap.reshape(-1, T, C) video_2_feamap_re = video_2_feamap.reshape(-1, T, C) ############# Procedure Segmentation ############# com_feature_12_u = torch.cat((video_1_fea, video_2_fea), 0) com_feamap_12_u = torch.cat((video_1_feamap_re, video_2_feamap_re), 0) u_fea_96, transits_pred = psnet_model(com_feature_12_u) u_feamap_96, transits_pred_map = psnet_model(com_feamap_12_u) u_feamap_96 = u_feamap_96.reshape(2*N, u_feamap_96.shape[1], u_feamap_96.shape[2], H_t, W_t) label_12_tas = torch.cat((label_1_tas, label_2_tas), 0) label_12_pad = torch.zeros(transits_pred.size()) for bs in range(transits_pred.shape[0]): label_12_pad[bs, int(label_12_tas[bs, 0]), 0] = 1 label_12_pad[bs, int(label_12_tas[bs, -1]), -1] = 1 loss_tas = bce(transits_pred, label_12_pad.cuda()) num = round(transits_pred.shape[1] / transits_pred.shape[-1]) transits_st_ed = torch.zeros(label_12_tas.size()) for bs in range(transits_pred.shape[0]): for i in range(transits_pred.shape[-1]): transits_st_ed[bs, i] = transits_pred[bs, i * num: (i + 1) * num, i].argmax(0).cpu().item() + i * num label_1_tas_pred = transits_st_ed[:transits_st_ed.shape[0] // 2] label_2_tas_pred = transits_st_ed[transits_st_ed.shape[0] // 2:] ############# Procedure-aware Cross-attention ############# u_fea_96_1 = u_fea_96[:u_fea_96.shape[0] // 2].transpose(1, 2) u_fea_96_2 = u_fea_96[u_fea_96.shape[0] // 2:].transpose(1, 2) u_feamap_96_1 = u_feamap_96[:u_feamap_96.shape[0] // 2].transpose(1, 2) u_feamap_96_2 = u_feamap_96[u_feamap_96.shape[0] // 2:].transpose(1, 2) if epoch / args.max_epoch <= args.prob_tas_threshold: video_1_segs = [] for bs_1 in range(u_fea_96_1.shape[0]): video_1_st = int(label_1_tas[bs_1][0].item()) video_1_ed = int(label_1_tas[bs_1][1].item()) video_1_segs.append(seg_pool_1d(u_fea_96_1[bs_1].unsqueeze(0), video_1_st, video_1_ed, args.fix_size)) video_1_segs = torch.cat(video_1_segs, 0).transpose(1, 2) video_2_segs = [] for bs_2 in range(u_fea_96_2.shape[0]): video_2_st = int(label_2_tas[bs_2][0].item()) video_2_ed = int(label_2_tas[bs_2][1].item()) video_2_segs.append(seg_pool_1d(u_fea_96_2[bs_2].unsqueeze(0), video_2_st, video_2_ed, args.fix_size)) video_2_segs = torch.cat(video_2_segs, 0).transpose(1, 2) video_1_segs_map = [] for bs_1 in range(u_feamap_96_1.shape[0]): video_1_st = int(label_1_tas[bs_1][0].item()) video_1_ed = int(label_1_tas[bs_1][1].item()) video_1_segs_map.append(seg_pool_3d(u_feamap_96_1[bs_1].unsqueeze(0), video_1_st, video_1_ed, args.fix_size)) video_1_segs_map = torch.cat(video_1_segs_map, 0) video_1_segs_map = video_1_segs_map.reshape(video_1_segs_map.shape[0], video_1_segs_map.shape[1], video_1_segs_map.shape[2], -1).transpose(2, 3) video_1_segs_map = torch.cat([video_1_segs_map[:,:,:,i] for i in range(video_1_segs_map.shape[-1])], 2).transpose(1, 2) video_2_segs_map = [] for bs_2 in range(u_fea_96_2.shape[0]): video_2_st = int(label_2_tas[bs_2][0].item()) video_2_ed = int(label_2_tas[bs_2][1].item()) video_2_segs_map.append(seg_pool_3d(u_feamap_96_2[bs_2].unsqueeze(0), video_2_st, video_2_ed, args.fix_size)) video_2_segs_map = torch.cat(video_2_segs_map, 0) video_2_segs_map = video_2_segs_map.reshape(video_2_segs_map.shape[0], video_2_segs_map.shape[1], video_2_segs_map.shape[2], -1).transpose(2, 3) video_2_segs_map = torch.cat([video_2_segs_map[:, :, :, i] for i in range(video_2_segs_map.shape[-1])], 2).transpose(1, 2) else: video_1_segs = [] for bs_1 in range(u_fea_96_1.shape[0]): video_1_st = int(label_1_tas_pred[bs_1][0].item()) video_1_ed = int(label_1_tas_pred[bs_1][1].item()) if video_1_st == 0: video_1_st = 1 if video_1_ed == 0: video_1_ed = 1 video_1_segs.append(seg_pool_1d(u_fea_96_1[bs_1].unsqueeze(0), video_1_st, video_1_ed, args.fix_size)) video_1_segs = torch.cat(video_1_segs, 0).transpose(1, 2) video_2_segs = [] for bs_2 in range(u_fea_96_2.shape[0]): video_2_st = int(label_2_tas_pred[bs_2][0].item()) video_2_ed = int(label_2_tas_pred[bs_2][1].item()) if video_2_st == 0: video_2_st = 1 if video_2_ed == 0: video_2_ed = 1 video_2_segs.append(seg_pool_1d(u_fea_96_2[bs_2].unsqueeze(0), video_2_st, video_2_ed, args.fix_size)) video_2_segs = torch.cat(video_2_segs, 0).transpose(1, 2) video_1_segs_map = [] for bs_1 in range(u_feamap_96_1.shape[0]): video_1_st = int(label_1_tas_pred[bs_1][0].item()) video_1_ed = int(label_1_tas_pred[bs_1][1].item()) if video_1_st == 0: video_1_st = 1 if video_1_ed == 0: video_1_ed = 1 video_1_segs_map.append(seg_pool_3d(u_feamap_96_1[bs_1].unsqueeze(0), video_1_st, video_1_ed, args.fix_size)) video_1_segs_map = torch.cat(video_1_segs_map, 0) video_1_segs_map = video_1_segs_map.reshape(video_1_segs_map.shape[0], video_1_segs_map.shape[1], video_1_segs_map.shape[2], -1).transpose(2, 3) video_1_segs_map = torch.cat([video_1_segs_map[:, :, :, i] for i in range(video_1_segs_map.shape[-1])], 2).transpose(1, 2) video_2_segs_map = [] for bs_2 in range(u_fea_96_2.shape[0]): video_2_st = int(label_2_tas_pred[bs_2][0].item()) video_2_ed = int(label_2_tas_pred[bs_2][1].item()) if video_2_st == 0: video_2_st = 1 if video_2_ed == 0: video_2_ed = 1 video_2_segs_map.append(seg_pool_3d(u_feamap_96_2[bs_2].unsqueeze(0), video_2_st, video_2_ed, args.fix_size)) video_2_segs_map = torch.cat(video_2_segs_map, 0) video_2_segs_map = video_2_segs_map.reshape(video_2_segs_map.shape[0], video_2_segs_map.shape[1], video_2_segs_map.shape[2], -1).transpose(2, 3) video_2_segs_map = torch.cat([video_2_segs_map[:, :, :, i] for i in range(video_2_segs_map.shape[-1])], 2).transpose(1, 2) decoder_video_12_map_list = [] decoder_video_21_map_list = [] for i in range(args.step_num): decoder_video_12_map = decoder(video_1_segs[:, i*args.fix_size:(i+1)*args.fix_size,:], video_2_segs_map[:, i*args.fix_size*H_t*W_t:(i+1)*args.fix_size*H_t*W_t,:]) # N,15,256/64 decoder_video_21_map = decoder(video_2_segs[:, i*args.fix_size:(i+1)*args.fix_size,:], video_1_segs_map[:, i*args.fix_size*H_t*W_t:(i+1)*args.fix_size*H_t*W_t,:]) # N,15,256/64 decoder_video_12_map_list.append(decoder_video_12_map) decoder_video_21_map_list.append(decoder_video_21_map) decoder_video_12_map = torch.cat(decoder_video_12_map_list, 1) decoder_video_21_map = torch.cat(decoder_video_21_map_list, 1) ############# Fine-grained Contrastive Regression ############# decoder_12_21 = torch.cat((decoder_video_12_map, decoder_video_21_map), 0) delta = regressor_delta(decoder_12_21) delta = delta.mean(1) loss_aqa = mse(delta[:delta.shape[0]//2], (label_1_score - label_2_score)) \ + mse(delta[delta.shape[0]//2:], (label_2_score - label_1_score)) loss = loss_aqa + loss_tas loss.backward() optimizer.step() end = time.time() batch_time = end - start score = (delta[:delta.shape[0]//2].detach() + label_2_score) pred_scores.extend([i.item() for i in score]) tIoU_results = [] for bs in range(transits_pred.shape[0] // 2): tIoU_results.append(segment_iou(np.array(label_12_tas.squeeze(-1).cpu())[bs], np.array(transits_st_ed.squeeze(-1).cpu())[bs], args)) tiou_thresholds = np.array([0.5, 0.75]) tIoU_correct_per_thr = cal_tiou(tIoU_results, tiou_thresholds) Batch_tIoU_5 = tIoU_correct_per_thr[0] Batch_tIoU_75 = tIoU_correct_per_thr[1] pred_tious_5.extend([Batch_tIoU_5]) pred_tious_75.extend([Batch_tIoU_75]) if batch_idx % args.print_freq == 0: print('[Training][%d/%d][%d/%d] \t Batch_time: %.2f \t Batch_loss: %.4f \t ' 'lr1 : %0.5f \t lr2 : %0.5f' % (epoch, args.max_epoch, batch_idx, batch_num, batch_time, loss.item(), optimizer.param_groups[0]['lr'], optimizer.param_groups[1]['lr'])) def network_forward_test(base_model, psnet_model, decoder, regressor_delta, pred_scores, video_1, video_2_list, label_2_score_list, args, label_1_tas, label_2_tas_list, pred_tious_test_5, pred_tious_test_75): score = 0 tIoU_results = [] for video_2, label_2_score, label_2_tas in zip(video_2_list, label_2_score_list, label_2_tas_list): ############# I3D featrue ############# com_feature_12, com_feamap_12 = base_model(video_1, video_2) video_1_fea = com_feature_12[:, :, :com_feature_12.shape[2] // 2] video_2_fea = com_feature_12[:, :, com_feature_12.shape[2] // 2:] video_1_feamap = com_feamap_12[:, :, :com_feature_12.shape[2] // 2] video_2_feamap = com_feamap_12[:, :, com_feature_12.shape[2] // 2:] N, T, C, T_t, H_t, W_t = video_1_feamap.size() video_1_feamap = video_1_feamap.mean(-3) video_2_feamap = video_2_feamap.mean(-3) video_1_feamap_re = video_1_feamap.reshape(-1, T, C) video_2_feamap_re = video_2_feamap.reshape(-1, T, C) ############# Procedure Segmentation ############# com_feature_12_u = torch.cat((video_1_fea, video_2_fea), 0) com_feamap_12_u = torch.cat((video_1_feamap_re, video_2_feamap_re), 0) u_fea_96, transits_pred = psnet_model(com_feature_12_u) u_feamap_96, transits_pred_map = psnet_model(com_feamap_12_u) u_feamap_96 = u_feamap_96.reshape(2 * N, u_feamap_96.shape[1], u_feamap_96.shape[2], H_t, W_t) label_12_tas = torch.cat((label_1_tas, label_2_tas), 0) num = round(transits_pred.shape[1] / transits_pred.shape[-1]) transits_st_ed = torch.zeros(label_12_tas.size()) for bs in range(transits_pred.shape[0]): for i in range(transits_pred.shape[-1]): transits_st_ed[bs, i] = transits_pred[bs, i * num: (i + 1) * num, i].argmax(0).cpu().item() + i * num label_1_tas_pred = transits_st_ed[:transits_st_ed.shape[0] // 2] label_2_tas_pred = transits_st_ed[transits_st_ed.shape[0] // 2:] ############# Procedure-aware Cross-attention ############# u_fea_96_1 = u_fea_96[:u_fea_96.shape[0] // 2].transpose(1, 2) u_fea_96_2 = u_fea_96[u_fea_96.shape[0] // 2:].transpose(1, 2) u_feamap_96_1 = u_feamap_96[:u_feamap_96.shape[0] // 2].transpose(1, 2) u_feamap_96_2 = u_feamap_96[u_feamap_96.shape[0] // 2:].transpose(1, 2) video_1_segs = [] for bs_1 in range(u_fea_96_1.shape[0]): video_1_st = int(label_1_tas_pred[bs_1][0].item()) video_1_ed = int(label_1_tas_pred[bs_1][1].item()) if video_1_st == 0: video_1_st = 1 if video_1_ed == 0: video_1_ed = 1 video_1_segs.append(seg_pool_1d(u_fea_96_1[bs_1].unsqueeze(0), video_1_st, video_1_ed, args.fix_size)) video_1_segs = torch.cat(video_1_segs, 0).transpose(1, 2) video_2_segs = [] for bs_2 in range(u_fea_96_2.shape[0]): video_2_st = int(label_2_tas_pred[bs_2][0].item()) video_2_ed = int(label_2_tas_pred[bs_2][1].item()) if video_2_st == 0: video_2_st = 1 if video_2_ed == 0: video_2_ed = 1 video_2_segs.append(seg_pool_1d(u_fea_96_2[bs_2].unsqueeze(0), video_2_st, video_2_ed, args.fix_size)) video_2_segs = torch.cat(video_2_segs, 0).transpose(1, 2) video_1_segs_map = [] for bs_1 in range(u_feamap_96_1.shape[0]): video_1_st = int(label_1_tas_pred[bs_1][0].item()) video_1_ed = int(label_1_tas_pred[bs_1][1].item()) if video_1_st == 0: video_1_st = 1 if video_1_ed == 0: video_1_ed = 1 video_1_segs_map.append(seg_pool_3d(u_feamap_96_1[bs_1].unsqueeze(0), video_1_st, video_1_ed, args.fix_size)) video_1_segs_map = torch.cat(video_1_segs_map, 0) video_1_segs_map = video_1_segs_map.reshape(video_1_segs_map.shape[0], video_1_segs_map.shape[1], video_1_segs_map.shape[2], -1).transpose(2, 3) video_1_segs_map = torch.cat([video_1_segs_map[:, :, :, i] for i in range(video_1_segs_map.shape[-1])], 2).transpose(1, 2) video_2_segs_map = [] for bs_2 in range(u_fea_96_2.shape[0]): video_2_st = int(label_2_tas_pred[bs_2][0].item()) video_2_ed = int(label_2_tas_pred[bs_2][1].item()) if video_2_st == 0: video_2_st = 1 if video_2_ed == 0: video_2_ed = 1 video_2_segs_map.append(seg_pool_3d(u_feamap_96_2[bs_2].unsqueeze(0), video_2_st, video_2_ed, args.fix_size)) video_2_segs_map = torch.cat(video_2_segs_map, 0) video_2_segs_map = video_2_segs_map.reshape(video_2_segs_map.shape[0], video_2_segs_map.shape[1], video_2_segs_map.shape[2], -1).transpose(2, 3) video_2_segs_map = torch.cat([video_2_segs_map[:, :, :, i] for i in range(video_2_segs_map.shape[-1])], 2).transpose(1, 2) decoder_video_12_map_list = [] decoder_video_21_map_list = [] for i in range(args.step_num): decoder_video_12_map = decoder(video_1_segs[:, i * args.fix_size:(i + 1) * args.fix_size, :], video_2_segs_map[:, i * args.fix_size * H_t * W_t:(i + 1) * args.fix_size * H_t * W_t, :]) decoder_video_21_map = decoder(video_2_segs[:, i * args.fix_size:(i + 1) * args.fix_size, :], video_1_segs_map[:, i * args.fix_size * H_t * W_t:(i + 1) * args.fix_size * H_t * W_t, :]) decoder_video_12_map_list.append(decoder_video_12_map) decoder_video_21_map_list.append(decoder_video_21_map) decoder_video_12_map = torch.cat(decoder_video_12_map_list, 1) decoder_video_21_map = torch.cat(decoder_video_21_map_list, 1) ############# Fine-grained Contrastive Regression ############# decoder_12_21 = torch.cat((decoder_video_12_map, decoder_video_21_map), 0) delta = regressor_delta(decoder_12_21) delta = delta.mean(1) score += (delta[:delta.shape[0]//2].detach() + label_2_score) for bs in range(transits_pred.shape[0] // 2): tIoU_results.append(segment_iou(np.array(label_12_tas.squeeze(-1).cpu())[bs], np.array(transits_st_ed.squeeze(-1).cpu())[bs], args)) pred_scores.extend([i.item() / len(video_2_list) for i in score]) tIoU_results_mean = [sum(tIoU_results) / len(tIoU_results)] tiou_thresholds = np.array([0.5, 0.75]) tIoU_correct_per_thr = cal_tiou(tIoU_results_mean, tiou_thresholds) pred_tious_test_5.extend([tIoU_correct_per_thr[0]]) pred_tious_test_75.extend([tIoU_correct_per_thr[1]]) def save_checkpoint(base_model, psnet_model, decoder, regressor_delta, optimizer, epoch, epoch_best_aqa, rho_best, L2_min, RL2_min, prefix, args): torch.save({ 'base_model': base_model.state_dict(), 'psnet_model': psnet_model.state_dict(), 'decoder': decoder.state_dict(), 'regressor_delta': regressor_delta.state_dict(), 'optimizer': optimizer.state_dict(), 'epoch': epoch, 'epoch_best_aqa': epoch_best_aqa, 'rho_best': rho_best, 'L2_min': L2_min, 'RL2_min': RL2_min, }, os.path.join(args.experiment_path, prefix + '.pth')) def save_outputs(pred_scores, true_scores, args): save_path_pred = os.path.join(args.experiment_path, 'pred.npy') save_path_true = os.path.join(args.experiment_path, 'true.npy') np.save(save_path_pred, pred_scores) np.save(save_path_true, true_scores)
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/tools/__init__.py
tools/__init__.py
from .runner import train_net, test_net
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/tools/builder.py
tools/builder.py
import os, sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR, "../")) import torch import torch.optim as optim from models import I3D_backbone from models.PS import PSNet from utils.misc import import_class from torchvideotransforms import video_transforms, volume_transforms from models import decoder_fuser from models import MLP_score def get_video_trans(): train_trans = video_transforms.Compose([ video_transforms.RandomHorizontalFlip(), video_transforms.Resize((200, 112)), video_transforms.RandomCrop(112), volume_transforms.ClipToTensor(), video_transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) test_trans = video_transforms.Compose([ video_transforms.Resize((200, 112)), video_transforms.CenterCrop(112), volume_transforms.ClipToTensor(), video_transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) return train_trans, test_trans def dataset_builder(args): train_trans, test_trans = get_video_trans() Dataset = import_class("datasets." + args.benchmark) train_dataset = Dataset(args, transform=train_trans, subset='train') test_dataset = Dataset(args, transform=test_trans, subset='test') return train_dataset, test_dataset def model_builder(args): base_model = I3D_backbone(I3D_class=400) base_model.load_pretrain(args.pretrained_i3d_weight) PSNet_model = PSNet(n_channels=9) Decoder_vit = decoder_fuser(dim=64, num_heads=8, num_layers=3) Regressor_delta = MLP_score(in_channel=64, out_channel=1) return base_model, PSNet_model, Decoder_vit, Regressor_delta def build_opti_sche(base_model, psnet_model, decoder, regressor_delta, args): if args.optimizer == 'Adam': optimizer = optim.Adam([ {'params': base_model.parameters(), 'lr': args.base_lr * args.lr_factor}, {'params': psnet_model.parameters()}, {'params': decoder.parameters()}, {'params': regressor_delta.parameters()} ], lr=args.base_lr, weight_decay=args.weight_decay) else: raise NotImplementedError() scheduler = None return optimizer, scheduler def resume_train(base_model, psnet_model, decoder, regressor_delta, optimizer, args): ckpt_path = os.path.join(args.experiment_path, 'last.pth') if not os.path.exists(ckpt_path): print('no checkpoint file from path %s...' % ckpt_path) return 0, 0, 0, 1000, 1000 print('Loading weights from %s...' % ckpt_path) # load state dict state_dict = torch.load(ckpt_path, map_location='cpu') # parameter resume of base model base_ckpt = {k.replace("module.", ""): v for k, v in state_dict['base_model'].items()} base_model.load_state_dict(base_ckpt) psnet_ckpt = {k.replace("module.", ""): v for k, v in state_dict['psnet_model'].items()} psnet_model.load_state_dict(psnet_ckpt) decoder_ckpt = {k.replace("module.", ""): v for k, v in state_dict['decoder'].items()} decoder.load_state_dict(decoder_ckpt) regressor_delta_ckpt = {k.replace("module.", ""): v for k, v in state_dict['regressor_delta'].items()} regressor_delta.load_state_dict(regressor_delta_ckpt) # optimizer optimizer.load_state_dict(state_dict['optimizer']) # parameter start_epoch = state_dict['epoch'] + 1 epoch_best_aqa = state_dict['epoch_best_aqa'] rho_best = state_dict['rho_best'] L2_min = state_dict['L2_min'] RL2_min = state_dict['RL2_min'] return start_epoch, epoch_best_aqa, rho_best, L2_min, RL2_min def load_model(base_model, psnet_model, decoder, regressor_delta, args): ckpt_path = args.ckpts if not os.path.exists(ckpt_path): raise NotImplementedError('no checkpoint file from path %s...' % ckpt_path) print('Loading weights from %s...' % ckpt_path) # load state dict state_dict = torch.load(ckpt_path,map_location='cpu') # parameter resume of base model base_ckpt = {k.replace("module.", ""): v for k, v in state_dict['base_model'].items()} base_model.load_state_dict(base_ckpt) psnet_model_ckpt = {k.replace("module.", ""): v for k, v in state_dict['psnet_model'].items()} psnet_model.load_state_dict(psnet_model_ckpt) decoder_ckpt = {k.replace("module.", ""): v for k, v in state_dict['decoder'].items()} decoder.load_state_dict(decoder_ckpt) regressor_delta_ckpt = {k.replace("module.", ""): v for k, v in state_dict['regressor_delta'].items()} regressor_delta.load_state_dict(regressor_delta_ckpt) epoch_best_aqa = state_dict['epoch_best_aqa'] rho_best = state_dict['rho_best'] L2_min = state_dict['L2_min'] RL2_min = state_dict['RL2_min'] print('ckpts @ %d epoch(rho = %.4f, L2 = %.4f , RL2 = %.4f)' % (epoch_best_aqa - 1, rho_best, L2_min, RL2_min)) return
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/data_preparation/data_process.py
data_preparation/data_process.py
import glob import os import subprocess video_dir = "./FINADiving" video_list = glob.glob(os.path.join(video_dir, "*.mp4")) base_dir = "./FINADiving_jpgs" save_dir = "./FINADiving_jpgs_256" #################### step 1: video2frames #################### for vid in video_list: vid_dir = vid.split("/")[-1][:-4] vid_dir_1 = os.path.join(base_dir, vid_dir) if not os.path.exists(vid_dir_1): os.mkdir(vid_dir_1) vid_dir_2 = vid_dir_1 + "/%05d.jpg" subprocess.call("ffmpeg -i %s -f image2 -qscale:v 2 %s" % (vid, vid_dir_2), shell=True) #################### step 2: frames resize #################### if base_dir is None: raise RuntimeError('please choose the base dir and save dir') video_list = os.listdir(base_dir) for video in video_list: save_path = os.path.join(save_dir, video) if not os.path.exists(save_path): os.mkdir(save_path) frame_list = sorted(os.listdir(os.path.join(base_dir,video))) for frame in frame_list: subprocess.call('ffmpeg -i %s -vf scale=-1:256 %s' % (os.path.join(base_dir, video, frame), os.path.join(save_dir, video, frame)), shell=True)
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/datasets/__init__.py
datasets/__init__.py
from .FineDiving_Pair import FineDiving_Pair_Dataset as FineDiving
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/datasets/FineDiving_Pair.py
datasets/FineDiving_Pair.py
import torch import numpy as np import os import pickle import random import glob from os.path import join from PIL import Image class FineDiving_Pair_Dataset(torch.utils.data.Dataset): def __init__(self, args, subset, transform): random.seed(args.seed) self.subset = subset self.transforms = transform self.random_choosing = args.random_choosing self.action_number_choosing = args.action_number_choosing self.length = args.frame_length self.voter_number = args.voter_number # file path self.data_root = args.data_root self.data_anno = self.read_pickle(args.label_path) with open(args.train_split, 'rb') as f: self.train_dataset_list = pickle.load(f) with open(args.test_split, 'rb') as f: self.test_dataset_list = pickle.load(f) self.action_number_dict = {} self.difficulties_dict = {} if self.subset == 'train': self.dataset = self.train_dataset_list else: self.dataset = self.test_dataset_list self.action_number_dict_test = {} self.difficulties_dict_test = {} self.choose_list = self.train_dataset_list.copy() if self.action_number_choosing: self.preprocess() self.check_exemplar_dict() def preprocess(self): for item in self.train_dataset_list: dive_number = self.data_anno.get(item)[0] if self.action_number_dict.get(dive_number) is None: self.action_number_dict[dive_number] = [] self.action_number_dict[dive_number].append(item) if self.subset == 'test': for item in self.test_dataset_list: dive_number = self.data_anno.get(item)[0] if self.action_number_dict_test.get(dive_number) is None: self.action_number_dict_test[dive_number] = [] self.action_number_dict_test[dive_number].append(item) def check_exemplar_dict(self): if self.subset == 'train': for key in sorted(list(self.action_number_dict.keys())): file_list = self.action_number_dict[key] for item in file_list: assert self.data_anno[item][0] == key if self.subset == 'test': for key in sorted(list(self.action_number_dict_test.keys())): file_list = self.action_number_dict_test[key] for item in file_list: assert self.data_anno[item][0] == key def load_video(self, video_file_name): image_list = sorted((glob.glob(os.path.join(self.data_root, video_file_name[0], str(video_file_name[1]), '*.jpg')))) start_frame = int(image_list[0].split("/")[-1][:-4]) end_frame = int(image_list[-1].split("/")[-1][:-4]) frame_list = np.linspace(start_frame, end_frame, self.length).astype(np.int) image_frame_idx = [frame_list[i] - start_frame for i in range(self.length)] video = [Image.open(image_list[image_frame_idx[i]]) for i in range(self.length)] frames_labels = [self.data_anno.get(video_file_name)[4][i] for i in image_frame_idx] frames_catogeries = list(set(frames_labels)) frames_catogeries.sort(key=frames_labels.index) transitions = [frames_labels.index(c) for c in frames_catogeries] return self.transforms(video), np.array([transitions[1]-1,transitions[-1]-1]), np.array(frames_labels) def read_pickle(self, pickle_path): with open(pickle_path,'rb') as f: pickle_data = pickle.load(f) return pickle_data def __getitem__(self, index): sample_1 = self.dataset[index] data = {} data['video'], data['transits'], data['frame_labels'] = self.load_video(sample_1) data['number'] = self.data_anno.get(sample_1)[0] data['final_score'] = self.data_anno.get(sample_1)[1] data['difficulty'] = self.data_anno.get(sample_1)[2] data['completeness'] = (data['final_score'] / data['difficulty']) # choose a exemplar if self.subset == 'train': # train phrase if self.action_number_choosing == True: file_list = self.action_number_dict[self.data_anno[sample_1][0]].copy() elif self.DD_choosing == True: file_list = self.difficulties_dict[self.data_anno[sample_1][2]].copy() else: # randomly file_list = self.train_dataset_list.copy() # exclude self if len(file_list) > 1: file_list.pop(file_list.index(sample_1)) # choosing one out idx = random.randint(0, len(file_list) - 1) sample_2 = file_list[idx] target = {} target['video'], target['transits'], target['frame_labels'] = self.load_video(sample_2) target['number'] = self.data_anno.get(sample_2)[0] target['final_score'] = self.data_anno.get(sample_2)[1] target['difficulty'] = self.data_anno.get(sample_2)[2] target['completeness'] = (target['final_score'] / target['difficulty']) return data, target else: # test phrase if self.action_number_choosing: train_file_list = self.action_number_dict[self.data_anno[sample_1][0]] random.shuffle(train_file_list) choosen_sample_list = train_file_list[:self.voter_number] elif self.DD_choosing: train_file_list = self.difficulties_dict[self.data_anno[sample_1][2]] random.shuffle(train_file_list) choosen_sample_list = train_file_list[:self.voter_number] else: # randomly train_file_list = self.choose_list random.shuffle(train_file_list) choosen_sample_list = train_file_list[:self.voter_number] target_list = [] for item in choosen_sample_list: tmp = {} tmp['video'], tmp['transits'], tmp['frame_labels'] = self.load_video(item) tmp['number'] = self.data_anno.get(item)[0] tmp['final_score'] = self.data_anno.get(item)[1] tmp['difficulty'] = self.data_anno.get(item)[2] tmp['completeness'] = (tmp['final_score'] / tmp['difficulty']) target_list.append(tmp) return data, target_list def __len__(self): return len(self.dataset)
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/models/vit_decoder.py
models/vit_decoder.py
import torch import torch.nn as nn from timm.models.layers import DropPath, trunc_normal_ import numpy as np class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class CrossAttention(nn.Module): def __init__(self, dim, out_dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.): super().__init__() self.num_heads = num_heads self.dim = dim self.out_dim = out_dim head_dim = out_dim // num_heads self.scale = qk_scale or head_dim ** -0.5 self.q_map = nn.Linear(dim, out_dim, bias=qkv_bias) self.k_map = nn.Linear(dim, out_dim, bias=qkv_bias) self.v_map = nn.Linear(dim, out_dim, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(out_dim, out_dim) self.proj_drop = nn.Dropout(proj_drop) def forward(self, q, v): B, N, _ = q.shape C = self.out_dim k = v NK = k.size(1) q = self.q_map(q).view(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) k = self.k_map(k).view(B, NK, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) v = self.v_map(v).view(B, NK, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class DecoderBlock(nn.Module): def __init__(self, dim, num_heads, dim_q=None, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm): super().__init__() dim_q = dim_q or dim self.norm_q = norm_layer(dim_q) self.norm_v = norm_layer(dim) self.attn = CrossAttention( dim, dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) def forward(self, q, v): q = q + self.drop_path(self.attn(self.norm_q(q), self.norm_v(v))) q = q + self.drop_path(self.mlp(self.norm2(q))) return q class decoder_fuser(nn.Module): def __init__(self, dim, num_heads, num_layers): super(decoder_fuser, self).__init__() model_list = [] for i in range(num_layers): model_list.append(DecoderBlock(dim, num_heads)) self.model = nn.ModuleList(model_list) def forward(self, q, v): for _layer in self.model: q = _layer(q, v) return q
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/models/Backbone.py
models/Backbone.py
import torch.nn as nn import torch from .i3d import I3D import logging class I3D_backbone(nn.Module): def __init__(self, I3D_class): super(I3D_backbone, self).__init__() print('Using I3D backbone') self.backbone = I3D(num_classes=I3D_class, modality='rgb', dropout_prob=0.5) def load_pretrain(self, I3D_ckpt_path): try: self.backbone.load_state_dict(torch.load(I3D_ckpt_path)) print('loading ckpt done') except: logging.info('Ckpt path {} do not exists'.format(I3D_ckpt_path)) pass def forward(self, video_1, video_2): total_video = torch.cat((video_1, video_2), 0) start_idx = list(range(0, 90, 10)) video_pack = torch.cat([total_video[:, :, i: i + 16] for i in start_idx]) total_feamap, total_feature = self.backbone(video_pack) Nt, C, T, H, W = total_feamap.size() total_feature = total_feature.reshape(len(start_idx), len(total_video), -1).transpose(0, 1) total_feamap = total_feamap.reshape(len(start_idx), len(total_video), C, T, H, W).transpose(0, 1) com_feature_12 = torch.cat( (total_feature[:total_feature.shape[0] // 2], total_feature[total_feature.shape[0] // 2:]), 2) com_feamap_12 = torch.cat( (total_feamap[:total_feamap.shape[0] // 2], total_feamap[total_feamap.shape[0] // 2:]), 2) return com_feature_12, com_feamap_12
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/models/i3d.py
models/i3d.py
import math import os import numpy as np import torch from torch.nn import ReplicationPad3d import torch.nn as nn def get_padding_shape(filter_shape, stride): def _pad_top_bottom(filter_dim, stride_val): pad_along = max(filter_dim - stride_val, 0) pad_top = pad_along // 2 pad_bottom = pad_along - pad_top return pad_top, pad_bottom padding_shape = [] for filter_dim, stride_val in zip(filter_shape, stride): pad_top, pad_bottom = _pad_top_bottom(filter_dim, stride_val) padding_shape.append(pad_top) padding_shape.append(pad_bottom) depth_top = padding_shape.pop(0) depth_bottom = padding_shape.pop(0) padding_shape.append(depth_top) padding_shape.append(depth_bottom) return tuple(padding_shape) def simplify_padding(padding_shapes): all_same = True padding_init = padding_shapes[0] for pad in padding_shapes[1:]: if pad != padding_init: all_same = False return all_same, padding_init class Unit3Dpy(torch.nn.Module): def __init__(self, in_channels, out_channels, kernel_size=(1, 1, 1), stride=(1, 1, 1), activation='relu', padding='SAME', use_bias=False, use_bn=True): super(Unit3Dpy, self).__init__() self.padding = padding self.activation = activation self.use_bn = use_bn if padding == 'SAME': padding_shape = get_padding_shape(kernel_size, stride) simplify_pad, pad_size = simplify_padding(padding_shape) self.simplify_pad = simplify_pad elif padding == 'VALID': padding_shape = 0 else: raise ValueError( 'padding should be in [VALID|SAME] but got {}'.format(padding)) if padding == 'SAME': if not simplify_pad: self.pad = torch.nn.ConstantPad3d(padding_shape, 0) self.conv3d = torch.nn.Conv3d( in_channels, out_channels, kernel_size, stride=stride, bias=use_bias) else: self.conv3d = torch.nn.Conv3d( in_channels, out_channels, kernel_size, stride=stride, padding=pad_size, bias=use_bias) elif padding == 'VALID': self.conv3d = torch.nn.Conv3d( in_channels, out_channels, kernel_size, padding=padding_shape, stride=stride, bias=use_bias) else: raise ValueError( 'padding should be in [VALID|SAME] but got {}'.format(padding)) if self.use_bn: self.batch3d = torch.nn.BatchNorm3d(out_channels) if activation == 'relu': self.activation = torch.nn.functional.relu def forward(self, inp): if self.padding == 'SAME' and self.simplify_pad is False: inp = self.pad(inp) out = self.conv3d(inp) if self.use_bn: out = self.batch3d(out) if self.activation is not None: out = torch.nn.functional.relu(out) return out class MaxPool3dTFPadding(torch.nn.Module): def __init__(self, kernel_size, stride=None, padding='SAME'): super(MaxPool3dTFPadding, self).__init__() if padding == 'SAME': padding_shape = get_padding_shape(kernel_size, stride) self.padding_shape = padding_shape self.pad = torch.nn.ConstantPad3d(padding_shape, 0) self.pool = torch.nn.MaxPool3d(kernel_size, stride, ceil_mode=True) def forward(self, inp): inp = self.pad(inp) out = self.pool(inp) return out class Mixed(torch.nn.Module): def __init__(self, in_channels, out_channels): super(Mixed, self).__init__() # Branch 0 self.branch_0 = Unit3Dpy( in_channels, out_channels[0], kernel_size=(1, 1, 1)) # Branch 1 branch_1_conv1 = Unit3Dpy( in_channels, out_channels[1], kernel_size=(1, 1, 1)) branch_1_conv2 = Unit3Dpy( out_channels[1], out_channels[2], kernel_size=(3, 3, 3)) self.branch_1 = torch.nn.Sequential(branch_1_conv1, branch_1_conv2) # Branch 2 branch_2_conv1 = Unit3Dpy( in_channels, out_channels[3], kernel_size=(1, 1, 1)) branch_2_conv2 = Unit3Dpy( out_channels[3], out_channels[4], kernel_size=(3, 3, 3)) self.branch_2 = torch.nn.Sequential(branch_2_conv1, branch_2_conv2) # Branch3 branch_3_pool = MaxPool3dTFPadding( kernel_size=(3, 3, 3), stride=(1, 1, 1), padding='SAME') branch_3_conv2 = Unit3Dpy( in_channels, out_channels[5], kernel_size=(1, 1, 1)) self.branch_3 = torch.nn.Sequential(branch_3_pool, branch_3_conv2) def forward(self, inp): out_0 = self.branch_0(inp) out_1 = self.branch_1(inp) out_2 = self.branch_2(inp) out_3 = self.branch_3(inp) out = torch.cat((out_0, out_1, out_2, out_3), 1) return out class I3D(torch.nn.Module): def __init__(self, num_classes, modality='rgb', dropout_prob=0, name='inception'): super(I3D, self).__init__() self.name = name self.num_classes = num_classes if modality == 'rgb': in_channels = 3 elif modality == 'flow': in_channels = 2 else: raise ValueError( '{} not among known modalities [rgb|flow]'.format(modality)) self.modality = modality conv3d_1a_7x7 = Unit3Dpy( out_channels=64, in_channels=in_channels, kernel_size=(7, 7, 7), stride=(2, 2, 2), padding='SAME') # 1st conv-pool self.conv3d_1a_7x7 = conv3d_1a_7x7 self.maxPool3d_2a_3x3 = MaxPool3dTFPadding( kernel_size=(1, 3, 3), stride=(1, 2, 2), padding='SAME') # conv conv conv3d_2b_1x1 = Unit3Dpy( out_channels=64, in_channels=64, kernel_size=(1, 1, 1), padding='SAME') self.conv3d_2b_1x1 = conv3d_2b_1x1 conv3d_2c_3x3 = Unit3Dpy( out_channels=192, in_channels=64, kernel_size=(3, 3, 3), padding='SAME') self.conv3d_2c_3x3 = conv3d_2c_3x3 self.maxPool3d_3a_3x3 = MaxPool3dTFPadding( kernel_size=(1, 3, 3), stride=(1, 2, 2), padding='SAME') # Mixed_3b self.mixed_3b = Mixed(192, [64, 96, 128, 16, 32, 32]) self.mixed_3c = Mixed(256, [128, 128, 192, 32, 96, 64]) self.maxPool3d_4a_3x3 = MaxPool3dTFPadding( kernel_size=(3, 3, 3), stride=(2, 2, 2), padding='SAME') # Mixed 4 self.mixed_4b = Mixed(480, [192, 96, 208, 16, 48, 64]) self.mixed_4c = Mixed(512, [160, 112, 224, 24, 64, 64]) self.mixed_4d = Mixed(512, [128, 128, 256, 24, 64, 64]) self.mixed_4e = Mixed(512, [112, 144, 288, 32, 64, 64]) self.mixed_4f = Mixed(528, [256, 160, 320, 32, 128, 128]) self.maxPool3d_5a_2x2 = MaxPool3dTFPadding( kernel_size=(2, 2, 2), stride=(2, 2, 2), padding='SAME') # Mixed 5 self.mixed_5b = Mixed(832, [256, 160, 320, 32, 128, 128]) self.mixed_5c = Mixed(832, [384, 192, 384, 48, 128, 128]) # self.avg_pool = torch.nn.AvgPool3d((2, 7, 7), (1, 1, 1)) self.avg_pool = torch.nn.AvgPool3d((2, 4, 4), (1, 1, 1)) self.dropout = torch.nn.Dropout(dropout_prob) self.conv3d_0c_1x1 = Unit3Dpy( in_channels=1024, out_channels=self.num_classes, kernel_size=(1, 1, 1), activation='None', use_bias=True, use_bn=False) self.softmax = torch.nn.Softmax(1) def forward(self, inp): out = self.conv3d_1a_7x7(inp) out = self.maxPool3d_2a_3x3(out) out = self.conv3d_2b_1x1(out) out = self.conv3d_2c_3x3(out) out = self.maxPool3d_3a_3x3(out) out = self.mixed_3b(out) out = self.mixed_3c(out) out = self.maxPool3d_4a_3x3(out) out = self.mixed_4b(out) out = self.mixed_4c(out) out = self.mixed_4d(out) out = self.mixed_4e(out) out = self.mixed_4f(out) out = self.maxPool3d_5a_2x2(out) out = self.mixed_5b(out) out = self.mixed_5c(out) feature = self.avg_pool(out) return out, feature def load_tf_weights(self, sess): state_dict = {} if self.modality == 'rgb': prefix = 'RGB/inception_i3d' elif self.modality == 'flow': prefix = 'Flow/inception_i3d' load_conv3d(state_dict, 'conv3d_1a_7x7', sess, os.path.join(prefix, 'Conv3d_1a_7x7')) load_conv3d(state_dict, 'conv3d_2b_1x1', sess, os.path.join(prefix, 'Conv3d_2b_1x1')) load_conv3d(state_dict, 'conv3d_2c_3x3', sess, os.path.join(prefix, 'Conv3d_2c_3x3')) load_mixed(state_dict, 'mixed_3b', sess, os.path.join(prefix, 'Mixed_3b')) load_mixed(state_dict, 'mixed_3c', sess, os.path.join(prefix, 'Mixed_3c')) load_mixed(state_dict, 'mixed_4b', sess, os.path.join(prefix, 'Mixed_4b')) load_mixed(state_dict, 'mixed_4c', sess, os.path.join(prefix, 'Mixed_4c')) load_mixed(state_dict, 'mixed_4d', sess, os.path.join(prefix, 'Mixed_4d')) load_mixed(state_dict, 'mixed_4e', sess, os.path.join(prefix, 'Mixed_4e')) # Here goest to 0.1 max error with tf load_mixed(state_dict, 'mixed_4f', sess, os.path.join(prefix, 'Mixed_4f')) load_mixed( state_dict, 'mixed_5b', sess, os.path.join(prefix, 'Mixed_5b'), fix_typo=True) load_mixed(state_dict, 'mixed_5c', sess, os.path.join(prefix, 'Mixed_5c')) load_conv3d( state_dict, 'conv3d_0c_1x1', sess, os.path.join(prefix, 'Logits', 'Conv3d_0c_1x1'), bias=True, bn=False) self.load_state_dict(state_dict) def get_conv_params(sess, name, bias=False): # Get conv weights conv_weights_tensor = sess.graph.get_tensor_by_name( os.path.join(name, 'w:0')) if bias: conv_bias_tensor = sess.graph.get_tensor_by_name( os.path.join(name, 'b:0')) conv_bias = sess.run(conv_bias_tensor) conv_weights = sess.run(conv_weights_tensor) conv_shape = conv_weights.shape kernel_shape = conv_shape[0:3] in_channels = conv_shape[3] out_channels = conv_shape[4] conv_op = sess.graph.get_operation_by_name( os.path.join(name, 'convolution')) padding_name = conv_op.get_attr('padding') padding = _get_padding(padding_name, kernel_shape) all_strides = conv_op.get_attr('strides') strides = all_strides[1:4] conv_params = [ conv_weights, kernel_shape, in_channels, out_channels, strides, padding ] if bias: conv_params.append(conv_bias) return conv_params def get_bn_params(sess, name): moving_mean_tensor = sess.graph.get_tensor_by_name( os.path.join(name, 'moving_mean:0')) moving_var_tensor = sess.graph.get_tensor_by_name( os.path.join(name, 'moving_variance:0')) beta_tensor = sess.graph.get_tensor_by_name(os.path.join(name, 'beta:0')) moving_mean = sess.run(moving_mean_tensor) moving_var = sess.run(moving_var_tensor) beta = sess.run(beta_tensor) return moving_mean, moving_var, beta def _get_padding(padding_name, conv_shape): padding_name = padding_name.decode("utf-8") if padding_name == "VALID": return [0, 0] elif padding_name == "SAME": return [ math.floor(int(conv_shape[0]) / 2), math.floor(int(conv_shape[1]) / 2), math.floor(int(conv_shape[2]) / 2) ] else: raise ValueError('Invalid padding name ' + padding_name) def load_conv3d(state_dict, name_pt, sess, name_tf, bias=False, bn=True): # Transfer convolution params conv_name_tf = os.path.join(name_tf, 'conv_3d') conv_params = get_conv_params(sess, conv_name_tf, bias=bias) if bias: conv_weights, kernel_shape, in_channels, out_channels, strides, padding, conv_bias = conv_params else: conv_weights, kernel_shape, in_channels, out_channels, strides, padding = conv_params conv_weights_rs = np.transpose( conv_weights, (4, 3, 0, 1, 2)) state_dict[name_pt + '.conv3d.weight'] = torch.from_numpy(conv_weights_rs) if bias: state_dict[name_pt + '.conv3d.bias'] = torch.from_numpy(conv_bias) # Transfer batch norm params if bn: conv_tf_name = os.path.join(name_tf, 'batch_norm') moving_mean, moving_var, beta = get_bn_params(sess, conv_tf_name) out_planes = conv_weights_rs.shape[0] state_dict[name_pt + '.batch3d.weight'] = torch.ones(out_planes) state_dict[name_pt + '.batch3d.bias'] = torch.from_numpy(beta.squeeze()) state_dict[name_pt + '.batch3d.running_mean'] = torch.from_numpy(moving_mean.squeeze()) state_dict[name_pt + '.batch3d.running_var'] = torch.from_numpy(moving_var.squeeze()) def load_mixed(state_dict, name_pt, sess, name_tf, fix_typo=False): # Branch 0 load_conv3d(state_dict, name_pt + '.branch_0', sess, os.path.join(name_tf, 'Branch_0/Conv3d_0a_1x1')) # Branch .1 load_conv3d(state_dict, name_pt + '.branch_1.0', sess, os.path.join(name_tf, 'Branch_1/Conv3d_0a_1x1')) load_conv3d(state_dict, name_pt + '.branch_1.1', sess, os.path.join(name_tf, 'Branch_1/Conv3d_0b_3x3')) # Branch 2 load_conv3d(state_dict, name_pt + '.branch_2.0', sess, os.path.join(name_tf, 'Branch_2/Conv3d_0a_1x1')) if fix_typo: load_conv3d(state_dict, name_pt + '.branch_2.1', sess, os.path.join(name_tf, 'Branch_2/Conv3d_0a_3x3')) else: load_conv3d(state_dict, name_pt + '.branch_2.1', sess, os.path.join(name_tf, 'Branch_2/Conv3d_0b_3x3')) # Branch 3 load_conv3d(state_dict, name_pt + '.branch_3.1', sess, os.path.join(name_tf, 'Branch_3/Conv3d_0b_1x1'))
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/models/PS.py
models/PS.py
import torch.nn as nn from models.PS_parts import * class PSNet(nn.Module): def __init__(self, n_channels=6): super(PSNet, self).__init__() self.inc = inconv(n_channels, 12) self.down1 = down(12, 24) self.down2 = down(24, 48) self.down3 = down(48, 96) self.down4 = down(96, 96) self.tas = MLP_tas(64, 2) def forward(self, x): x1 = self.inc(x) x2 = self.down1(x1) x3 = self.down2(x2) x4 = self.down3(x3) x5 = self.down4(x4) x = self.tas(x5) return x5, x
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/models/MLP.py
models/MLP.py
import torch import torch.nn as nn class MLP_score(nn.Module): def __init__(self, in_channel, out_channel): super(MLP_score, self).__init__() self.activation_1 = nn.ReLU() self.layer1 = nn.Linear(in_channel, 256) self.layer2 = nn.Linear(256, 64) self.layer3 = nn.Linear(64, out_channel) def forward(self, x): x = self.activation_1(self.layer1(x)) x = self.activation_1(self.layer2(x)) output = self.layer3(x) return output
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/models/PS_parts.py
models/PS_parts.py
import torch import torch.nn as nn class double_conv(nn.Module): def __init__(self, in_ch, out_ch): super(double_conv, self).__init__() self.conv = nn.Sequential( nn.Conv1d(in_ch, out_ch, 3, padding=1), nn.BatchNorm1d(out_ch), nn.ReLU(inplace=True), nn.Conv1d(out_ch, out_ch, 3, padding=1), nn.BatchNorm1d(out_ch), nn.ReLU(inplace=True) ) def forward(self, x): x = self.conv(x) return x class inconv(nn.Module): def __init__(self, in_ch, out_ch): super(inconv, self).__init__() self.conv = double_conv(in_ch, out_ch) def forward(self, x): x = self.conv(x) return x class down(nn.Module): def __init__(self, in_ch, out_ch): super(down, self).__init__() self.mpconv = nn.Sequential( nn.MaxPool1d(2), double_conv(in_ch, out_ch) ) def forward(self, x): x = self.mpconv(x) return x class MLP_tas(nn.Module): def __init__(self, in_channel, out_channel): super(MLP_tas, self).__init__() self.activation_1 = nn.ReLU() self.layer1 = nn.Linear(in_channel, 128) self.layer2 = nn.Linear(128, 64) self.layer3 = nn.Linear(64, out_channel) self.activation_2 = nn.Sigmoid() def forward(self, x): x = self.activation_1(self.layer1(x)) x = self.activation_1(self.layer2(x)) output = self.activation_2(self.layer3(x)) return output
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/models/__init__.py
models/__init__.py
from .Backbone import I3D_backbone from .vit_decoder import decoder_fuser from .MLP import MLP_score from .PS import PSNet
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/utils/parser.py
utils/parser.py
import os import yaml import argparse def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--archs', type = str, choices=['TSA'], help = 'our approach') parser.add_argument('--benchmark', type = str, choices=['FineDiving'], help = 'dataset') parser.add_argument('--prefix', type = str, default='default', help = 'experiment name') parser.add_argument('--resume', action='store_true', default=False ,help = 'resume training (interrupted by accident)') parser.add_argument('--sync_bn', type=bool, default=False) parser.add_argument('--fix_bn', type=bool, default=True) parser.add_argument('--test', action='store_true', default=False) parser.add_argument('--ckpts', type=str, default=None, help='test used ckpt path') args = parser.parse_args() if args.test: if args.ckpts is None: raise RuntimeError('--ckpts should not be None when --test is activate') return args def setup(args): args.config = '{}_TSA.yaml'.format(args.benchmark) args.experiment_path = os.path.join('./experiments',args.archs, args.benchmark, args.prefix) if args.resume: cfg_path = os.path.join(args.experiment_path,'config.yaml') if not os.path.exists(cfg_path): print("Failed to resume") args.resume = False setup(args) return print('Resume yaml from %s' % cfg_path) with open(cfg_path) as f: config = yaml.load(f, Loader=yaml.Loader) merge_config(config, args) args.resume = True else: config = get_config(args) merge_config(config, args) create_experiment_dir(args) save_experiment_config(args) def get_config(args): try: print('Load config yaml from %s' % args.config) with open(args.config) as f: config = yaml.load(f, Loader=yaml.Loader) except: raise NotImplementedError('%s arch is not supported'% args.archs) return config def merge_config(config, args): for k, v in config.items(): setattr(args, k, v) def create_experiment_dir(args): try: os.makedirs(args.experiment_path) print('Create experiment path successfully at %s' % args.experiment_path) except: pass def save_experiment_config(args): config_path = os.path.join(args.experiment_path,'config.yaml') with open(config_path, 'w') as f: yaml.dump(args.__dict__, f) print('Save the Config file at %s' % config_path)
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
xujinglin/FineDiving
https://github.com/xujinglin/FineDiving/blob/a2b80579326364b08fbf94ccf8e68266a7ed7e7e/utils/misc.py
utils/misc.py
import cv2.cv2 import torch import numpy as np import os from os.path import join from pydoc import locate import sys import torch.nn as nn import torch.nn.functional as F def import_class(name): return locate(name) def worker_init_fn(worker_id): np.random.seed(np.random.get_state()[1][0] + worker_id) def fix_bn(m): classname = m.__class__.__name__ if classname.find('BatchNorm') != -1: m.eval() def denormalize(label, label_range, upper = 100.0): true_label = (label.float() / float(upper)) * (label_range[1] - label_range[0]) + label_range[0] return true_label def normalize(label, label_range, upper = 100.0): norm_label = ((label - label_range[0]) / (label_range[1] - label_range[0]) ) * float(upper) return norm_label def segment_iou(target_segment, candidate_segments, args): tt1 = np.maximum(target_segment[0], candidate_segments[0]) tt2 = np.minimum(target_segment[1], candidate_segments[1]) segments_intersection = (tt2 - tt1).clip(0) segments_union = (candidate_segments[1] - candidate_segments[0]) \ + (target_segment[1] - target_segment[0]) - segments_intersection tIoU = segments_intersection.astype(float) / (segments_union + sys.float_info.epsilon) return tIoU def cal_tiou(tIoU_results, tiou_thresholds): tIoU_correct = np.zeros((len(tIoU_results), len(tiou_thresholds))) for tidx, tiou_thr in enumerate(tiou_thresholds): for idx in range(len(tIoU_results)): if tIoU_results[idx] >= tiou_thr: tIoU_correct[idx, tidx] = 1 else: tIoU_correct[idx, tidx] = 0 tIoU_correct_per_thr = tIoU_correct.sum(0) return tIoU_correct_per_thr def seg_pool_1d(video_fea_1, video_1_st, video_1_ed, fix_size): video_fea_seg0 = F.interpolate(video_fea_1[:,:,:video_1_st], size=fix_size, mode='linear', align_corners=True) video_fea_seg1 = F.interpolate(video_fea_1[:,:,video_1_st:video_1_ed], size=fix_size, mode='linear', align_corners=True) video_fea_seg2 = F.interpolate(video_fea_1[:,:,video_1_ed:], size=fix_size, mode='linear', align_corners=True) video_1_segs = torch.cat([video_fea_seg0, video_fea_seg1, video_fea_seg2], 2) return video_1_segs def seg_pool_3d(video_feamap_2, video_2_st, video_2_ed, fix_size): N, C, T, H, W = video_feamap_2.size() video_feamap_seg0 = F.interpolate(video_feamap_2[:, :, :video_2_st, :, :], size=[fix_size, H, W], mode='trilinear', align_corners=True) video_feamap_seg1 = F.interpolate(video_feamap_2[:, :, video_2_st:video_2_ed, :, :], size=[fix_size, H, W], mode='trilinear', align_corners=True) video_feamap_seg2 = F.interpolate(video_feamap_2[:, :, video_2_ed:, :, :], size=[fix_size, H, W], mode='trilinear', align_corners=True) video_2_segs_map = torch.cat([video_feamap_seg0, video_feamap_seg1, video_feamap_seg2], 2) return video_2_segs_map
python
MIT
a2b80579326364b08fbf94ccf8e68266a7ed7e7e
2026-01-05T07:13:19.060820Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/main.py
main.py
# -*- coding: utf-8 -*- import argparse import json import os import os.path import shutil from itertools import chain import numpy as np import torch from tqdm import tqdm from utils import builder, configurator, io, misc, ops, pipeline, recorder def parse_config(): parser = argparse.ArgumentParser("Training and evaluation script") parser.add_argument("--config", default="./configs/zoomnet/zoomnet.py", type=str) parser.add_argument("--datasets-info", default="./configs/_base_/dataset/dataset_configs.json", type=str) parser.add_argument("--model-name", type=str) parser.add_argument("--batch-size", type=int) parser.add_argument("--load-from", type=str) parser.add_argument("--resume-from", type=str) parser.add_argument("--info", type=str) args = parser.parse_args() config = configurator.Configurator.fromfile(args.config) config.use_ddp = False if args.model_name is not None: config.model_name = args.model_name if args.batch_size is not None: config.train.batch_size = args.batch_size if args.info is not None: config.experiment_tag = args.info if args.load_from is not None: config.load_from = args.load_from with open(args.datasets_info, encoding="utf-8", mode="r") as f: datasets_info = json.load(f) tr_paths = {} for tr_dataset in config.datasets.train.path: if tr_dataset not in datasets_info: raise KeyError(f"{tr_dataset} not in {args.datasets_info}!!!") tr_paths[tr_dataset] = datasets_info[tr_dataset] config.datasets.train.path = tr_paths te_paths = {} for te_dataset in config.datasets.test.path: if te_dataset not in datasets_info: raise KeyError(f"{te_dataset} not in {args.datasets_info}!!!") te_paths[te_dataset] = datasets_info[te_dataset] config.datasets.test.path = te_paths config.proj_root = os.path.dirname(os.path.abspath(__file__)) config.exp_name = misc.construct_exp_name(model_name=config.model_name, cfg=config) if args.resume_from is not None: config.resume_from = args.resume_from resume_proj_root = os.sep.join(args.resume_from.split("/")[:-3]) if resume_proj_root.startswith("./"): resume_proj_root = resume_proj_root[2:] config.output_dir = os.path.join(config.proj_root, resume_proj_root) config.exp_name = args.resume_from.split("/")[-3] else: config.output_dir = os.path.join(config.proj_root, "output") config.path = misc.construct_path(output_dir=config.output_dir, exp_name=config.exp_name) return config @recorder.TimeRecoder.decorator(start_msg="Test") def test_once( model, data_loader, save_path, tta_setting, clip_range=None, show_bar=False, desc="[TE]", to_minmax=False ): model.eval() model.is_training = False cal_total_seg_metrics = recorder.CalTotalMetric() pgr_bar = enumerate(data_loader) if show_bar: pgr_bar = tqdm(pgr_bar, total=len(data_loader), ncols=79, desc=desc) for batch_id, batch in pgr_bar: batch_images = misc.to_device(batch["data"], device=model.device) if tta_setting.enable: logits = pipeline.test_aug( model=model, data=batch_images, strategy=tta_setting.strategy, reducation=tta_setting.reduction ) else: logits = model(data=batch_images) probs = logits.sigmoid().squeeze(1).cpu().detach().numpy() for i, pred in enumerate(probs): mask_path = batch["info"]["mask_path"][i] mask_array = io.read_gray_array(mask_path, dtype=np.uint8) mask_h, mask_w = mask_array.shape # here, sometimes, we can resize the prediciton to the shape of the mask's shape pred = ops.imresize(pred, target_h=mask_h, target_w=mask_w, interp="linear") if clip_range is not None: pred = ops.clip_to_normalize(pred, clip_range=clip_range) if save_path: # 这里的save_path包含了数据集名字 ops.save_array_as_image( data_array=pred, save_name=os.path.basename(mask_path), save_dir=save_path, to_minmax=to_minmax ) pred = (pred * 255).astype(np.uint8) cal_total_seg_metrics.step(pred, mask_array, mask_path) fixed_seg_results = cal_total_seg_metrics.get_results() return fixed_seg_results @torch.no_grad() def testing(model, cfg): for data_name, data_path, loader in pipeline.get_te_loader(cfg): pred_save_path = os.path.join(cfg.path.save, data_name) cfg.te_logger.record(f"Results will be saved into {pred_save_path}") seg_results = test_once( model=model, save_path=pred_save_path, data_loader=loader, tta_setting=cfg.test.tta, clip_range=cfg.test.clip_range, show_bar=cfg.test.get("show_bar", False), to_minmax=cfg.test.get("to_minmax", False), ) cfg.te_logger.record(f"Results on the testset({data_name}): {misc.mapping_to_str(data_path)}\n{seg_results}") cfg.excel_logger(row_data=seg_results, dataset_name=data_name, method_name=cfg.exp_name) def training(model, cfg) -> pipeline.ModelEma: tr_loader = pipeline.get_tr_loader(cfg) cfg.epoch_length = len(tr_loader) if not cfg.train.epoch_based: cfg.train.num_epochs = (cfg.train.num_iters + cfg.epoch_length) // cfg.epoch_length else: cfg.train.num_iters = cfg.train.num_epochs * cfg.epoch_length optimizer = pipeline.construct_optimizer( model=model, initial_lr=cfg.train.lr, mode=cfg.train.optimizer.mode, group_mode=cfg.train.optimizer.group_mode, cfg=cfg.train.optimizer.cfg, ) scheduler = pipeline.Scheduler( optimizer=optimizer, num_iters=cfg.train.num_iters, epoch_length=cfg.epoch_length, scheduler_cfg=cfg.train.scheduler, step_by_batch=cfg.train.sche_usebatch, ) scheduler.record_lrs(param_groups=optimizer.param_groups) scaler = torch.cuda.amp.GradScaler(enabled=cfg.train.use_amp) cfg.tr_logger.record(f"Scheduler:\n{scheduler}") cfg.tr_logger.record(f"Optimizer:\n{optimizer}") scheduler.plot_lr_coef_curve(save_path=cfg.path.pth_log) start_epoch = 0 if cfg.resume_from: params_in_checkpoint = io.load_specific_params( load_path=cfg.resume_from, names=["model", "optimizer", "scaler", "start_epoch"] ) model.load_state_dict(params_in_checkpoint["model"]) optimizer.load_state_dict(state_dict=params_in_checkpoint["optimizer"]) scaler.load_state_dict(state_dict=params_in_checkpoint["scaler"]) start_epoch = params_in_checkpoint["start_epoch"] model_ema = None if cfg.train.ema.enable: # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper model_ema = pipeline.ModelEma( model.module if hasattr(model, "module") else model, decay=cfg.train.ema.decay, device="cpu" if cfg.train.ema.force_cpu else None, has_set=False, ) if cfg.resume_from: params_in_checkpoint = io.load_specific_params(load_path=cfg.resume_from, names=["model_ema"]) model_ema.module.load_state_dict(state_dict=params_in_checkpoint["model_ema"]) time_logger = recorder.TimeRecoder() loss_recorder = recorder.AvgMeter() curr_iter = 0 for curr_epoch in range(start_epoch, cfg.train.num_epochs): cfg.tr_logger.record(f"Exp_Name: {cfg.exp_name}") time_logger.start(msg="An Epoch Start...") loss_recorder.reset() model.train() model.is_training = True # an epoch starts for batch_idx, batch in enumerate(tr_loader): scheduler.step(curr_idx=curr_iter) # update learning rate batch_data = misc.to_device(data=batch["data"], device=model.device) with torch.cuda.amp.autocast(enabled=cfg.train.use_amp): probs, loss, loss_str = model( data=batch_data, curr=dict( iter_percentage=curr_iter / cfg.train.num_iters, epoch_percentage=curr_epoch / cfg.train.num_epochs, ), ) loss = loss / cfg.train.grad_acc_step scaler.scale(loss).backward() if cfg.train.grad_clip.enable: scaler.unscale_(optimizer) ops.clip_grad( chain(*[group["params"] for group in optimizer.param_groups]), mode=cfg.train.grad_clip.mode, clip_cfg=cfg.train.grad_clip.cfg, ) # Accumulates scaled gradients. if (curr_iter + 1) % cfg.train.grad_acc_step == 0: scaler.step(optimizer) scaler.update() optimizer.zero_grad(set_to_none=cfg.train.optimizer.set_to_none) if model_ema is not None: model_ema.update(model) item_loss = loss.item() data_shape = batch_data["mask"].shape loss_recorder.update(value=item_loss, num=data_shape[0]) if cfg.log_interval.txt > 0 and ( curr_iter % cfg.log_interval.txt == 0 or (curr_iter + 1) % cfg.epoch_length == 0 or (curr_iter + 1) == cfg.train.num_iters ): msg = " | ".join( [ f"I:{curr_iter}:{cfg.train.num_iters} {batch_idx}/{cfg.epoch_length} {curr_epoch}/{cfg.train.num_epochs}", f"Lr:{optimizer.lr_string()}", f"M:{loss_recorder.avg:.5f}/C:{item_loss:.5f}", f"{list(data_shape)}", f"{loss_str}", ] ) cfg.tr_logger.record(msg) if cfg.log_interval.tensorboard > 0 and ( curr_iter % cfg.log_interval.tensorboard == 0 or (curr_iter + 1) % cfg.epoch_length == 0 or (curr_iter + 1) == cfg.train.num_iters ): cfg.tb_logger.record_curve("iter_loss", item_loss, curr_iter) cfg.tb_logger.record_curve("lr", optimizer.lr_groups(), curr_iter) cfg.tb_logger.record_curve("avg_loss", loss_recorder.avg, curr_iter) cfg.tb_logger.record_images(dict(**probs, **batch_data), curr_iter) if curr_iter < 3: # plot some batches of the training phase recorder.plot_results( dict(**probs, **batch_data), save_path=os.path.join(cfg.path.pth_log, f"train_batch_{curr_iter}.png"), ) curr_iter += 1 if curr_iter >= cfg.train.num_iters: break # an epoch ends if curr_epoch == 0 and model_ema is not None: model_ema.set(model=model) # using a better initial model state # save all params for (curr_epoch+1)th epoch io.save_params( exp_name=cfg.exp_name, model=model, model_ema=model_ema, optimizer=optimizer, scaler=scaler, next_epoch=curr_epoch + 1, total_epoch=cfg.train.num_epochs, save_num_models=cfg.train.save_num_models, full_net_path=cfg.path.final_full_net, state_net_path=cfg.path.final_state_net, ) time_logger.now(pre_msg="An Epoch End...") if curr_iter >= cfg.train.num_iters: break # only save the last weight io.save_weight(model=model, save_path=cfg.path.final_state_net) return model_ema def main(): cfg = parse_config() if not cfg.resume_from: misc.pre_mkdir(path_config=cfg.path) with open(cfg.path.cfg_copy, encoding="utf-8", mode="w") as f: f.write(cfg.pretty_text) shutil.copy(__file__, cfg.path.trainer_copy) cfg.tr_logger = recorder.TxtLogger(cfg.path.tr_log) cfg.te_logger = recorder.TxtLogger(cfg.path.te_log) # TODO: Excel -> CSV(More flexible and simple) cfg.excel_logger = recorder.MetricExcelRecorder( xlsx_path=cfg.path.excel, dataset_names=sorted([x for x in cfg.datasets.test.path.keys()]) ) if cfg.log_interval.tensorboard > 0: cfg.tb_logger = recorder.TBRecorder(tb_path=cfg.path.tb) if cfg.base_seed >= 0: cfg.tr_logger.record(f"{cfg.proj_root} with base_seed {cfg.base_seed}") else: cfg.tr_logger.record(f"{cfg.proj_root} without fixed seed") if cfg.train.ms.enable: deterministic = True else: deterministic = cfg.deterministic misc.initialize_seed_cudnn(seed=cfg.base_seed, deterministic=deterministic) model, model_code = builder.build_obj_from_registry( registry_name="MODELS", obj_name=cfg.model_name, return_code=True ) cfg.tr_logger.record(model_code) cfg.tr_logger.record(model) model.device = "cuda:0" model.to(model.device) if cfg.load_from: model_ema = io.load_weight(model=model, load_path=cfg.load_from) else: model_ema = training(model=model, cfg=cfg) if cfg.has_test: if model_ema is not None: testing(model=model_ema.module, cfg=cfg) if cfg.train.ema.keep_original_test: cfg.tr_logger.record(f"The results from original model will overwrite the model_ema's.") testing(model=model, cfg=cfg) else: testing(model=model, cfg=cfg) cfg.tr_logger.record("End training...") if __name__ == "__main__": main()
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/test.py
test.py
# -*- coding: utf-8 -*- import argparse import json import os import os.path import numpy as np import torch from tqdm import tqdm from utils import builder, configurator, io, misc, ops, pipeline, recorder def parse_config(): parser = argparse.ArgumentParser("Training and evaluation script") parser.add_argument("--config", default="./configs/zoomnet/zoomnet.py", type=str) parser.add_argument("--datasets-info", default="./configs/_base_/dataset/dataset_configs.json", type=str) parser.add_argument("--model-name", type=str) parser.add_argument("--batch-size", type=int) parser.add_argument("--load-from", type=str) parser.add_argument("--save-path", type=str) parser.add_argument("--minmax-results", action="store_true") parser.add_argument("--info", type=str) args = parser.parse_args() config = configurator.Configurator.fromfile(args.config) config.use_ddp = False if args.model_name is not None: config.model_name = args.model_name if args.batch_size is not None: config.test.batch_size = args.batch_size if args.load_from is not None: config.load_from = args.load_from if args.info is not None: config.experiment_tag = args.info if args.save_path is not None: if os.path.exists(args.save_path): if len(os.listdir(args.save_path)) != 0: raise ValueError(f"--save-path is not an empty folder.") else: print(f"{args.save_path} does not exist, create it.") os.makedirs(args.save_path) config.save_path = args.save_path config.test.to_minmax = args.minmax_results with open(args.datasets_info, encoding="utf-8", mode="r") as f: datasets_info = json.load(f) te_paths = {} for te_dataset in config.datasets.test.path: if te_dataset not in datasets_info: raise KeyError(f"{te_dataset} not in {args.datasets_info}!!!") te_paths[te_dataset] = datasets_info[te_dataset] config.datasets.test.path = te_paths config.proj_root = os.path.dirname(os.path.abspath(__file__)) config.exp_name = misc.construct_exp_name(model_name=config.model_name, cfg=config) return config def test_once( model, data_loader, save_path, tta_setting, clip_range=None, show_bar=False, desc="[TE]", to_minmax=False, ): model.is_training = False cal_total_seg_metrics = recorder.CalTotalMetric() pgr_bar = enumerate(data_loader) if show_bar: pgr_bar = tqdm(pgr_bar, total=len(data_loader), ncols=79, desc=desc) for batch_id, batch in pgr_bar: batch_images = misc.to_device(batch["data"], device=model.device) if tta_setting.enable: logits = pipeline.test_aug( model=model, data=batch_images, strategy=tta_setting.strategy, reducation=tta_setting.reduction ) else: logits = model(data=batch_images) probs = logits.sigmoid().squeeze(1).cpu().detach().numpy() for i, pred in enumerate(probs): mask_path = batch["info"]["mask_path"][i] mask_array = io.read_gray_array(mask_path, dtype=np.uint8) mask_h, mask_w = mask_array.shape # here, sometimes, we can resize the prediciton to the shape of the mask's shape pred = ops.imresize(pred, target_h=mask_h, target_w=mask_w, interp="linear") if clip_range is not None: pred = ops.clip_to_normalize(pred, clip_range=clip_range) if to_minmax: pred = ops.minmax(pred) if save_path: # 这里的save_path包含了数据集名字 ops.save_array_as_image(data_array=pred, save_name=os.path.basename(mask_path), save_dir=save_path) pred = (pred * 255).astype(np.uint8) cal_total_seg_metrics.step(pred, mask_array, mask_path) fixed_seg_results = cal_total_seg_metrics.get_results() return fixed_seg_results @torch.no_grad() def testing(model, cfg): pred_save_path = None for data_name, data_path, loader in pipeline.get_te_loader(cfg): if cfg.save_path: pred_save_path = os.path.join(cfg.save_path, data_name) print(f"Results will be saved into {pred_save_path}") seg_results = test_once( model=model, save_path=pred_save_path, data_loader=loader, tta_setting=cfg.test.tta, clip_range=cfg.test.clip_range, show_bar=cfg.test.get("show_bar", False), to_minmax=cfg.test.get("to_minmax", False), ) print(f"Results on the testset({data_name}): {misc.mapping_to_str(data_path)}\n{seg_results}") def main(): cfg = parse_config() model, model_code = builder.build_obj_from_registry( registry_name="MODELS", obj_name=cfg.model_name, return_code=True ) io.load_weight(model=model, load_path=cfg.load_from) model.device = "cuda:0" model.to(model.device) model.eval() testing(model=model, cfg=cfg) if __name__ == "__main__": main()
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/tools/run_it.py
tools/run_it.py
# -*- coding: utf-8 -*- # @Time : 2021/3/6 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import argparse import os.path import subprocess import time from enum import Enum from multiprocessing import Process import pynvml pynvml.nvmlInit() class STATUS(Enum): NORMAL = 0 GPU_BUSY = 1 class MyProcess: slot_idx = -1 curr_task_id = 0 def __init__( self, interpreter_path, gpu_id, verbose=True, stdin=None, stdout=None, stderr=None, num_cmds=None, max_used_ratio=0.5, ): super().__init__() self.gpu_id = gpu_id self.interpreter_path = interpreter_path self.verbose = verbose self.num_cmds = num_cmds self.stdin = stdin self.stdout = stdout self.stderr = stderr self.sub_proc = None self.proc = None self.gpu_handler = pynvml.nvmlDeviceGetHandleByIndex(gpu_id) self.max_used_ratio = max_used_ratio MyProcess.slot_idx += 1 def __str__(self): return f"[ID {self.slot_idx} INFO] NEW PROCESS SLOT ON GPU {self.gpu_id} IS CREATED!" def _used_ratio(self, used, total): return used / total def get_used_mem(self, return_ratio=False): meminfo = pynvml.nvmlDeviceGetMemoryInfo(self.gpu_handler) if return_ratio: return self._used_ratio(meminfo.used, meminfo.total) return meminfo.used def _create_sub_proc(self, cmd=""): self.sub_proc = subprocess.Popen( args=f"CUDA_VISIBLE_DEVICES={self.gpu_id} {self.interpreter_path} -u {cmd}", stdin=self.stdin, stdout=self.stdout, stderr=self.stderr, shell=True, executable="bash", env=None, close_fds=True, bufsize=1, text=True, encoding="utf-8", ) print(f"[NEW TASK PID: {self.sub_proc.pid}] {self.sub_proc.args}") if self.verbose: if self.stdout is not None and self.sub_proc is not None: for l in self.sub_proc.stdout: print(f"[ID: {self.curr_task_id}/{self.num_cmds} GPU: {self.gpu_id}] {l}", end="") def create_and_start_proc(self, cmd=None): if (used_mem := self.get_used_mem(return_ratio=True)) > self.max_used_ratio: # TODO: 当前的判定方式并不是太准确。最好的方式是由程序提供设置周期数的选项(`--num-epochs`), # 首先按照num_epoch=1来进行初步的运行,并统计各个命令对应使用的显存。 # 之后根据这些程序实际使用的显存来安排后续的操作。 # 这可能需要程序对输出可以实现覆盖式(`--overwrite`)操作。 self.status = STATUS.GPU_BUSY print( f"[ID {self.slot_idx} WARN] the memory usage of the GPU {self.gpu_id} is currently {used_mem}, " f"which exceeds the maximum threshold {self.max_used_ratio}." ) return print(f"[ID {self.slot_idx} INFO] {cmd}") MyProcess.curr_task_id += 1 self.proc = Process(target=self._create_sub_proc, kwargs=dict(cmd=cmd)) self.proc.start() # 只有成功创建并启动了进城后才改变状态 self.status = STATUS.NORMAL def is_alive(self): if self.status == STATUS.NORMAL: return self.proc.is_alive() return False def read_cmds_from_txt(path): with open(path, encoding="utf-8", mode="r") as f: cmds = [] for line in f: line = line.rstrip() if line and line[0].isalpha(): cmds.append(line) return cmds def get_args(): parser = argparse.ArgumentParser() parser.add_argument("--interpreter", type=str, required=True, help="The path of your interpreter you want to use.") parser.add_argument("--verbose", action="store_true", help="Whether to print the output of the subprocess.") parser.add_argument( "--gpu-pool", nargs="+", type=int, default=[0], help="The pool containing all ids of your gpu devices." ) parser.add_argument("--max-workers", type=int, help="The max number of the workers.") parser.add_argument( "--cmd-pool", type=str, required=True, help="The text file containing all your commands. It will be combined with `interpreter`.", ) parser.add_argument("--poll-interval", type=int, default=0, help="The interval of the poll.") parser.add_argument("--max-used-ratio", type=float, default=0.5) args = parser.parse_args() args.interpreter = os.path.abspath(args.interpreter) if args.max_workers is None: args.max_workers = len(args.gpu_pool) return args def main(): args = get_args() print("[YOUR CONFIG]\n" + str(args)) cmd_pool = read_cmds_from_txt(path=args.cmd_pool) print("[YOUR CMDS]\n" + "\n".join(cmd_pool)) num_gpus = len(args.gpu_pool) print("[CREATE PROCESS OBJECTS]") proc_slots = [] for i in range(min(args.max_workers, len(cmd_pool))): # 确保slots数量小于等于命令数量 gpu_id = i % num_gpus proc = MyProcess( interpreter_path=args.interpreter, gpu_id=args.gpu_pool[gpu_id], verbose=args.verbose, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, num_cmds=len(cmd_pool), max_used_ratio=args.max_used_ratio, ) print(proc) proc_slots.append(proc) cmd_pool.reverse() # 后面的操作是按照栈的形式处理的,所以这里翻转一下 for p in proc_slots: if len(cmd_pool) == 0: # 确保出栈不会异常 break cmd = cmd_pool.pop() # 指令出栈 p.create_and_start_proc(cmd=cmd) if p.status == STATUS.GPU_BUSY: # 当前GPU显存不足,暂先跳过 cmd_pool.append(cmd) # 指令未能顺利执行,重新入栈 continue is_normal_ending = True while proc_slots: # the pool of the processes is not empty for slot_idx, p in enumerate(proc_slots): # polling if not p.is_alive(): if len(cmd_pool) == 0: # 指令均在执行或者已被执行 del proc_slots[slot_idx] print("[NO MORE COMMANDS, DELETE THE PROCESS SLOT!]") break cmd = cmd_pool.pop() p.create_and_start_proc(cmd=cmd) if p.status == STATUS.GPU_BUSY: # 当前GPU显存不足,暂先跳过 cmd_pool.append(cmd) # 指令未能顺利执行,重新入栈 continue if proc_slots and all([_p.status == STATUS.GPU_BUSY for _p in proc_slots]): # 所有GPU都被外部程序占用,直接退出。因为如果我们的程序正常执行时,状态是NORMAL if args.poll_interval > 0: print(f"[ALL GPUS ARE BUSY, WAITING {args.poll_interval} SECONDS!]") time.sleep(args.poll_interval) else: print("[ALL GPUS ARE BUSY, EXIT THE LOOP!]") proc_slots.clear() is_normal_ending = False break time.sleep(1) if is_normal_ending: print("[ALL COMMANDS HAVE BEEN COMPLETED!]") if __name__ == "__main__": main()
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/methods/__init__.py
methods/__init__.py
from .classic_methods.CMWNet import CMWNet_V16 from .classic_methods.CPD import CPD_R50 from .classic_methods.HDFNet import HDFNet_Res50 from .classic_methods.MINet import MINet_Res50, MINet_VGG16 from .zoomnet.zoomnet import ZoomNet, ZoomNet_CK
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/methods/classic_methods/CMWNet.py
methods/classic_methods/CMWNet.py
# -*- coding: utf-8 -*- # @Time : 2021/6/3 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import torch import torch.nn as nn from torchvision.models import vgg from methods.module.base_model import BasicModelClass from utils.builder import MODELS from utils.ops.module_ops import load_params_for_new_conv def Cus_V16BN_tv(): net = vgg.vgg16_bn(pretrained=True, progress=True) head_convs = list(net.children())[0][:6] rgb_head = nn.Sequential(*head_convs[:3]) shared_head = nn.Sequential(*head_convs[3:-1]) depth_head = nn.Sequential(nn.Conv2d(1, 64, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(64), nn.ReLU(True)) load_params_for_new_conv(conv_layer=rgb_head[0], new_conv_layer=depth_head[0], in_dim=1) model = nn.ModuleDict( dict( rgb_head=rgb_head, depth_head=depth_head, shared_head=shared_head, layer1=nn.Sequential(*list(net.children())[0][6:13]), layer2=nn.Sequential(*list(net.children())[0][13:23]), layer3=nn.Sequential(*list(net.children())[0][23:33]), layer4=nn.Sequential(*list(net.children())[0][33:43]), ) ) return model class ConvBNReLU(nn.Sequential): def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False): super().__init__() self.add_module( name="conv", module=nn.Conv2d( in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias, ), ) self.add_module(name="bn", module=nn.BatchNorm2d(out_planes)) self.add_module(name="relu", module=nn.ReLU(True)) class DW(nn.Module): def __init__(self, in_dim, mid_dim, out_dim, mode=""): super(DW, self).__init__() self.loc_3x3_1 = ConvBNReLU(in_dim, mid_dim, 3, 1, 1) self.loc_3x3_2 = ConvBNReLU(in_dim, mid_dim, 3, 1, 1) self.glo_3x3 = ConvBNReLU(in_dim, mid_dim, 3, 1, 5, dilation=5) self.glo_7x7 = ConvBNReLU(in_dim, mid_dim, 7, 1, 3) if mode == "up": self.fusion = nn.Sequential( nn.ConvTranspose2d(4 * mid_dim, out_dim, 2, 2, bias=False), nn.BatchNorm2d(out_dim), nn.Sigmoid(), ) elif mode == "down": self.fusion = nn.Sequential( nn.Conv2d(4 * mid_dim, out_dim, 2, 2, bias=False), nn.BatchNorm2d(out_dim), nn.Sigmoid(), ) else: self.fusion = nn.Sequential( nn.Conv2d(4 * mid_dim, out_dim, 3, 1, 1, bias=False), nn.BatchNorm2d(out_dim), nn.Sigmoid(), ) def forward(self, fr, fd): fd = torch.cat([self.loc_3x3_1(fd), self.loc_3x3_2(fd), self.glo_3x3(fd), self.glo_7x7(fd)], dim=1) r_dw = self.fusion(fd) return r_dw * fr class RW(nn.Module): def __init__(self, in_dim, out_dim): super(RW, self).__init__() self.conv = nn.Sequential( nn.Conv2d(in_dim, out_dim, 3, 1, 1, bias=False), nn.BatchNorm2d(out_dim), nn.Sigmoid(), ) def forward(self, fr): r_rw = self.conv(fr) return r_rw * fr class CMW_LM(nn.Module): def __init__(self, in_dims, out_dims, mid_dim): super().__init__() # Depth-to-RGB weighting (DW) self.dw_l = DW(in_dim=max(in_dims), mid_dim=mid_dim, out_dim=min(out_dims), mode="up") self.dw_h = DW(in_dim=min(in_dims), mid_dim=mid_dim, out_dim=max(out_dims), mode="down") # RGB-to-RGB weighting (RW) self.rw_l = RW(in_dim=min(in_dims), out_dim=min(out_dims)) self.rw_h = RW(in_dim=max(in_dims), out_dim=max(out_dims)) # Aggregation of Double Weighting Features self.up_conv = nn.Sequential( nn.ConvTranspose2d(max(out_dims), min(out_dims), 2, 2), nn.BatchNorm2d(min(out_dims)), nn.ReLU(True), nn.Conv2d(min(out_dims), min(out_dims), 1), nn.BatchNorm2d(min(out_dims)), nn.ReLU(True), ) def forward(self, rgb_feats, depth_feats): fr_l, fr_h = rgb_feats fd_l, fd_h = depth_feats f_dw_l = self.dw_l(fr=fr_l, fd=fd_h) f_rw_l = self.rw_l(fr=fr_l) f_de_l = fr_l + f_dw_l + f_rw_l f_dw_h = self.dw_h(fr=fr_h, fd=fd_l) f_rw_h = self.rw_h(fr=fr_h) f_de_h = fr_h + f_dw_h + f_rw_h f_cmw = torch.cat([f_de_l, self.up_conv(f_de_h)], dim=1) return f_cmw class CMW_H(nn.Module): def __init__(self, in_dim, mid_dim, out_dim): super(CMW_H, self).__init__() # Depth-to-RGB weighting (DW) self.dw = DW(in_dim=in_dim, mid_dim=mid_dim, out_dim=out_dim) # RGB-to-RGB weighting (RW) self.rw = RW(in_dim=in_dim, out_dim=out_dim) def forward(self, rgb_feats, depth_feats): fr = rgb_feats fd = depth_feats f_dw = self.dw(fr=fr, fd=fd) f_rw = self.rw(fr=fr) f_cmw = fr + f_dw + f_rw return f_cmw @MODELS.register() class CMWNet_V16(BasicModelClass): def __init__(self): super().__init__() self.siamese_encoder = Cus_V16BN_tv() self.cmw_l = CMW_LM(in_dims=(64, 128), mid_dim=64, out_dims=(64, 128)) self.cmw_m = CMW_LM(in_dims=(256, 512), mid_dim=256, out_dims=(256, 512)) self.cmw_h = CMW_H(in_dim=512, mid_dim=256, out_dim=512) self.d_12 = nn.Sequential( ConvBNReLU(256 + 64 * 2, 64, 3, 1, 1), ConvBNReLU(64, 64, 3, 1, 1), ConvBNReLU(64, 64, 3, 1, 1), ) self.d_34 = nn.Sequential( ConvBNReLU(512 + 256 * 2, 256, 3, 1, 1), ConvBNReLU(256, 256, 3, 1, 1), ConvBNReLU(256, 256, 3, 1, 1), nn.Dropout(p=0.5), nn.ConvTranspose2d(256, 256, 4, 4), ) self.d_5 = nn.Sequential( ConvBNReLU(512, 512, 3, 1, 1), ConvBNReLU(512, 512, 3, 1, 1), ConvBNReLU(512, 512, 3, 1, 1), nn.Dropout(p=0.5), nn.ConvTranspose2d(512, 512, 4, 4), ) self.sal_head_12 = nn.Conv2d(64, 1, 3, 1, 1) self.sal_head_34 = nn.Conv2d(256, 1, 3, 1, 1) self.sal_head_5 = nn.Conv2d(512, 1, 3, 1, 1) def body(self, rgb_image, depth_image): # separate head fr_0 = self.siamese_encoder["rgb_head"](rgb_image) fd_0 = self.siamese_encoder["depth_head"](depth_image) # siamese body fr_0 = self.siamese_encoder["shared_head"](fr_0) fd_0 = self.siamese_encoder["shared_head"](fd_0) fr_1 = self.siamese_encoder["layer1"](fr_0) fd_1 = self.siamese_encoder["layer1"](fd_0) fr_2 = self.siamese_encoder["layer2"](fr_1) fd_2 = self.siamese_encoder["layer2"](fd_1) fr_3 = self.siamese_encoder["layer3"](fr_2) fd_3 = self.siamese_encoder["layer3"](fd_2) fr_4 = self.siamese_encoder["layer4"](fr_3) fd_4 = self.siamese_encoder["layer4"](fd_3) d_12 = self.cmw_l(rgb_feats=[fr_0, fr_1], depth_feats=[fd_0, fd_1]) d_34 = self.cmw_m(rgb_feats=[fr_2, fr_3], depth_feats=[fd_2, fd_3]) d_5 = self.cmw_h(rgb_feats=fr_4, depth_feats=fd_4) d_5 = self.d_5(d_5) d_34 = self.d_34(torch.cat([d_34, d_5], dim=1)) d_12 = self.d_12(torch.cat([d_12, d_34], dim=1)) sal_12 = self.sal_head_12(d_12) sal_34 = self.sal_head_34(d_34) sal_5 = self.sal_head_5(fr_4) return dict(sal_12=sal_12, sal_34=sal_34, sal_5=sal_5) def train_forward(self, data, **kwargs): results = self.body(rgb_image=data["image"], depth_image=data["depth"]) loss, loss_str = self.cal_loss(all_preds=results, gts=data["mask"]) return results["sal_12"].sigmoid(), loss, loss_str def test_forward(self, data, **kwargs): results = self.body(rgb_image=data["image"], depth_image=data["depth"]) return results["sal_12"].sigmoid()
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/methods/classic_methods/HDFNet.py
methods/classic_methods/HDFNet.py
# -*- coding: utf-8 -*- # @Time : 2021/5/25 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import timm import torch import torch.nn as nn import torch.nn.functional as F from methods.module.base_model import BasicModelClass from methods.module.conv_block import ConvBNReLU from utils.builder import MODELS from utils.ops.tensor_ops import cus_sample, upsample_add class DenseLayer(nn.Module): def __init__(self, in_C, out_C, down_factor=4, k=4): """ 更像是DenseNet的Block,从而构造特征内的密集连接 """ super(DenseLayer, self).__init__() self.k = k self.down_factor = down_factor mid_C = out_C // self.down_factor self.down = nn.Conv2d(in_C, mid_C, 1) self.denseblock = nn.ModuleList() for i in range(1, self.k + 1): self.denseblock.append(ConvBNReLU(mid_C * i, mid_C, 3, 1, 1)) self.fuse = ConvBNReLU(in_C + mid_C, out_C, kernel_size=3, stride=1, padding=1) def forward(self, in_feat): down_feats = self.down(in_feat) out_feats = [] for denseblock in self.denseblock: feats = denseblock(torch.cat((*out_feats, down_feats), dim=1)) out_feats.append(feats) feats = torch.cat((in_feat, feats), dim=1) return self.fuse(feats) class DenseTransLayer(nn.Module): def __init__(self, in_C, out_C): super(DenseTransLayer, self).__init__() down_factor = in_C // out_C self.fuse_down_mul = ConvBNReLU(in_C, in_C, 3, 1, 1) self.res_main = DenseLayer(in_C, in_C, down_factor=down_factor) self.fuse_main = ConvBNReLU(in_C, out_C, kernel_size=3, stride=1, padding=1) def forward(self, rgb, depth): assert rgb.size() == depth.size() feat = self.fuse_down_mul(rgb + depth) return self.fuse_main(self.res_main(feat) + feat) class DDPM(nn.Module): def __init__(self, in_xC, in_yC, out_C, kernel_size=3, down_factor=4): """DDPM,利用nn.Unfold实现的动态卷积模块 Args: in_xC (int): 第一个输入的通道数 in_yC (int): 第二个输入的通道数 out_C (int): 最终输出的通道数 kernel_size (int): 指定的生成的卷积核的大小 down_factor (int): 用来降低卷积核生成过程中的参数量的一个降低通道数的参数 """ super(DDPM, self).__init__() self.kernel_size = kernel_size self.mid_c = out_C // 4 self.down_input = nn.Conv2d(in_xC, self.mid_c, 1) self.branch_1 = DepthDC3x3_1(self.mid_c, in_yC, self.mid_c, down_factor=down_factor) self.branch_3 = DepthDC3x3_3(self.mid_c, in_yC, self.mid_c, down_factor=down_factor) self.branch_5 = DepthDC3x3_5(self.mid_c, in_yC, self.mid_c, down_factor=down_factor) self.fuse = ConvBNReLU(4 * self.mid_c, out_C, 3, 1, 1) def forward(self, x, y): x = self.down_input(x) result_1 = self.branch_1(x, y) result_3 = self.branch_3(x, y) result_5 = self.branch_5(x, y) return self.fuse(torch.cat((x, result_1, result_3, result_5), dim=1)) class DepthDC3x3_1(nn.Module): def __init__(self, in_xC, in_yC, out_C, down_factor=4): """DepthDC3x3_1,利用nn.Unfold实现的动态卷积模块 Args: in_xC (int): 第一个输入的通道数 in_yC (int): 第二个输入的通道数 out_C (int): 最终输出的通道数 down_factor (int): 用来降低卷积核生成过程中的参数量的一个降低通道数的参数 """ super(DepthDC3x3_1, self).__init__() self.kernel_size = 3 self.fuse = nn.Conv2d(in_xC, out_C, 3, 1, 1) self.gernerate_kernel = nn.Sequential( nn.Conv2d(in_yC, in_yC, 3, 1, 1), DenseLayer(in_yC, in_yC, k=down_factor), nn.Conv2d(in_yC, in_xC * self.kernel_size ** 2, 1), ) self.unfold = nn.Unfold(kernel_size=3, dilation=1, padding=1, stride=1) def forward(self, x, y): N, xC, xH, xW = x.size() kernel = self.gernerate_kernel(y).reshape([N, xC, self.kernel_size ** 2, xH, xW]) unfold_x = self.unfold(x).reshape([N, xC, -1, xH, xW]) result = (unfold_x * kernel).sum(2) return self.fuse(result) class DepthDC3x3_3(nn.Module): def __init__(self, in_xC, in_yC, out_C, down_factor=4): """DepthDC3x3_3,利用nn.Unfold实现的动态卷积模块 Args: in_xC (int): 第一个输入的通道数 in_yC (int): 第二个输入的通道数 out_C (int): 最终输出的通道数 down_factor (int): 用来降低卷积核生成过程中的参数量的一个降低通道数的参数 """ super(DepthDC3x3_3, self).__init__() self.fuse = nn.Conv2d(in_xC, out_C, 3, 1, 1) self.kernel_size = 3 self.gernerate_kernel = nn.Sequential( nn.Conv2d(in_yC, in_yC, 3, 1, 1), DenseLayer(in_yC, in_yC, k=down_factor), nn.Conv2d(in_yC, in_xC * self.kernel_size ** 2, 1), ) self.unfold = nn.Unfold(kernel_size=3, dilation=3, padding=3, stride=1) def forward(self, x, y): N, xC, xH, xW = x.size() kernel = self.gernerate_kernel(y).reshape([N, xC, self.kernel_size ** 2, xH, xW]) unfold_x = self.unfold(x).reshape([N, xC, -1, xH, xW]) result = (unfold_x * kernel).sum(2) return self.fuse(result) class DepthDC3x3_5(nn.Module): def __init__(self, in_xC, in_yC, out_C, down_factor=4): """DepthDC3x3_5,利用nn.Unfold实现的动态卷积模块 Args: in_xC (int): 第一个输入的通道数 in_yC (int): 第二个输入的通道数 out_C (int): 最终输出的通道数 down_factor (int): 用来降低卷积核生成过程中的参数量的一个降低通道数的参数 """ super(DepthDC3x3_5, self).__init__() self.kernel_size = 3 self.fuse = nn.Conv2d(in_xC, out_C, 3, 1, 1) self.gernerate_kernel = nn.Sequential( nn.Conv2d(in_yC, in_yC, 3, 1, 1), DenseLayer(in_yC, in_yC, k=down_factor), nn.Conv2d(in_yC, in_xC * self.kernel_size ** 2, 1), ) self.unfold = nn.Unfold(kernel_size=3, dilation=5, padding=5, stride=1) def forward(self, x, y): N, xC, xH, xW = x.size() kernel = self.gernerate_kernel(y).reshape([N, xC, self.kernel_size ** 2, xH, xW]) unfold_x = self.unfold(x).reshape([N, xC, -1, xH, xW]) result = (unfold_x * kernel).sum(2) return self.fuse(result) @MODELS.register() class HDFNet_Res50(BasicModelClass): def __init__(self): super().__init__() self.rgb_encoder = timm.create_model(model_name="resnet50", in_chans=3, features_only=True, pretrained=True) self.depth_encoder = timm.create_model(model_name="resnet50", in_chans=1, features_only=True, pretrained=True) self.rgb_trans = nn.ModuleDict( dict( layer0=nn.Conv2d(64, 64, kernel_size=1), layer1=nn.Conv2d(256, 64, kernel_size=1), layer2=nn.Conv2d(512, 64, kernel_size=1), layer3=nn.Conv2d(1024, 64, kernel_size=1), layer4=nn.Conv2d(2048, 64, kernel_size=1), ) ) self.rgbd_trans = nn.ModuleDict( dict( layer2=DenseTransLayer(512, 64), layer3=DenseTransLayer(1024, 64), layer4=DenseTransLayer(2048, 64), ) ) self.upconv32 = ConvBNReLU(64, 64, kernel_size=3, stride=1, padding=1) self.upconv16 = ConvBNReLU(64, 64, kernel_size=3, stride=1, padding=1) self.upconv8 = ConvBNReLU(64, 64, kernel_size=3, stride=1, padding=1) self.upconv4 = ConvBNReLU(64, 64, kernel_size=3, stride=1, padding=1) self.upconv2 = ConvBNReLU(64, 32, kernel_size=3, stride=1, padding=1) self.upconv1 = ConvBNReLU(32, 32, kernel_size=3, stride=1, padding=1) self.selfdc_32 = DDPM(64, 64, 64, 3, 4) self.selfdc_16 = DDPM(64, 64, 64, 3, 4) self.selfdc_8 = DDPM(64, 64, 64, 3, 4) self.classifier = nn.Conv2d(32, 1, 1) def body(self, rgb_image, depth_image): rgb_en_feats = self.rgb_encoder(rgb_image) depth_en_feats = self.depth_encoder(depth_image) depth_en_feats[2] = self.rgbd_trans["layer2"](rgb_en_feats[2], depth_en_feats[2]) depth_en_feats[3] = self.rgbd_trans["layer3"](rgb_en_feats[3], depth_en_feats[3]) depth_en_feats[4] = self.rgbd_trans["layer4"](rgb_en_feats[4], depth_en_feats[4]) rgb_en_feats[0] = self.rgb_trans["layer0"](rgb_en_feats[0]) rgb_en_feats[1] = self.rgb_trans["layer1"](rgb_en_feats[1]) rgb_en_feats[2] = self.rgb_trans["layer2"](rgb_en_feats[2]) rgb_en_feats[3] = self.rgb_trans["layer3"](rgb_en_feats[3]) rgb_en_feats[4] = self.rgb_trans["layer4"](rgb_en_feats[4]) x = self.upconv32(rgb_en_feats[4]) # 1024 x = self.upconv16(upsample_add(self.selfdc_32(x, depth_en_feats[4]), rgb_en_feats[3])) # 1024 x = self.upconv8(upsample_add(self.selfdc_16(x, depth_en_feats[3]), rgb_en_feats[2])) # 512 x = self.upconv4(upsample_add(self.selfdc_8(x, depth_en_feats[2]), rgb_en_feats[1])) # 256 x = self.upconv2(upsample_add(x, rgb_en_feats[0])) # 64 x = self.upconv1(cus_sample(x, mode="scale", factors=2)) # 32 x = self.classifier(x) return dict(seg=x) def train_forward(self, data, **kwargs): assert not {"image", "depth", "mask"}.difference(set(data)), set(data) output = self.body(rgb_image=data["image"], depth_image=data["depth"]) loss, loss_str = self.cal_loss(all_preds=output, gts=data["mask"]) return dict(sal=output["seg"].sigmoid()), loss, loss_str def test_forward(self, data, **kwargs): output = self.body(rgb_image=data["image"], depth_image=data["depth"]) return output["seg"] def cal_loss(self, all_preds, gts): def cal_hel(pred, target, eps=1e-6): def edge_loss(pred, target): edge = target - F.avg_pool2d(target, kernel_size=5, stride=1, padding=2) edge[edge != 0] = 1 # input, kernel_size, stride=None, padding=0 numerator = (edge * (pred - target).abs_()).sum([2, 3]) denominator = edge.sum([2, 3]) + eps return numerator / denominator def region_loss(pred, target): # 该部分损失更强调前景区域内部或者背景区域内部的预测一致性 numerator_fore = (target - target * pred).sum([2, 3]) denominator_fore = target.sum([2, 3]) + eps numerator_back = ((1 - target) * pred).sum([2, 3]) denominator_back = (1 - target).sum([2, 3]) + eps return numerator_fore / denominator_fore + numerator_back / denominator_back edge_loss = edge_loss(pred, target) region_loss = region_loss(pred, target) return (edge_loss + region_loss).mean() losses = [] loss_str = [] # for main for name, preds in all_preds.items(): sod_loss = F.binary_cross_entropy_with_logits( input=preds, target=cus_sample(gts, mode="size", factors=preds.shape[2:]), reduction="mean" ) losses.append(sod_loss) loss_str.append(f"BCE:{sod_loss.item():.5f}") hel_loss = cal_hel(pred=preds.sigmoid(), target=cus_sample(gts, mode="size", factors=preds.shape[2:])) losses.append(hel_loss) loss_str.append(f"HEL:{hel_loss.item():.5f}") return sum(losses), " ".join(loss_str)
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/methods/classic_methods/MINet.py
methods/classic_methods/MINet.py
# -*- coding: utf-8 -*- import timm import torch from torch import nn from torch.nn.functional import binary_cross_entropy_with_logits from methods.module.base_model import BasicModelClass from methods.module.conv_block import ConvBNReLU from utils.builder import MODELS from utils.ops.tensor_ops import cus_sample, upsample_add def down_2x(x): return cus_sample(x, mode="scale", factors=0.5) def up_2x(x): return cus_sample(x, mode="scale", factors=2) def up_to(x, hw): return cus_sample(x, mode="size", factors=hw) class SIM(nn.Module): def __init__(self, h_C, l_C): super(SIM, self).__init__() self.h2l_0 = nn.Conv2d(h_C, l_C, 3, 1, 1) self.h2h_0 = nn.Conv2d(h_C, h_C, 3, 1, 1) self.bnl_0 = nn.BatchNorm2d(l_C) self.bnh_0 = nn.BatchNorm2d(h_C) self.h2h_1 = nn.Conv2d(h_C, h_C, 3, 1, 1) self.h2l_1 = nn.Conv2d(h_C, l_C, 3, 1, 1) self.l2h_1 = nn.Conv2d(l_C, h_C, 3, 1, 1) self.l2l_1 = nn.Conv2d(l_C, l_C, 3, 1, 1) self.bnl_1 = nn.BatchNorm2d(l_C) self.bnh_1 = nn.BatchNorm2d(h_C) self.h2h_2 = nn.Conv2d(h_C, h_C, 3, 1, 1) self.l2h_2 = nn.Conv2d(l_C, h_C, 3, 1, 1) self.bnh_2 = nn.BatchNorm2d(h_C) self.relu = nn.ReLU(True) def forward(self, x): h, w = x.shape[2:] # first conv x_h = self.relu(self.bnh_0(self.h2h_0(x))) x_l = self.relu(self.bnl_0(self.h2l_0(down_2x(x)))) # mid conv x_h2h = self.h2h_1(x_h) x_h2l = self.h2l_1(down_2x(x_h)) x_l2l = self.l2l_1(x_l) x_l2h = self.l2h_1(up_to(x_l, (h, w))) x_h = self.relu(self.bnh_1(x_h2h + x_l2h)) x_l = self.relu(self.bnl_1(x_l2l + x_h2l)) # last conv x_h2h = self.h2h_2(x_h) x_l2h = self.l2h_2(up_to(x_l, (h, w))) x_h = self.relu(self.bnh_2(x_h2h + x_l2h)) return x_h + x class conv_2nV1(nn.Module): def __init__(self, in_hc=64, in_lc=256, out_c=64, main=0): super(conv_2nV1, self).__init__() self.main = main mid_c = min(in_hc, in_lc) self.relu = nn.ReLU(True) # stage 0 self.h2h_0 = nn.Conv2d(in_hc, mid_c, 3, 1, 1) self.l2l_0 = nn.Conv2d(in_lc, mid_c, 3, 1, 1) self.bnh_0 = nn.BatchNorm2d(mid_c) self.bnl_0 = nn.BatchNorm2d(mid_c) # stage 1 self.h2h_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.h2l_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.l2h_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.l2l_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.bnl_1 = nn.BatchNorm2d(mid_c) self.bnh_1 = nn.BatchNorm2d(mid_c) if self.main == 0: # stage 2 self.h2h_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.l2h_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.bnh_2 = nn.BatchNorm2d(mid_c) # stage 3 self.h2h_3 = nn.Conv2d(mid_c, out_c, 3, 1, 1) self.bnh_3 = nn.BatchNorm2d(out_c) self.identity = nn.Conv2d(in_hc, out_c, 1) elif self.main == 1: # stage 2 self.h2l_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.l2l_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.bnl_2 = nn.BatchNorm2d(mid_c) # stage 3 self.l2l_3 = nn.Conv2d(mid_c, out_c, 3, 1, 1) self.bnl_3 = nn.BatchNorm2d(out_c) self.identity = nn.Conv2d(in_lc, out_c, 1) else: raise NotImplementedError def forward(self, in_h, in_l): # stage 0 h = self.relu(self.bnh_0(self.h2h_0(in_h))) l = self.relu(self.bnl_0(self.l2l_0(in_l))) # stage 1 h2h = self.h2h_1(h) h2l = self.h2l_1(down_2x(h)) l2l = self.l2l_1(l) l2h = self.l2h_1(up_2x(l)) h = self.relu(self.bnh_1(h2h + l2h)) l = self.relu(self.bnl_1(l2l + h2l)) if self.main == 0: # stage 2 l2h = self.l2h_2(up_2x(l)) h2h = self.h2h_2(h) h_fuse = self.relu(self.bnh_2(h2h + l2h)) # stage 3 out = self.relu(self.bnh_3(self.h2h_3(h_fuse)) + self.identity(in_h)) elif self.main == 1: # stage 2 h2l = self.h2l_2(down_2x(h)) l2l = self.l2l_2(l) l_fuse = self.relu(self.bnl_2(h2l + l2l)) # stage 3 out = self.relu(self.bnl_3(self.l2l_3(l_fuse)) + self.identity(in_l)) else: raise NotImplementedError return out class conv_3nV1(nn.Module): def __init__(self, in_hc=64, in_mc=256, in_lc=512, out_c=64): super(conv_3nV1, self).__init__() mid_c = min(in_hc, in_mc, in_lc) self.relu = nn.ReLU(True) # stage 0 self.h2h_0 = nn.Conv2d(in_hc, mid_c, 3, 1, 1) self.m2m_0 = nn.Conv2d(in_mc, mid_c, 3, 1, 1) self.l2l_0 = nn.Conv2d(in_lc, mid_c, 3, 1, 1) self.bnh_0 = nn.BatchNorm2d(mid_c) self.bnm_0 = nn.BatchNorm2d(mid_c) self.bnl_0 = nn.BatchNorm2d(mid_c) # stage 1 self.h2h_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.h2m_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.m2h_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.m2m_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.m2l_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.l2m_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.l2l_1 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.bnh_1 = nn.BatchNorm2d(mid_c) self.bnm_1 = nn.BatchNorm2d(mid_c) self.bnl_1 = nn.BatchNorm2d(mid_c) # stage 2 self.h2m_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.l2m_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.m2m_2 = nn.Conv2d(mid_c, mid_c, 3, 1, 1) self.bnm_2 = nn.BatchNorm2d(mid_c) # stage 3 self.m2m_3 = nn.Conv2d(mid_c, out_c, 3, 1, 1) self.bnm_3 = nn.BatchNorm2d(out_c) self.identity = nn.Conv2d(in_mc, out_c, 1) def forward(self, in_h, in_m, in_l): # stage 0 h = self.relu(self.bnh_0(self.h2h_0(in_h))) m = self.relu(self.bnm_0(self.m2m_0(in_m))) l = self.relu(self.bnl_0(self.l2l_0(in_l))) # stage 1 h2h = self.h2h_1(h) m2h = self.m2h_1(up_2x(m)) h2m = self.h2m_1(down_2x(h)) m2m = self.m2m_1(m) l2m = self.l2m_1(up_2x(l)) m2l = self.m2l_1(down_2x(m)) l2l = self.l2l_1(l) h = self.relu(self.bnh_1(h2h + m2h)) m = self.relu(self.bnm_1(h2m + m2m + l2m)) l = self.relu(self.bnl_1(m2l + l2l)) # stage 2 h2m = self.h2m_2(down_2x(h)) m2m = self.m2m_2(m) l2m = self.l2m_2(up_2x(l)) m = self.relu(self.bnm_2(h2m + m2m + l2m)) # stage 3 out = self.relu(self.bnm_3(self.m2m_3(m)) + self.identity(in_m)) return out class AIM(nn.Module): def __init__(self, iC_list, oC_list): super(AIM, self).__init__() ic0, ic1, ic2, ic3, ic4 = iC_list oc0, oc1, oc2, oc3, oc4 = oC_list self.conv0 = conv_2nV1(in_hc=ic0, in_lc=ic1, out_c=oc0, main=0) self.conv1 = conv_3nV1(in_hc=ic0, in_mc=ic1, in_lc=ic2, out_c=oc1) self.conv2 = conv_3nV1(in_hc=ic1, in_mc=ic2, in_lc=ic3, out_c=oc2) self.conv3 = conv_3nV1(in_hc=ic2, in_mc=ic3, in_lc=ic4, out_c=oc3) self.conv4 = conv_2nV1(in_hc=ic3, in_lc=ic4, out_c=oc4, main=1) def forward(self, *xs): # in_data_2, in_data_4, in_data_8, in_data_16, in_data_32 out_xs = [] out_xs.append(self.conv0(xs[0], xs[1])) out_xs.append(self.conv1(xs[0], xs[1], xs[2])) out_xs.append(self.conv2(xs[1], xs[2], xs[3])) out_xs.append(self.conv3(xs[2], xs[3], xs[4])) out_xs.append(self.conv4(xs[3], xs[4])) return out_xs class BaseMINet(BasicModelClass): def train_forward(self, data, **kwargs): assert not {"image", "mask"}.difference(set(data)), set(data) output = self.body(rgb_image=data["image"]) loss, loss_str = self.cal_loss(all_preds=output, gts=data["mask"]) return dict(sal=output["seg"].sigmoid()), loss, loss_str def test_forward(self, data, **kwargs): output = self.body(rgb_image=data["image"]) return output["seg"] def cal_loss(self, all_preds: dict, gts: torch.Tensor): """ loss, loss_str = self.cal_loss(all_preds=output, gts=data["mask"]) """ def cal_cel(pred, target): pred = pred.sigmoid() intersection = pred * target numerator = (pred - intersection).sum() + (target - intersection).sum() denominator = pred.sum() + target.sum() return numerator / (denominator + 1e-6) losses = [] loss_str = [] # for main for name, preds in all_preds.items(): resized_gts = cus_sample(gts, mode="size", factors=preds.shape[2:]) sod_loss = binary_cross_entropy_with_logits(input=preds, target=resized_gts, reduction="mean") losses.append(sod_loss) loss_str.append(f"{name}_BCE: {sod_loss.item():.5f}") cel_loss = cal_cel(pred=preds, target=resized_gts) losses.append(cel_loss) loss_str.append(f"{name}_CEL: {cel_loss.item():.5f}") return sum(losses), " ".join(loss_str) @MODELS.register() class MINet_VGG16(BaseMINet): def __init__(self): super(MINet_VGG16, self).__init__() self.encoder = timm.create_model( model_name="vgg16_bn", pretrained=True, in_chans=3, features_only=True, output_stride=32 ) self.trans = AIM((64, 128, 256, 512, 512), (32, 64, 64, 64, 64)) self.sim16 = SIM(64, 32) self.sim8 = SIM(64, 32) self.sim4 = SIM(64, 32) self.sim2 = SIM(64, 32) self.sim1 = SIM(32, 16) self.upconv16 = ConvBNReLU(64, 64, kernel_size=3, stride=1, padding=1) self.upconv8 = ConvBNReLU(64, 64, kernel_size=3, stride=1, padding=1) self.upconv4 = ConvBNReLU(64, 64, kernel_size=3, stride=1, padding=1) self.upconv2 = ConvBNReLU(64, 32, kernel_size=3, stride=1, padding=1) self.upconv1 = ConvBNReLU(32, 32, kernel_size=3, stride=1, padding=1) self.classifier = nn.Conv2d(32, 1, 1) def body(self, rgb_image): en_feats = self.encoder(rgb_image) en_feats = self.trans(*en_feats) x = self.upconv16(self.sim16(en_feats[-1])) # 1024 x = self.upconv8(self.sim8(upsample_add(x, en_feats[-2]))) # 512 x = self.upconv4(self.sim4(upsample_add(x, en_feats[-3]))) # 256 x = self.upconv2(self.sim2(upsample_add(x, en_feats[-4]))) # 64 x = self.upconv1(self.sim1(upsample_add(x, en_feats[-5]))) # 32 x = self.classifier(x) return dict(seg=x) @MODELS.register() class MINet_Res50(BaseMINet): def __init__(self): super(MINet_Res50, self).__init__() self.encoder = timm.create_model( model_name="resnet50", pretrained=True, in_chans=3, features_only=True, output_stride=32 ) self.trans = AIM(iC_list=(64, 256, 512, 1024, 2048), oC_list=(64, 64, 64, 64, 64)) self.sim32 = SIM(64, 32) self.sim16 = SIM(64, 32) self.sim8 = SIM(64, 32) self.sim4 = SIM(64, 32) self.sim2 = SIM(64, 32) self.upconv32 = ConvBNReLU(64, 64, kernel_size=3, stride=1, padding=1) self.upconv16 = ConvBNReLU(64, 64, kernel_size=3, stride=1, padding=1) self.upconv8 = ConvBNReLU(64, 64, kernel_size=3, stride=1, padding=1) self.upconv4 = ConvBNReLU(64, 64, kernel_size=3, stride=1, padding=1) self.upconv2 = ConvBNReLU(64, 32, kernel_size=3, stride=1, padding=1) self.upconv1 = ConvBNReLU(32, 32, kernel_size=3, stride=1, padding=1) self.classifier = nn.Conv2d(32, 1, 1) def body(self, rgb_image): en_feats = self.encoder(rgb_image) en_feats = self.trans(*en_feats) x = self.upconv32(self.sim32(en_feats[-1])) # 1024 x = self.upconv16(self.sim16(upsample_add(x, en_feats[-2]))) x = self.upconv8(self.sim8(upsample_add(x, en_feats[-3]))) # 512 x = self.upconv4(self.sim4(upsample_add(x, en_feats[-4]))) # 256 x = self.upconv2(self.sim2(upsample_add(x, en_feats[-5]))) # 64 x = self.upconv1(cus_sample(x, mode="scale", factors=2)) # 32 x = self.classifier(x) return dict(seg=x)
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/methods/classic_methods/CPD.py
methods/classic_methods/CPD.py
# -*- coding: utf-8 -*- # @Time : 2021/6/1 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import math import numpy as np import scipy.stats as st import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as models from torch.nn import Parameter from methods.module.base_model import BasicModelClass from utils.builder import MODELS def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = nn.BatchNorm2d(planes) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class B2_ResNet(nn.Module): # ResNet50 with two branches def __init__(self): # self.inplanes = 128 self.inplanes = 64 super(B2_ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(Bottleneck, 64, 3) self.layer2 = self._make_layer(Bottleneck, 128, 4, stride=2) self.layer3_1 = self._make_layer(Bottleneck, 256, 6, stride=2) self.layer4_1 = self._make_layer(Bottleneck, 512, 3, stride=2) self.inplanes = 512 self.layer3_2 = self._make_layer(Bottleneck, 256, 6, stride=2) self.layer4_2 = self._make_layer(Bottleneck, 512, 3, stride=2) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2.0 / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x1 = self.layer3_1(x) x1 = self.layer4_1(x1) x2 = self.layer3_2(x) x2 = self.layer4_2(x2) return x1, x2 def gkern(kernlen=16, nsig=3): interval = (2 * nsig + 1.0) / kernlen x = np.linspace(-nsig - interval / 2.0, nsig + interval / 2.0, kernlen + 1) kern1d = np.diff(st.norm.cdf(x)) kernel_raw = np.sqrt(np.outer(kern1d, kern1d)) kernel = kernel_raw / kernel_raw.sum() return kernel def min_max_norm(in_): max_ = in_.max(3)[0].max(2)[0].unsqueeze(2).unsqueeze(3).expand_as(in_) min_ = in_.min(3)[0].min(2)[0].unsqueeze(2).unsqueeze(3).expand_as(in_) in_ = in_ - min_ return in_.div(max_ - min_ + 1e-8) class HA(nn.Module): # holistic attention module def __init__(self): super(HA, self).__init__() gaussian_kernel = np.float32(gkern(31, 4)) gaussian_kernel = gaussian_kernel[np.newaxis, np.newaxis, ...] self.gaussian_kernel = Parameter(torch.from_numpy(gaussian_kernel)) def forward(self, attention, x): soft_attention = F.conv2d(attention, self.gaussian_kernel, padding=15) soft_attention = min_max_norm(soft_attention) x = torch.mul(x, soft_attention.max(attention)) return x class BasicConv2d(nn.Module): def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1): super(BasicConv2d, self).__init__() self.conv = nn.Conv2d( in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=False, ) self.bn = nn.BatchNorm2d(out_planes) self.relu = nn.ReLU(inplace=True) def forward(self, x): x = self.conv(x) x = self.bn(x) return x class RFB(nn.Module): # RFB-like multi-scale module def __init__(self, in_channel, out_channel): super(RFB, self).__init__() self.relu = nn.ReLU(True) self.branch0 = nn.Sequential( BasicConv2d(in_channel, out_channel, 1), ) self.branch1 = nn.Sequential( BasicConv2d(in_channel, out_channel, 1), BasicConv2d(out_channel, out_channel, kernel_size=(1, 3), padding=(0, 1)), BasicConv2d(out_channel, out_channel, kernel_size=(3, 1), padding=(1, 0)), BasicConv2d(out_channel, out_channel, 3, padding=3, dilation=3), ) self.branch2 = nn.Sequential( BasicConv2d(in_channel, out_channel, 1), BasicConv2d(out_channel, out_channel, kernel_size=(1, 5), padding=(0, 2)), BasicConv2d(out_channel, out_channel, kernel_size=(5, 1), padding=(2, 0)), BasicConv2d(out_channel, out_channel, 3, padding=5, dilation=5), ) self.branch3 = nn.Sequential( BasicConv2d(in_channel, out_channel, 1), BasicConv2d(out_channel, out_channel, kernel_size=(1, 7), padding=(0, 3)), BasicConv2d(out_channel, out_channel, kernel_size=(7, 1), padding=(3, 0)), BasicConv2d(out_channel, out_channel, 3, padding=7, dilation=7), ) self.conv_cat = BasicConv2d(4 * out_channel, out_channel, 3, padding=1) self.conv_res = BasicConv2d(in_channel, out_channel, 1) def forward(self, x): x0 = self.branch0(x) x1 = self.branch1(x) x2 = self.branch2(x) x3 = self.branch3(x) x_cat = self.conv_cat(torch.cat((x0, x1, x2, x3), 1)) x = self.relu(x_cat + self.conv_res(x)) return x class aggregation(nn.Module): # dense aggregation, it can be replaced by other aggregation model, such as DSS, amulet, and so on. # used after MSF def __init__(self, channel): super(aggregation, self).__init__() self.relu = nn.ReLU(True) self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True) self.conv_upsample1 = BasicConv2d(channel, channel, 3, padding=1) self.conv_upsample2 = BasicConv2d(channel, channel, 3, padding=1) self.conv_upsample3 = BasicConv2d(channel, channel, 3, padding=1) self.conv_upsample4 = BasicConv2d(channel, channel, 3, padding=1) self.conv_upsample5 = BasicConv2d(2 * channel, 2 * channel, 3, padding=1) self.conv_concat2 = BasicConv2d(2 * channel, 2 * channel, 3, padding=1) self.conv_concat3 = BasicConv2d(3 * channel, 3 * channel, 3, padding=1) self.conv4 = BasicConv2d(3 * channel, 3 * channel, 3, padding=1) self.conv5 = nn.Conv2d(3 * channel, 1, 1) def forward(self, x1, x2, x3): x1_1 = x1 x2_1 = self.conv_upsample1(self.upsample(x1)) * x2 x3_1 = self.conv_upsample2(self.upsample(self.upsample(x1))) * self.conv_upsample3(self.upsample(x2)) * x3 x2_2 = torch.cat((x2_1, self.conv_upsample4(self.upsample(x1_1))), 1) x2_2 = self.conv_concat2(x2_2) x3_2 = torch.cat((x3_1, self.conv_upsample5(self.upsample(x2_2))), 1) x3_2 = self.conv_concat3(x3_2) x = self.conv4(x3_2) x = self.conv5(x) return x @MODELS.register() class CPD_R50(BasicModelClass): def __init__(self): super().__init__() self.resnet = B2_ResNet() channel = 32 self.rfb2_1 = RFB(512, channel) self.rfb3_1 = RFB(1024, channel) self.rfb4_1 = RFB(2048, channel) self.agg1 = aggregation(channel) self.rfb2_2 = RFB(512, channel) self.rfb3_2 = RFB(1024, channel) self.rfb4_2 = RFB(2048, channel) self.agg2 = aggregation(channel) self.upsample = nn.Upsample(scale_factor=8, mode="bilinear", align_corners=True) self.HA = HA() if self.training: self.initialize_weights() def initialize_weights(self): res50 = models.resnet50(pretrained=True, progress=True) pretrained_dict = res50.state_dict() all_params = {} for k, v in self.resnet.state_dict().items(): if k in pretrained_dict.keys(): v = pretrained_dict[k] all_params[k] = v elif "_1" in k: name = k.split("_1")[0] + k.split("_1")[1] v = pretrained_dict[name] all_params[k] = v elif "_2" in k: name = k.split("_2")[0] + k.split("_2")[1] v = pretrained_dict[name] all_params[k] = v assert len(all_params.keys()) == len(self.resnet.state_dict().keys()) self.resnet.load_state_dict(all_params) def body(self, x): x = self.resnet.conv1(x) x = self.resnet.bn1(x) x = self.resnet.relu(x) x = self.resnet.maxpool(x) x1 = self.resnet.layer1(x) # 256 x 64 x 64 x2 = self.resnet.layer2(x1) # 512 x 32 x 32 x2_1 = x2 x3_1 = self.resnet.layer3_1(x2_1) # 1024 x 16 x 16 x4_1 = self.resnet.layer4_1(x3_1) # 2048 x 8 x 8 x2_1 = self.rfb2_1(x2_1) x3_1 = self.rfb3_1(x3_1) x4_1 = self.rfb4_1(x4_1) attention_map = self.agg1(x4_1, x3_1, x2_1) x2_2 = self.HA(attention_map.sigmoid(), x2) x3_2 = self.resnet.layer3_2(x2_2) # 1024 x 16 x 16 x4_2 = self.resnet.layer4_2(x3_2) # 2048 x 8 x 8 x2_2 = self.rfb2_2(x2_2) x3_2 = self.rfb3_2(x3_2) x4_2 = self.rfb4_2(x4_2) detection_map = self.agg2(x4_2, x3_2, x2_2) return dict(seg=detection_map, attn=attention_map) def train_forward(self, data, **kwargs): assert not {"image", "mask"}.difference(set(data)), set(data) output = self.body(x=data["image"]) loss, loss_str = self.cal_loss(all_preds=output, gts=data["mask"]) return output["seg"].sigmoid(), loss, loss_str def test_forward(self, data, **kwargs): output = self.body(x=data["image"]) return output["seg"].sigmoid()
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/methods/classic_methods/__init__.py
methods/classic_methods/__init__.py
# -*- coding: utf-8 -*- # @Time : 2021/7/25 # @Author : Lart Pang # @GitHub : https://github.com/lartpang
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/methods/module/base_model.py
methods/module/base_model.py
# -*- coding: utf-8 -*- # @Time : 2021/4/14 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import abc import torch.nn as nn class BasicModelClass(nn.Module): def __init__(self): super(BasicModelClass, self).__init__() self.is_training = True def forward(self, *args, **kwargs): if not self.is_training or not self.training: results = self.test_forward(*args, **kwargs) else: results = self.train_forward(*args, **kwargs) return results @abc.abstractmethod def train_forward(self, *args, **kwargs): pass @abc.abstractmethod def test_forward(self, *args, **kwargs): pass @abc.abstractmethod def cal_loss(self, *args, **kwargs): """ losses = [] loss_str = [] # for main for name, preds in all_preds.items(): sod_loss = binary_cross_entropy_with_logits( input=preds, target=cus_sample(gts, mode="size", factors=preds.shape[2:]), reduction="mean" ) losses.append(sod_loss) loss_str.append(f"{name}:{sod_loss.item():.5f}") loss = sum(losses) loss_str = " ".join(loss_str) return loss, loss_str """ pass
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/methods/module/__init__.py
methods/module/__init__.py
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/methods/module/conv_block.py
methods/module/conv_block.py
# -*- coding: utf-8 -*- # @Time : 2020 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import torch.nn as nn from timm.models.layers import to_2tuple def _get_act_fn(act_name, inplace=True): if act_name == "relu": return nn.ReLU(inplace=inplace) elif act_name == "leaklyrelu": return nn.LeakyReLU(negative_slope=0.1, inplace=inplace) elif act_name == "gelu": return nn.GELU() else: raise NotImplementedError class ConvBNReLU(nn.Sequential): def __init__( self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False, act_name="relu", is_transposed=False, ): """ Convolution-BatchNormalization-ActivationLayer :param in_planes: :param out_planes: :param kernel_size: :param stride: :param padding: :param dilation: :param groups: :param bias: :param act_name: None denote it doesn't use the activation layer. :param is_transposed: True -> nn.ConvTranspose2d, False -> nn.Conv2d """ super().__init__() if is_transposed: conv_module = nn.ConvTranspose2d else: conv_module = nn.Conv2d self.add_module( name="conv", module=conv_module( in_planes, out_planes, kernel_size=kernel_size, stride=to_2tuple(stride), padding=to_2tuple(padding), dilation=to_2tuple(dilation), groups=groups, bias=bias, ), ) self.add_module(name="bn", module=nn.BatchNorm2d(out_planes)) if act_name is not None: self.add_module(name=act_name, module=_get_act_fn(act_name=act_name)) class ConvGNReLU(nn.Sequential): def __init__( self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, gn_groups=4, bias=False, act_name="relu", inplace=True, ): """ 执行流程Conv2d => GroupNormalization [=> Activation] Args: in_planes: 模块输入通道数 out_planes: 模块输出通道数 kernel_size: 内部卷积操作的卷积核大小 stride: 卷积步长 padding: 卷积padding dilation: 卷积的扩张率 groups: 卷积分组数,需满足pytorch自身要求 gn_groups: GroupNormalization的分组数,默认为4 bias: 是否启用卷积的偏置,默认为False act_name: 使用的激活函数,默认为relu,设置为None的时候则不使用激活函数 inplace: 设置激活函数的inplace参数 """ super(ConvGNReLU, self).__init__() self.add_module( name="conv", module=nn.Conv2d( in_planes, out_planes, kernel_size=kernel_size, stride=to_2tuple(stride), padding=to_2tuple(padding), dilation=to_2tuple(dilation), groups=groups, bias=bias, ), ) self.add_module(name="gn", module=nn.GroupNorm(num_groups=gn_groups, num_channels=out_planes)) if act_name is not None: self.add_module(name=act_name, module=_get_act_fn(act_name=act_name, inplace=inplace))
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/methods/zoomnet/__init__.py
methods/zoomnet/__init__.py
# -*- coding: utf-8 -*- # @Time : 2021/7/24 # @Author : Lart Pang # @GitHub : https://github.com/lartpang
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/methods/zoomnet/zoomnet.py
methods/zoomnet/zoomnet.py
import numpy as np import timm import torch import torch.nn.functional as F from torch import nn from torch.utils.checkpoint import checkpoint from methods.module.base_model import BasicModelClass from methods.module.conv_block import ConvBNReLU from utils.builder import MODELS from utils.ops import cus_sample class ASPP(nn.Module): def __init__(self, in_dim, out_dim): super(ASPP, self).__init__() self.conv1 = ConvBNReLU(in_dim, out_dim, kernel_size=1) self.conv2 = ConvBNReLU(in_dim, out_dim, kernel_size=3, dilation=2, padding=2) self.conv3 = ConvBNReLU(in_dim, out_dim, kernel_size=3, dilation=5, padding=5) self.conv4 = ConvBNReLU(in_dim, out_dim, kernel_size=3, dilation=7, padding=7) self.conv5 = ConvBNReLU(in_dim, out_dim, kernel_size=1) self.fuse = ConvBNReLU(5 * out_dim, out_dim, 3, 1, 1) def forward(self, x): conv1 = self.conv1(x) conv2 = self.conv2(x) conv3 = self.conv3(x) conv4 = self.conv4(x) conv5 = self.conv5(cus_sample(x.mean((2, 3), keepdim=True), mode="size", factors=x.size()[2:])) return self.fuse(torch.cat((conv1, conv2, conv3, conv4, conv5), 1)) class TransLayer(nn.Module): def __init__(self, out_c, last_module=ASPP): super().__init__() self.c5_down = nn.Sequential( # ConvBNReLU(2048, 256, 3, 1, 1), last_module(in_dim=2048, out_dim=out_c), ) self.c4_down = nn.Sequential(ConvBNReLU(1024, out_c, 3, 1, 1)) self.c3_down = nn.Sequential(ConvBNReLU(512, out_c, 3, 1, 1)) self.c2_down = nn.Sequential(ConvBNReLU(256, out_c, 3, 1, 1)) self.c1_down = nn.Sequential(ConvBNReLU(64, out_c, 3, 1, 1)) def forward(self, xs): assert isinstance(xs, (tuple, list)) assert len(xs) == 5 c1, c2, c3, c4, c5 = xs c5 = self.c5_down(c5) c4 = self.c4_down(c4) c3 = self.c3_down(c3) c2 = self.c2_down(c2) c1 = self.c1_down(c1) return c5, c4, c3, c2, c1 class SIU(nn.Module): def __init__(self, in_dim): super().__init__() self.conv_l_pre_down = ConvBNReLU(in_dim, in_dim, 5, stride=1, padding=2) self.conv_l_post_down = ConvBNReLU(in_dim, in_dim, 3, 1, 1) self.conv_m = ConvBNReLU(in_dim, in_dim, 3, 1, 1) self.conv_s_pre_up = ConvBNReLU(in_dim, in_dim, 3, 1, 1) self.conv_s_post_up = ConvBNReLU(in_dim, in_dim, 3, 1, 1) self.trans = nn.Sequential( ConvBNReLU(3 * in_dim, in_dim, 1), ConvBNReLU(in_dim, in_dim, 3, 1, 1), ConvBNReLU(in_dim, in_dim, 3, 1, 1), nn.Conv2d(in_dim, 3, 1), ) def forward(self, l, m, s, return_feats=False): """l,m,s表示大中小三个尺度,最终会被整合到m这个尺度上""" tgt_size = m.shape[2:] # 尺度缩小 l = self.conv_l_pre_down(l) l = F.adaptive_max_pool2d(l, tgt_size) + F.adaptive_avg_pool2d(l, tgt_size) l = self.conv_l_post_down(l) # 尺度不变 m = self.conv_m(m) # 尺度增加(这里使用上采样之后卷积的策略) s = self.conv_s_pre_up(s) s = cus_sample(s, mode="size", factors=m.shape[2:]) s = self.conv_s_post_up(s) attn = self.trans(torch.cat([l, m, s], dim=1)) attn_l, attn_m, attn_s = torch.softmax(attn, dim=1).chunk(3, dim=1) lms = attn_l * l + attn_m * m + attn_s * s if return_feats: return lms, dict(attn_l=attn_l, attn_m=attn_m, attn_s=attn_s, l=l, m=m, s=s) return lms class HMU(nn.Module): def __init__(self, in_c, num_groups=4, hidden_dim=None): super().__init__() self.num_groups = num_groups hidden_dim = hidden_dim or in_c // 2 expand_dim = hidden_dim * num_groups self.expand_conv = ConvBNReLU(in_c, expand_dim, 1) self.gate_genator = nn.Sequential( nn.AdaptiveAvgPool2d((1, 1)), nn.Conv2d(num_groups * hidden_dim, hidden_dim, 1), nn.ReLU(True), nn.Conv2d(hidden_dim, num_groups * hidden_dim, 1), nn.Softmax(dim=1), ) self.interact = nn.ModuleDict() self.interact["0"] = ConvBNReLU(hidden_dim, 3 * hidden_dim, 3, 1, 1) for group_id in range(1, num_groups - 1): self.interact[str(group_id)] = ConvBNReLU(2 * hidden_dim, 3 * hidden_dim, 3, 1, 1) self.interact[str(num_groups - 1)] = ConvBNReLU(2 * hidden_dim, 2 * hidden_dim, 3, 1, 1) self.fuse = nn.Sequential(nn.Conv2d(num_groups * hidden_dim, in_c, 3, 1, 1), nn.BatchNorm2d(in_c)) self.final_relu = nn.ReLU(True) def forward(self, x): xs = self.expand_conv(x).chunk(self.num_groups, dim=1) outs = [] branch_out = self.interact["0"](xs[0]) outs.append(branch_out.chunk(3, dim=1)) for group_id in range(1, self.num_groups - 1): branch_out = self.interact[str(group_id)](torch.cat([xs[group_id], outs[group_id - 1][1]], dim=1)) outs.append(branch_out.chunk(3, dim=1)) group_id = self.num_groups - 1 branch_out = self.interact[str(group_id)](torch.cat([xs[group_id], outs[group_id - 1][1]], dim=1)) outs.append(branch_out.chunk(2, dim=1)) out = torch.cat([o[0] for o in outs], dim=1) gate = self.gate_genator(torch.cat([o[-1] for o in outs], dim=1)) out = self.fuse(out * gate) return self.final_relu(out + x) def get_coef(iter_percentage, method): if method == "linear": milestones = (0.3, 0.7) coef_range = (0, 1) min_point, max_point = min(milestones), max(milestones) min_coef, max_coef = min(coef_range), max(coef_range) if iter_percentage < min_point: ual_coef = min_coef elif iter_percentage > max_point: ual_coef = max_coef else: ratio = (max_coef - min_coef) / (max_point - min_point) ual_coef = ratio * (iter_percentage - min_point) elif method == "cos": coef_range = (0, 1) min_coef, max_coef = min(coef_range), max(coef_range) normalized_coef = (1 - np.cos(iter_percentage * np.pi)) / 2 ual_coef = normalized_coef * (max_coef - min_coef) + min_coef else: ual_coef = 1.0 return ual_coef def cal_ual(seg_logits, seg_gts): assert seg_logits.shape == seg_gts.shape, (seg_logits.shape, seg_gts.shape) sigmoid_x = seg_logits.sigmoid() loss_map = 1 - (2 * sigmoid_x - 1).abs().pow(2) return loss_map.mean() @MODELS.register() class ZoomNet(BasicModelClass): def __init__(self): super().__init__() self.shared_encoder = timm.create_model(model_name="resnet50", pretrained=True, in_chans=3, features_only=True) self.translayer = TransLayer(out_c=64) # [c5, c4, c3, c2, c1] self.merge_layers = nn.ModuleList([SIU(in_dim=in_c) for in_c in (64, 64, 64, 64, 64)]) self.d5 = nn.Sequential(HMU(64, num_groups=6, hidden_dim=32)) self.d4 = nn.Sequential(HMU(64, num_groups=6, hidden_dim=32)) self.d3 = nn.Sequential(HMU(64, num_groups=6, hidden_dim=32)) self.d2 = nn.Sequential(HMU(64, num_groups=6, hidden_dim=32)) self.d1 = nn.Sequential(HMU(64, num_groups=6, hidden_dim=32)) self.out_layer_00 = ConvBNReLU(64, 32, 3, 1, 1) self.out_layer_01 = nn.Conv2d(32, 1, 1) def encoder_translayer(self, x): en_feats = self.shared_encoder(x) trans_feats = self.translayer(en_feats) return trans_feats def body(self, l_scale, m_scale, s_scale): l_trans_feats = self.encoder_translayer(l_scale) m_trans_feats = self.encoder_translayer(m_scale) s_trans_feats = self.encoder_translayer(s_scale) feats = [] for l, m, s, layer in zip(l_trans_feats, m_trans_feats, s_trans_feats, self.merge_layers): siu_outs = layer(l=l, m=m, s=s) feats.append(siu_outs) x = self.d5(feats[0]) x = cus_sample(x, mode="scale", factors=2) x = self.d4(x + feats[1]) x = cus_sample(x, mode="scale", factors=2) x = self.d3(x + feats[2]) x = cus_sample(x, mode="scale", factors=2) x = self.d2(x + feats[3]) x = cus_sample(x, mode="scale", factors=2) x = self.d1(x + feats[4]) x = cus_sample(x, mode="scale", factors=2) logits = self.out_layer_01(self.out_layer_00(x)) return dict(seg=logits) def train_forward(self, data, **kwargs): assert not {"image1.5", "image1.0", "image0.5", "mask"}.difference(set(data)), set(data) output = self.body( l_scale=data["image1.5"], m_scale=data["image1.0"], s_scale=data["image0.5"], ) loss, loss_str = self.cal_loss( all_preds=output, gts=data["mask"], iter_percentage=kwargs["curr"]["iter_percentage"], ) return dict(sal=output["seg"].sigmoid()), loss, loss_str def test_forward(self, data, **kwargs): output = self.body( l_scale=data["image1.5"], m_scale=data["image1.0"], s_scale=data["image0.5"], ) return output["seg"] def cal_loss(self, all_preds: dict, gts: torch.Tensor, method="cos", iter_percentage: float = 0): ual_coef = get_coef(iter_percentage, method) losses = [] loss_str = [] # for main for name, preds in all_preds.items(): resized_gts = cus_sample(gts, mode="size", factors=preds.shape[2:]) sod_loss = F.binary_cross_entropy_with_logits(input=preds, target=resized_gts, reduction="mean") losses.append(sod_loss) loss_str.append(f"{name}_BCE: {sod_loss.item():.5f}") ual_loss = cal_ual(seg_logits=preds, seg_gts=resized_gts) ual_loss *= ual_coef losses.append(ual_loss) loss_str.append(f"{name}_UAL_{ual_coef:.5f}: {ual_loss.item():.5f}") return sum(losses), " ".join(loss_str) def get_grouped_params(self): param_groups = {} for name, param in self.named_parameters(): if name.startswith("shared_encoder.layer"): param_groups.setdefault("pretrained", []).append(param) elif name.startswith("shared_encoder."): param_groups.setdefault("fixed", []).append(param) else: param_groups.setdefault("retrained", []).append(param) return param_groups @MODELS.register() class ZoomNet_CK(ZoomNet): def __init__(self): super().__init__() self.dummy = torch.ones(1, dtype=torch.float32, requires_grad=True) def encoder(self, x, dummy_arg=None): assert dummy_arg is not None x0, x1, x2, x3, x4 = self.shared_encoder(x) return x0, x1, x2, x3, x4 def trans(self, x0, x1, x2, x3, x4): x5, x4, x3, x2, x1 = self.translayer([x0, x1, x2, x3, x4]) return x5, x4, x3, x2, x1 def decoder(self, x5, x4, x3, x2, x1): x = self.d5(x5) x = cus_sample(x, mode="scale", factors=2) x = self.d4(x + x4) x = cus_sample(x, mode="scale", factors=2) x = self.d3(x + x3) x = cus_sample(x, mode="scale", factors=2) x = self.d2(x + x2) x = cus_sample(x, mode="scale", factors=2) x = self.d1(x + x1) x = cus_sample(x, mode="scale", factors=2) logits = self.out_layer_01(self.out_layer_00(x)) return logits def body(self, l_scale, m_scale, s_scale): l_trans_feats = checkpoint(self.encoder, l_scale, self.dummy) m_trans_feats = checkpoint(self.encoder, m_scale, self.dummy) s_trans_feats = checkpoint(self.encoder, s_scale, self.dummy) l_trans_feats = checkpoint(self.trans, *l_trans_feats) m_trans_feats = checkpoint(self.trans, *m_trans_feats) s_trans_feats = checkpoint(self.trans, *s_trans_feats) feats = [] for layer_idx, (l, m, s) in enumerate(zip(l_trans_feats, m_trans_feats, s_trans_feats)): siu_outs = checkpoint(self.merge_layers[layer_idx], l, m, s) feats.append(siu_outs) logits = checkpoint(self.decoder, *feats) return dict(seg=logits)
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/configurator.py
utils/configurator.py
# -*- coding: utf-8 -*- # @Time : 2021/6/1 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import ast import os.path as osp import platform import shutil import sys import tempfile import warnings from importlib import import_module from addict import Dict from yapf.yapflib.yapf_api import FormatCode from utils.misc import check_file_exist, import_modules_from_strings BASE_KEY = "_base_" DELETE_KEY = "_delete_" RESERVED_KEYS = ["filename", "text", "pretty_text"] class _ConfigDict(Dict): def __missing__(self, name): raise KeyError(name) def __getattr__(self, name): try: value = super(_ConfigDict, self).__getattr__(name) except KeyError: ex = AttributeError(f"'{self.__class__.__name__}' object has no " f"attribute '{name}'") except Exception as e: ex = e else: return value raise ex class Configurator: """A facility for config and config files. Borrow from mmcv. """ @staticmethod def _validate_py_syntax(filename): with open(filename, "r", encoding="utf-8") as f: # Setting encoding explicitly to resolve coding issue on windows content = f.read() try: ast.parse(content) except SyntaxError as e: raise SyntaxError("There are syntax errors in config " f"file {filename}: {e}") @staticmethod def _file2dict(filename): filename = osp.abspath(osp.expanduser(filename)) check_file_exist(filename) fileExtname = osp.splitext(filename)[1] if fileExtname not in [".py", ".json", ".yaml", ".yml"]: raise IOError("Only py/yml/yaml/json type are supported now!") with tempfile.TemporaryDirectory() as temp_config_dir: temp_config_file = tempfile.NamedTemporaryFile(dir=temp_config_dir, suffix=fileExtname) if platform.system() == "Windows": temp_config_file.close() temp_config_name = osp.basename(temp_config_file.name) # Substitute predefined variables shutil.copyfile(filename, temp_config_file.name) if filename.endswith(".py"): temp_module_name = osp.splitext(temp_config_name)[0] sys.path.insert(0, temp_config_dir) Configurator._validate_py_syntax(filename) mod = import_module(temp_module_name) sys.path.pop(0) cfg_dict = {name: value for name, value in mod.__dict__.items() if not name.startswith("__")} # delete imported module del sys.modules[temp_module_name] else: raise NotImplementedError # close temp file temp_config_file.close() cfg_text = filename + "\n" with open(filename, "r", encoding="utf-8") as f: # Setting encoding explicitly to resolve coding issue on windows cfg_text += f.read() if BASE_KEY in cfg_dict: cfg_dir = osp.dirname(filename) base_filename = cfg_dict.pop(BASE_KEY) base_filename = base_filename if isinstance(base_filename, list) else [base_filename] cfg_dict_list = list() cfg_text_list = list() for f in base_filename: _cfg_dict, _cfg_text = Configurator._file2dict(osp.join(cfg_dir, f)) cfg_dict_list.append(_cfg_dict) cfg_text_list.append(_cfg_text) base_cfg_dict = dict() for c in cfg_dict_list: if len(base_cfg_dict.keys() & c.keys()) > 0: raise KeyError("Duplicate key is not allowed among bases") base_cfg_dict.update(c) base_cfg_dict = Configurator._merge_a_into_b(cfg_dict, base_cfg_dict) cfg_dict = base_cfg_dict # merge cfg_text cfg_text_list.append(cfg_text) cfg_text = "\n".join(cfg_text_list) return cfg_dict, cfg_text @staticmethod def _merge_a_into_b(a, b, allow_list_keys=False): """merge dict ``a`` into dict ``b`` (non-inplace). Values in ``a`` will overwrite ``b``. ``b`` is copied first to avoid in-place modifications. Args: a (dict): The source dict to be merged into ``b``. b (dict): The origin dict to be fetch keys from ``a``. allow_list_keys (bool): If True, int string keys (e.g. '0', '1') are allowed in source ``a`` and will replace the element of the corresponding index in b if b is a list. Default: False. Returns: dict: The modified dict of ``b`` using ``a``. """ b = b.copy() for k, v in a.items(): if allow_list_keys and k.isdigit() and isinstance(b, list): k = int(k) if len(b) <= k: raise KeyError(f"Index {k} exceeds the length of list {b}") b[k] = Configurator._merge_a_into_b(v, b[k], allow_list_keys) elif isinstance(v, dict) and k in b and not v.pop(DELETE_KEY, False): allowed_types = (dict, list) if allow_list_keys else dict if not isinstance(b[k], allowed_types): raise TypeError( f"{k}={v} in child config cannot inherit from base " f"because {k} is a dict in the child config but is of " f"type {type(b[k])} in base config. You may set " f"`{DELETE_KEY}=True` to ignore the base config" ) b[k] = Configurator._merge_a_into_b(v, b[k], allow_list_keys) else: b[k] = v return b @staticmethod def fromfile(filename, import_custom_modules=True): cfg_dict, cfg_text = Configurator._file2dict(filename) if import_custom_modules and cfg_dict.get("custom_imports", None): import_modules_from_strings(**cfg_dict["custom_imports"]) return Configurator(cfg_dict, cfg_text=cfg_text, filename=filename) @staticmethod def fromstring(cfg_str, file_format): """Generate config from config str. Args: cfg_str (str): Configurator str. file_format (str): Configurator file format corresponding to the config str. Only py/yml/yaml/json type are supported now! Returns: obj:`Configurator`: Configurator obj. """ if file_format not in [".py", ".json", ".yaml", ".yml"]: raise IOError("Only py/yml/yaml/json type are supported now!") if file_format != ".py" and "dict(" in cfg_str: # check if users specify a wrong suffix for python warnings.warn('Please check "file_format", the file format may be .py') with tempfile.NamedTemporaryFile("w", suffix=file_format) as temp_file: temp_file.write(cfg_str) temp_file.flush() cfg = Configurator.fromfile(temp_file.name) return cfg def __init__(self, cfg_dict=None, cfg_text=None, filename=None): if cfg_dict is None: cfg_dict = dict() elif not isinstance(cfg_dict, dict): raise TypeError("cfg_dict must be a dict, but " f"got {type(cfg_dict)}") for key in cfg_dict: if key in RESERVED_KEYS: raise KeyError(f"{key} is reserved for config file") super(Configurator, self).__setattr__("_cfg_dict", _ConfigDict(cfg_dict)) super(Configurator, self).__setattr__("_filename", filename) if cfg_text: text = cfg_text elif filename: with open(filename, "r") as f: text = f.read() else: text = "" super(Configurator, self).__setattr__("_text", text) @property def filename(self): return self._filename @property def text(self): return self._text @property def pretty_text(self): indent = 4 def _indent(s_, num_spaces): s = s_.split("\n") if len(s) == 1: return s_ first = s.pop(0) s = [(num_spaces * " ") + line for line in s] s = "\n".join(s) s = first + "\n" + s return s def _format_basic_types(k, v, use_mapping=False): if isinstance(v, str): v_str = f"'{v}'" else: v_str = str(v) if use_mapping: k_str = f"'{k}'" if isinstance(k, str) else str(k) attr_str = f"{k_str}: {v_str}" else: attr_str = f"{str(k)}={v_str}" attr_str = _indent(attr_str, indent) return attr_str def _format_list(k, v, use_mapping=False): # check if all items in the list are dict if all(isinstance(_, dict) for _ in v): v_str = "[\n" v_str += "\n".join(f"dict({_indent(_format_dict(v_), indent)})," for v_ in v).rstrip(",") if use_mapping: k_str = f"'{k}'" if isinstance(k, str) else str(k) attr_str = f"{k_str}: {v_str}" else: attr_str = f"{str(k)}={v_str}" attr_str = _indent(attr_str, indent) + "]" else: attr_str = _format_basic_types(k, v, use_mapping) return attr_str def _contain_invalid_identifier(dict_str): contain_invalid_identifier = False for key_name in dict_str: contain_invalid_identifier |= not str(key_name).isidentifier() return contain_invalid_identifier def _format_dict(input_dict, outest_level=False): r = "" s = [] use_mapping = _contain_invalid_identifier(input_dict) if use_mapping: r += "{" for idx, (k, v) in enumerate(input_dict.items()): is_last = idx >= len(input_dict) - 1 end = "" if outest_level or is_last else "," if isinstance(v, dict): v_str = "\n" + _format_dict(v) if use_mapping: k_str = f"'{k}'" if isinstance(k, str) else str(k) attr_str = f"{k_str}: dict({v_str}" else: attr_str = f"{str(k)}=dict({v_str}" attr_str = _indent(attr_str, indent) + ")" + end elif isinstance(v, list): attr_str = _format_list(k, v, use_mapping) + end else: attr_str = _format_basic_types(k, v, use_mapping) + end s.append(attr_str) r += "\n".join(s) if use_mapping: r += "}" return r cfg_dict = self._cfg_dict.to_dict() text = _format_dict(cfg_dict, outest_level=True) # copied from setup.cfg yapf_style = dict( based_on_style="pep8", blank_line_before_nested_class_or_def=True, split_before_expression_after_opening_paren=True, ) text, _ = FormatCode(text, style_config=yapf_style, verify=True) return text def __repr__(self): return f"Configurator (path: {self.filename}): {self._cfg_dict.__repr__()}" def __len__(self): return len(self._cfg_dict) def __getattr__(self, name): return getattr(self._cfg_dict, name) def __getitem__(self, name): return self._cfg_dict.__getitem__(name) def __setattr__(self, name, value): if isinstance(value, dict): value = _ConfigDict(value) self._cfg_dict.__setattr__(name, value) def __setitem__(self, name, value): if isinstance(value, dict): value = _ConfigDict(value) self._cfg_dict.__setitem__(name, value) def __iter__(self): return iter(self._cfg_dict) def __getstate__(self): return (self._cfg_dict, self._filename, self._text) def __setstate__(self, state): _cfg_dict, _filename, _text = state super(Configurator, self).__setattr__("_cfg_dict", _cfg_dict) super(Configurator, self).__setattr__("_filename", _filename) super(Configurator, self).__setattr__("_text", _text) def dump(self, file=None): cfg_dict = super(Configurator, self).__getattribute__("_cfg_dict").to_dict() if self.filename.endswith(".py"): if file is None: return self.pretty_text else: with open(file, "w") as f: f.write(self.pretty_text) else: raise NotImplementedError def merge_from_dict(self, options, allow_list_keys=True): """Merge list into cfg_dict. Merge the dict parsed by MultipleKVAction into this cfg. Examples: >>> options = {'model.backbone.depth': 50, ... 'model.backbone.with_cp':True} >>> cfg = Configurator(dict(model=dict(backbone=dict(type='ResNet')))) >>> cfg.merge_from_dict(options) >>> cfg_dict = super(Configurator, self).__getattribute__('_cfg_dict') >>> assert cfg_dict == dict( ... model=dict(backbone=dict(depth=50, with_cp=True))) # Merge list element >>> cfg = Configurator(dict(pipeline=[ ... dict(type='LoadImage'), dict(type='LoadAnnotations')])) >>> options = dict(pipeline={'0': dict(type='SelfLoadImage')}) >>> cfg.merge_from_dict(options, allow_list_keys=True) >>> cfg_dict = super(Configurator, self).__getattribute__('_cfg_dict') >>> assert cfg_dict == dict(pipeline=[ ... dict(type='SelfLoadImage'), dict(type='LoadAnnotations')]) Args: options (dict): dict of configs to merge from. allow_list_keys (bool): If True, int string keys (e.g. '0', '1') are allowed in ``options`` and will replace the element of the corresponding index in the config if the config is a list. Default: True. """ option_cfg_dict = {} for full_key, v in options.items(): d = option_cfg_dict key_list = full_key.split(".") for subkey in key_list[:-1]: d.setdefault(subkey, _ConfigDict()) d = d[subkey] subkey = key_list[-1] d[subkey] = v cfg_dict = super(Configurator, self).__getattribute__("_cfg_dict") super(Configurator, self).__setattr__( "_cfg_dict", Configurator._merge_a_into_b(option_cfg_dict, cfg_dict, allow_list_keys=allow_list_keys) )
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/registry.py
utils/registry.py
# -*- coding: utf-8 -*- # @Time : 2021/5/22 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import importlib import sys from typing import Any, Dict, Iterable, Iterator, Tuple def formatter_for_dict(info_dict: dict, headers: list, name_length=20, obj_str_length=60): assert len(headers) == 2 table_cfg = dict( name=dict(max_length=name_length, mode="left"), obj=dict(max_length=obj_str_length, mode="left"), ) table_rows = [item2str(headers[0], **table_cfg["name"]) + "|" + item2str(headers[1], **table_cfg["obj"])] for name, obj in info_dict.items(): table_rows.append((item2str(name, **table_cfg["name"]) + "|" + item2str(str(obj), **table_cfg["obj"]))) dividing_line = "\n" + "-" * len(table_rows[0]) + "\n" return dividing_line.join(table_rows) def item2str(string: str, max_length: int, padding_char: str = " ", mode: str = "left"): assert isinstance(max_length, int), f"{max_length} must be `int`" real_length = len(string) if real_length <= max_length: padding_length = max_length - real_length if mode == "left": clipped_string = string + f"{padding_char}" * padding_length elif mode == "center": left_padding_str = f"{padding_char}" * (padding_length // 2) right_padding_str = f"{padding_char}" * (padding_length - padding_length // 2) clipped_string = left_padding_str + string + right_padding_str elif mode == "right": clipped_string = f"{padding_char}" * padding_length + string else: raise NotImplementedError else: clipped_string = string[:max_length] return clipped_string class Registry(Iterable[Tuple[str, Any]]): """ The registry that provides name -> object mapping, to support classes and functions. To create a registry (e.g. a class registry and a function registry): :: DATASETS = Registry(name="dataset") EVALUATE = Registry(name="evaluate") To register an object: :: @DATASETS.register(name='mymodule') class MyModule(*args, **kwargs): ... @EVALUATE.register(name='myfunc') def my_func(*args, **kwargs): ... Or: :: DATASETS.register(name='mymodule', obj=MyModule) EVALUATE.register(name='myfunc', obj=my_func) To construct an object of the class or the function: :: DATASETS = Registry(name="dataset") # The callers of the DATASETS are from the module data, we need to manually import it. DATASETS.import_module_from_module_names(["data"]) EVALUATE = Registry(name="evaluate") # The callers of the EVALUATE are from the module evaluate, we need to manually import it. EVALUATE.import_module_from_module_names(["evaluate"]) """ def __init__(self, name: str) -> None: """ Args: name (str): the name of this registry """ self._name: str = name self._obj_map: Dict[str, Any] = {} def _do_register(self, name: str, obj: Any) -> None: assert ( name not in self._obj_map ), f"An object named '{name}' was already registered in '{self._name}' registry!" self._obj_map[name] = obj def register(self, name: str = None, *, obj: Any = None) -> Any: """ Register the given object under the the name `obj.__name__`. Can be used as either a decorator or not. See docstring of this class and the examples in the folder `examples` for usage. """ if name is not None: assert isinstance(name, str), f"name must be a str obj, but current name is {type(name)}" if obj is None: # used as a decorator def deco(func_or_class: Any) -> Any: key = func_or_class.__name__ if name is None else name self._do_register(key, func_or_class) return func_or_class return deco # used as a function call name = obj.__name__ if name is None else name self._do_register(name, obj) def get(self, name: str) -> Any: ret = self._obj_map.get(name) if ret is None: raise KeyError(f"No object named '{name}' found in '{self._name}' registry!") return ret def __getattr__(self, name: str): return self.get(name=name) def __getitem__(self, name: str): return self.get(name=name) def __contains__(self, name: str) -> bool: return name in self._obj_map def __repr__(self) -> str: table_headers = ["Names", "Objects"] table = formatter_for_dict(self._obj_map, headers=table_headers) return "Registry of {}:\n".format(self._name) + table __str__ = __repr__ def __iter__(self) -> Iterator[Tuple[str, Any]]: return iter(self._obj_map.items()) def keys(self): return self._obj_map.keys() def values(self): return self._obj_map.values() @staticmethod def import_module_from_module_names(module_names, verbose=True): for name in module_names: for _existing_module in sys.modules.keys(): _existing_module_splits = _existing_module.split(".") name_splits = name.split(".") if name_splits == _existing_module_splits[: len(name_splits)]: if verbose: print(f"Module:{name} has been contained in sys.modules ({_existing_module}).") continue module_spec = importlib.util.find_spec(name) if module_spec is None: raise ModuleNotFoundError(f"Module :{name} not found") if verbose: print(f"Module:{name} is being imported!") module = importlib.util.module_from_spec(module_spec) module_spec.loader.exec_module(module) if verbose: print(f"Module:{name} has been imported!")
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/misc.py
utils/misc.py
# -*- coding: utf-8 -*- import copy import importlib import os import random import shutil import sys import warnings from collections import abc, OrderedDict from datetime import datetime from importlib.util import find_spec, module_from_spec import numpy as np import torch from torch import nn from torch.backends import cudnn def customized_worker_init_fn(worker_id, base_seed): set_seed_for_lib(base_seed + worker_id) def set_seed_for_lib(seed): random.seed(seed) np.random.seed(seed) # 为了禁止hash随机化,使得实验可复现。 os.environ["PYTHONHASHSEED"] = str(seed) torch.manual_seed(seed) # 为CPU设置随机种子 torch.cuda.manual_seed(seed) # 为当前GPU设置随机种子 torch.cuda.manual_seed_all(seed) # 为所有GPU设置随机种子 def initialize_seed_cudnn(seed, deterministic): assert isinstance(deterministic, bool) and isinstance(seed, int) if seed >= 0: set_seed_for_lib(seed) if not deterministic: print("We will use `torch.backends.cudnn.benchmark`") else: print("We will not use `torch.backends.cudnn.benchmark`") cudnn.enabled = True cudnn.benchmark = not deterministic cudnn.deterministic = deterministic def construct_path(output_dir: str, exp_name: str) -> dict: pth_log_path = os.path.join(output_dir, exp_name) tb_path = os.path.join(pth_log_path, "tb") save_path = os.path.join(pth_log_path, "pre") pth_path = os.path.join(pth_log_path, "pth") final_full_model_path = os.path.join(pth_path, "checkpoint_final.pth") final_state_path = os.path.join(pth_path, "state_final.pth") tr_log_path = os.path.join(pth_log_path, f"tr_{str(datetime.now())[:10]}.txt") te_log_path = os.path.join(pth_log_path, f"te_{str(datetime.now())[:10]}.txt") trans_log_path = os.path.join(pth_log_path, f"trans_{str(datetime.now())[:10]}.txt") cfg_copy_path = os.path.join(pth_log_path, f"cfg_{str(datetime.now())}.py") trainer_copy_path = os.path.join(pth_log_path, f"trainer_{str(datetime.now())}.txt") excel_path = os.path.join(pth_log_path, f"results.xlsx") path_config = { "output_dir": output_dir, "pth_log": pth_log_path, "tb": tb_path, "save": save_path, "pth": pth_path, "final_full_net": final_full_model_path, "final_state_net": final_state_path, "tr_log": tr_log_path, "te_log": te_log_path, "trans_log": trans_log_path, "cfg_copy": cfg_copy_path, "excel": excel_path, "trainer_copy": trainer_copy_path, } return path_config def construct_exp_name(model_name: str, cfg: dict): # bs_16_lr_0.05_e30_noamp_2gpu_noms_352 focus_item = OrderedDict( { "train/batch_size": "bs", "train/lr": "lr", "train/num_epochs": "e", "train/num_iters": "i", "datasets/train/shape/h": "h", "datasets/train/shape/w": "w", "train/optimizer/mode": "opm", "train/optimizer/group_mode": "opgm", "train/scheduler/mode": "sc", "train/scheduler/warmup/num_iters": "wu", "train/use_amp": "amp", # "train/sam/enable": "sam", "train/ema/enable": "ema", "train/ms/enable": "ms", } ) config = copy.deepcopy(cfg) def _format_item(_i): if isinstance(_i, bool): _i = "" if _i else "false" elif isinstance(_i, (int, float)): if _i == 0: _i = "false" elif isinstance(_i, (list, tuple)): _i = "" if _i else "false" # 只是判断是否非空 elif isinstance(_i, str): if "_" in _i: _i = _i.replace("_", "").lower() elif _i is None: _i = "none" # else: other types and values will be returned directly return _i if (epoch_based := config.train.get("epoch_based", None)) is not None and (not epoch_based): focus_item.pop("train/num_epochs") else: # 默认基于epoch focus_item.pop("train/num_iters") exp_names = [model_name] for key, alias in focus_item.items(): item = get_value_recurse(keys=key.split("/"), info=config) formatted_item = _format_item(item) if formatted_item == 'false': continue exp_names.append(f"{alias.upper()}{formatted_item}") experiment_tag = config.get("experiment_tag", None) if experiment_tag: exp_names.append(f"INFO{experiment_tag.lower()}") return "_".join(exp_names) def to_device(data, device): """ :param data: :param device: :return: """ if isinstance(data, (tuple, list)): ctor = tuple if isinstance(data, tuple) else list return ctor(to_device(d, device) for d in data) elif isinstance(data, dict): return {name: to_device(item, device) for name, item in data.items()} elif isinstance(data, torch.Tensor): return data.to(device=device, non_blocking=True) else: raise TypeError(f"Unsupported type {type(data)}. Only support Tensor or tuple/list/dict containing Tensors.") def is_on_gpu(x): """ 判定x是否是gpu上的实例,可以检测tensor和module :param x: (torch.Tensor, nn.Module)目标对象 :return: 是否在gpu上 """ # https://blog.csdn.net/WYXHAHAHA123/article/details/86596981 if isinstance(x, torch.Tensor): return "cuda" in x.device elif isinstance(x, nn.Module): return next(x.parameters()).is_cuda else: raise NotImplementedError def is_parallel(model): # Returns True if model is of type DP or DDP return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel) def get_device(x): """ 返回x的设备信息,可以处理tensor和module :param x: (torch.Tensor, nn.Module) 目标对象 :return: 所在设备 """ # https://blog.csdn.net/WYXHAHAHA123/article/details/86596981 if isinstance(x, torch.Tensor): return x.device elif isinstance(x, nn.Module): return next(x.parameters()).device else: raise NotImplementedError def pre_mkdir(path_config): # 提前创建好记录文件,避免自动创建的时候触发文件创建事件 check_mkdir(path_config["pth_log"]) make_log(path_config["te_log"], f"=== te_log {datetime.now()} ===") make_log(path_config["tr_log"], f"=== tr_log {datetime.now()} ===") # 提前创建好存储预测结果和存放模型的文件夹 check_mkdir(path_config["save"]) check_mkdir(path_config["pth"]) def check_mkdir(dir_name, delete_if_exists=False): if not os.path.exists(dir_name): os.makedirs(dir_name) else: if delete_if_exists: print(f"{dir_name} will be re-created!!!") shutil.rmtree(dir_name) os.makedirs(dir_name) def check_file_exist(filename, msg_tmpl='file "{}" does not exist'): if not os.path.isfile(filename): raise FileNotFoundError(msg_tmpl.format(filename)) def make_log(path, context): with open(path, "a") as log: log.write(f"{context}\n") def are_the_same(file_path_1, file_path_2, buffer_size=8 * 1024): """ 通过逐块比较两个文件的二进制数据是否一致来确定两个文件是否是相同内容 REF: https://zhuanlan.zhihu.com/p/142453128 Args: file_path_1: 文件路径 file_path_2: 文件路径 buffer_size: 读取的数据片段大小,默认值8*1024 Returns: dict(state=True/False, msg=message) """ st1 = os.stat(file_path_1) st2 = os.stat(file_path_2) # 比较文件大小 if st1.st_size != st2.st_size: return dict(state=False, msg="文件大小不一致") with open(file_path_1, mode="rb") as f1, open(file_path_2, mode="rb") as f2: while True: b1 = f1.read(buffer_size) # 读取指定大小的数据进行比较 b2 = f2.read(buffer_size) if b1 != b2: msg = ( f"存在差异:" f"\n{file_path_1}\n==>\n{b1.decode('utf-8')}\n<==" f"\n{file_path_2}\n==>\n{b2.decode('utf-8')}\n<==" ) return dict(state=False, msg=msg) # b1 == b2 if not b1: # b1 == b2 == False (b'') return dict(state=True, msg="完全一样") def all_items_in_string(items, target_str): """判断items中是否全部都是属于target_str一部分的项""" for i in items: if i not in target_str: return False return True def any_item_in_string(items, target_str): """判断items中是否存在属于target_str一部分的项""" for i in items: if i in target_str: return True return False def slide_win_select(items, win_size=1, win_stride=1, drop_last=False): num_items = len(items) i = 0 while i + win_size <= num_items: yield items[i: i + win_size] i += win_stride if not drop_last: # 对于最后不满一个win_size的切片,保留 yield items[i: i + win_size] def iterate_nested_sequence(nested_sequence): """ 当前支持list/tuple/int/float/range()的多层嵌套,注意不要嵌套的太深,小心超出python默认的最大递归深度 例子 :: for x in iterate_nested_sequence([[1, (2, 3)], range(3, 10), 0]): print(x) 1 2 3 3 4 5 6 7 8 9 0 :param nested_sequence: 多层嵌套的序列 :return: generator """ for item in nested_sequence: if isinstance(item, (int, float)): yield item elif isinstance(item, (list, tuple, range)): yield from iterate_nested_sequence(item) else: raise NotImplementedError def get_value_recurse(keys: list, info: dict): curr_key, sub_keys = keys[0], keys[1:] if (sub_info := info.get(curr_key, "NoKey")) == "NoKey": raise KeyError(f"{curr_key} must be contained in {info}") if sub_keys: return get_value_recurse(keys=sub_keys, info=sub_info) else: return sub_info def import_module_from_module_names(module_names): for name in module_names: if any([_existing_module.startswith(name) for _existing_module in sys.modules.keys()]): print(f"Module:{name} has been contained in sys.modules.") continue module_spec = find_spec(name) if module_spec is None: raise ModuleNotFoundError(f"Module :{name} not found") print(f"Module:{name} is being imported!") module = module_from_spec(module_spec) module_spec.loader.exec_module(module) print(f"Module:{name} has been imported!") def import_modules_from_strings(imports, allow_failed_imports=False): """Import modules from the given list of strings. Args: imports (list | str | None): The given module names to be imported. allow_failed_imports (bool): If True, the failed imports will return None. Otherwise, an ImportError is raise. Default: False. Returns: list[module] | module | None: The imported modules. Examples: >>> osp, sys = import_modules_from_strings( ... ['os.path', 'sys']) >>> import os.path as osp_ >>> import sys as sys_ >>> assert osp == osp_ >>> assert sys == sys_ """ if not imports: return single_import = False if isinstance(imports, str): single_import = True imports = [imports] if not isinstance(imports, list): raise TypeError(f"custom_imports must be a list but got type {type(imports)}") imported = [] for imp in imports: if not isinstance(imp, str): raise TypeError(f"{imp} is of type {type(imp)} and cannot be imported.") try: imported_tmp = importlib.import_module(imp) except ImportError: if allow_failed_imports: warnings.warn(f"{imp} failed to import and is ignored.", UserWarning) imported_tmp = None else: raise ImportError imported.append(imported_tmp) if single_import: imported = imported[0] return imported def mapping_to_str(mapping: abc.Mapping, *, prefix: str = " ", lvl: int = 0, max_lvl: int = 1) -> str: """ Print the structural information of the dict. """ sub_lvl = lvl + 1 cur_prefix = prefix * lvl sub_prefix = prefix * sub_lvl if lvl == max_lvl: sub_items = str(mapping) else: sub_items = ["{"] for k, v in mapping.items(): sub_item = sub_prefix + k + ": " if isinstance(v, abc.Mapping): sub_item += mapping_to_str(v, prefix=prefix, lvl=sub_lvl, max_lvl=max_lvl) else: sub_item += str(v) sub_items.append(sub_item) sub_items.append(cur_prefix + "}") sub_items = "\n".join(sub_items) return sub_items if __name__ == "__main__": a = dict(a0=1, b0=2, c0=3, d0=dict(a1=[1, 2, 3], b1=dict(a2=dict(a3=10, b3=[1, 2, 3])), c1=dict(a2=1))) print("max_lvl=0 -->\n", mapping_to_str(a, max_lvl=0)) print("max_lvl=1 -->\n", mapping_to_str(a, max_lvl=1)) print("max_lvl=2 -->\n", mapping_to_str(a, max_lvl=2)) print("max_lvl=3 -->\n", mapping_to_str(a, max_lvl=3)) print("max_lvl=4 -->\n", mapping_to_str(a, max_lvl=4)) print("max_lvl=5 -->\n", mapping_to_str(a, max_lvl=5))
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/__init__.py
utils/__init__.py
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/builder.py
utils/builder.py
# -*- coding: utf-8 -*- # @Time : 2021/5/22 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import inspect from utils.registry import Registry DATASETS = Registry(name="dataset") DATASETS.import_module_from_module_names(["dataset"], verbose=False) MODELS = Registry(name="model") MODELS.import_module_from_module_names(["methods"], verbose=False) _ALL_REGISTRY = dict( DATASETS=DATASETS, MODELS=MODELS, ) def build_obj_from_registry(obj_name, registry_name, obj_cfg=None, return_code=False): """ :param obj_name: :param registry_name: BACKBONES,DATASETS,MODELS,EVALUATE :param obj_cfg: For the function obj, if obj_cfg is None, return the function obj, otherwise the outputs of the fucntion with the obj_cfg. For the class obj, always return the instance. If obj_cfg is None, it will be initialized by an empty, otherwise by the obj_cfg. :param return_code: If True, will return the source code of the function or class obj. :return: output [, source_code if return_code is True] """ assert ( registry_name in _ALL_REGISTRY ), f"registry_name: {registry_name} must be contained in {_ALL_REGISTRY.keys()}" _registry = _ALL_REGISTRY[registry_name] assert obj_name in _registry, f"obj_name: {obj_name} must be contained in the registry:\n{_registry}" obj = _registry[obj_name] if inspect.isclass(obj): if obj_cfg is None: obj_cfg = {} output = obj(**obj_cfg) elif inspect.isfunction(obj): if obj_cfg is None: output = obj else: output = obj(**obj_cfg) else: raise NotImplementedError if return_code: source_code = inspect.getsource(obj) return output, source_code else: return output
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/recorder/excel_recorder.py
utils/recorder/excel_recorder.py
# -*- coding: utf-8 -*- # @Time : 2021/1/3 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import contextlib import os import re from openpyxl import load_workbook, Workbook from openpyxl.utils import get_column_letter from openpyxl.worksheet.worksheet import Worksheet # Thanks: # - Python_Openpyxl: https://www.cnblogs.com/programmer-tlh/p/10461353.html # - Python之re模块: https://www.cnblogs.com/shenjianping/p/11647473.html def create_xlsx(xlsx_path: str): if not os.path.exists(xlsx_path): print("We have created a new excel file!!!") Workbook().save(xlsx_path) else: print("Excel file has existed!") @contextlib.contextmanager def open_excel(xlsx_path: str, sheet_name: str): wb = load_workbook(xlsx_path) if sheet_name not in wb.sheetnames: wb.create_sheet(title=sheet_name, index=0) sheet = wb[sheet_name] yield sheet wb.save(xlsx_path) def append_row(sheet: Worksheet, row_data): assert isinstance(row_data, (tuple, list)) sheet.append(row_data) def insert_row(sheet: Worksheet, row_data, row_id, min_col=1, interval=0): """ 将数据插入工作表中的一行 Args: sheet: 工作表对象 row_data: 要插入的数据,tuple或者list row_id: 要插入区域的行的序号(从1开始) min_col: 要插入区域的起始列的序号(从1开始) interval: row_data中各个数据之间要间隔多少个空的cell """ assert isinstance(row_id, int) and isinstance(min_col, int) and row_id > 0 and min_col > 0 assert isinstance(row_data, (tuple, list)), row_data num_elements = len(row_data) row_data = iter(row_data) for row in sheet.iter_rows( min_row=row_id, max_row=row_id, min_col=min_col, max_col=min_col + (interval + 1) * (num_elements - 1) ): for i, cell in enumerate(row): if i % (interval + 1) == 0: sheet.cell(row=row_id, column=cell.column, value=next(row_data)) def insert_cell(sheet: Worksheet, row_id, col_id, value): assert isinstance(row_id, int) and isinstance(col_id, int) and row_id > 0 and col_id > 0 sheet.cell(row=row_id, column=col_id, value=value) def merge_region(sheet: Worksheet, min_row, max_row, min_col, max_col): assert max_row >= min_row > 0 and max_col >= min_col > 0 merged_region = f"{get_column_letter(min_col)}{min_row}:{get_column_letter(max_col)}{max_row}" sheet.merge_cells(merged_region) def get_col_id_with_row_id(sheet: Worksheet, col_name: str, row_id): """ 从指定行中寻找特定的列名,并返回对应的列序号 """ assert isinstance(row_id, int) and row_id > 0 for cell in sheet[row_id]: if cell.value == col_name: return cell.column raise ValueError(f"In row {row_id}, there is not the column {col_name}!") def get_row_id_with_col_name(sheet: Worksheet, row_name: str, col_name: str): """ 从指定列名字的一列中寻找指定行,返回对应的row_id, col_id, is_new_row """ is_new_row = True col_id = get_col_id_with_row_id(sheet=sheet, col_name=col_name, row_id=1) row_id = 0 for cell in sheet[get_column_letter(col_id)]: row_id = cell.row if cell.value == row_name: return (row_id, col_id), not is_new_row return (row_id + 1, col_id), is_new_row def get_row_id_with_col_id(sheet: Worksheet, row_name: str, col_id: int): """ 从指定序号的一列中寻找指定行 """ assert isinstance(col_id, int) and col_id > 0 is_new_row = True row_id = 0 for cell in sheet[get_column_letter(col_id)]: row_id = cell.row if cell.value == row_name: return row_id, not is_new_row return row_id + 1, is_new_row def format_string_with_config(string: str, repalce_config: dict = None): assert repalce_config is not None if repalce_config.get("lower"): string = string.lower() elif repalce_config.get("upper"): string = string.upper() elif repalce_config.get("title"): string = string.title() if sub_rule := repalce_config.get("replace"): string = re.sub(pattern=sub_rule[0], repl=sub_rule[1], string=string) return string class MetricExcelRecorder(object): def __init__( self, xlsx_path: str, sheet_name="results", row_header="methods", repalce_config=None, dataset_names=None, metric_names=None, ): """ Args: xlsx_path: 保存工作表的xlsx文件地址 sheet_name: 存放数据的工作表名字 row_header: 最左上角的数据,在这个类中,指代存放于合并后的A1:A2区域的文本 repalce_config: 用来格式化数据集名字和指标名字的设定,这里借助re.sub函数进行处理, 默认设置:`dict(lower=True, replace=(r"[_-]", ""))` dataset_names: 数据集合名字列表 metric_names: 指标名字列表 """ create_xlsx(xlsx_path=xlsx_path) if repalce_config is None: repalce_config = dict(lower=True, replace=(r"[_-]", "")) if dataset_names is None: dataset_names = ["pascals", "ecssd", "hkuis", "dutste", "dutomron"] if metric_names is None: metric_names = ["smeasure", "wfmeasure", "mae", "adpfm", "meanfm", "maxfm", "adpem", "meanem", "maxem"] self.xlsx_path = xlsx_path self.sheet_name = sheet_name self.repalce_config = repalce_config self.row_header = format_string_with_config(row_header, self.repalce_config) self.dataset_names = [format_string_with_config(s, self.repalce_config) for s in dataset_names] self.metric_names = [format_string_with_config(s, self.repalce_config) for s in metric_names] self.num_datasets = len(self.dataset_names) self.num_metrics = len(self.metric_names) self._initial_table() def _initial_table(self): """ |-------|-------------|---------------|-----------------|---------------|-----------------|-------------------| |methods|dataset_name1|dataset_length1|...|dataset_name1|dataset_length1|...|dataset_name1|dataset_length1... | | |metric1 |metric2 |...|metric1 |metric2 |...|metric1 |metric2... | |-------|-------------|---------------|-----------------|---------------|-----------------|-------------------| |... """ with open_excel(xlsx_path=self.xlsx_path, sheet_name=self.sheet_name) as sheet: # 插入row_header insert_cell(sheet=sheet, row_id=1, col_id=1, value=self.row_header) # 合并row_header的单元格 merge_region(sheet=sheet, min_row=1, max_row=2, min_col=1, max_col=1) # 插入数据集信息 insert_row(sheet=sheet, row_data=self.dataset_names, row_id=1, min_col=2, interval=self.num_metrics - 1) # 插入指标信息 for i in range(self.num_datasets): insert_row(sheet=sheet, row_data=self.metric_names, row_id=2, min_col=2 + i * self.num_metrics) def _format_row_data(self, row_data: dict) -> list: row_data = {format_string_with_config(k, self.repalce_config): v for k, v in row_data.items()} return [row_data[n] for n in self.metric_names] def __call__(self, row_data: dict, dataset_name: str, method_name: str): dataset_name = format_string_with_config(dataset_name, self.repalce_config) assert dataset_name in self.dataset_names, f"{dataset_name} is not contained in {self.dataset_names}" # 1 载入数据表更新后写入新表 with open_excel(xlsx_path=self.xlsx_path, sheet_name=self.sheet_name) as sheet: # 2 搜索method_name是否存在,如果存在则直接寻找对应的行列坐标,如果不存在则直接使用新行 dataset_col_start_id = get_col_id_with_row_id(sheet=sheet, col_name=dataset_name, row_id=1) (method_row_id, method_col_id), is_new_row = get_row_id_with_col_name( sheet=sheet, row_name=method_name, col_name="methods" ) # 3 插入方法名字到对应的位置 if is_new_row: sheet.cell(row=method_row_id, column=method_col_id, value=method_name) # 4 格式化指标数据部分为合理的格式,并插入表中 row_data = self._format_row_data(row_data=row_data) insert_row(sheet=sheet, row_data=row_data, row_id=method_row_id, min_col=dataset_col_start_id) class NewMetricExcelRecorder(object): def __init__( self, xlsx_path: str, repalce_config: dict = None, sheet_name: str = "results", row_header: str = "methods", dataset_names: tuple = ("pascals", "ecssd", "hkuis", "dutste", "dutomron"), metric_names: tuple = ( "smeasure", "wfmeasure", "mae", "adpfm", "meanfm", "maxfm", "adpem", "meanem", "maxem"), dataset_lengths: tuple = (850, 1000, 4447, 5017, 5168), record_average: bool = True, ): assert all([isinstance(x, int) for x in dataset_lengths]) assert len(dataset_names) == len(dataset_lengths) create_xlsx(xlsx_path=xlsx_path) self.xlsx_path = xlsx_path if repalce_config is None: self.repalce_config = dict(lower=True, replace=(r"[_-]", "")) else: self.repalce_config = repalce_config self.row_header = format_string_with_config(row_header, self.repalce_config) self.dataset_names = [format_string_with_config(s, self.repalce_config) for s in dataset_names] self.metric_names = [format_string_with_config(s, self.repalce_config) for s in metric_names] self.dataset_lengths = [float(s) for s in self.dataset_lengths] self.record_average = record_average self.num_datasets = len(self.dataset_names) self.num_metrics = len(self.metric_names) self.sheet_name = sheet_name self._initial_table() def _initial_table(self): """ |-------|-------------|---------------|-----------------|---------------|-----------------|-------------------| |methods|dataset_name1|dataset_length1|...|dataset_name1|dataset_length1|...|dataset_name1|dataset_length1... | | |metric1 |metric2 |...|metric1 |metric2 |...|metric1 |metric2... | |-------|-------------|---------------|-----------------|---------------|-----------------|-------------------| |... """ with open_excel(xlsx_path=self.xlsx_path, sheet_name=self.sheet_name) as sheet: # 插入row_headers insert_cell(sheet=sheet, row_id=1, col_id=1, value=self.row_header) # 合并row_header的单元格 merge_region(sheet=sheet, min_row=1, max_row=3, min_col=1, max_col=1) if self.record_average: # 根据需要插入平均指标区域 self.dataset_names.append("average") self.dataset_lengths.append(sum(self.dataset_lengths)) self.num_datasets += 1 # 在第一行插入数据集名字和数据量 insert_row(sheet=sheet, row_data=self.dataset_names, row_id=1, min_col=2, interval=self.num_metrics - 1) insert_row(sheet=sheet, row_data=self.dataset_lengths, row_id=1, min_col=3, interval=self.num_metrics - 1) # 在第二行插入指标信息 for i in range(len(self.dataset_names)): insert_row(sheet=sheet, row_data=self.metric_names, row_id=2, min_col=2 + i * self.num_metrics) def _format_row_data(self, row_data: dict) -> list: row_data = {format_string_with_config(k, self.repalce_config): v for k, v in row_data.items()} return [row_data[n] for n in self.metric_names] def __call__(self, row_data: dict, dataset_name: str, method_name: str): assert dataset_name in self.dataset_names, f"{dataset_name} is not contained in {self.dataset_names}" dataset_name = format_string_with_config(dataset_name, self.repalce_config) # 1 载入数据表,改写后存入新表 with open_excel(xlsx_path=self.xlsx_path, sheet_name=self.sheet_name) as sheet: # 2 搜索method_name是否存在,如果存在则直接寻找对应的行列坐标,如果不存在则直接使用新行 dataset_col_start_id = get_col_id_with_row_id(sheet=sheet, col_name=dataset_name, row_id=1) (method_row_id, method_col_id), is_new_row = get_row_id_with_col_name( sheet=sheet, row_name=method_name, col_name=self.row_header ) # 3 插入方法名字到对应的位置 if is_new_row: insert_cell(sheet=sheet, row_id=method_row_id, col_id=method_col_id, value=method_name) # 4 格式化指标数据部分为合理的格式,并插入表中 row_data = self._format_row_data(row_data=row_data) insert_row(sheet=sheet, row_data=row_data, row_id=method_row_id, min_col=dataset_col_start_id)
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/recorder/meter_recorder.py
utils/recorder/meter_recorder.py
# -*- coding: utf-8 -*- # @Time : 2020/7/4 # @Author : Lart Pang # @GitHub : https://github.com/lartpang class AvgMeter(object): __slots__ = ["value", "avg", "sum", "count"] def __init__(self): self.value = 0 self.avg = 0 self.sum = 0 self.count = 0 def reset(self): self.value = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, value, num=1): self.value = value self.sum += value * num self.count += num self.avg = self.sum / self.count
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/recorder/timer.py
utils/recorder/timer.py
# -*- coding: utf-8 -*- # @Time : 2020/12/19 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import functools from datetime import datetime class TimeRecoder: __slots__ = ["_start_time", "_has_start"] def __init__(self): self._start_time = datetime.now() self._has_start = False def start(self, msg=""): self._start_time = datetime.now() self._has_start = True if msg: print(f"Start: {msg}") def now_and_reset(self, pre_msg=""): if not self._has_start: raise AttributeError("You must call the `.start` method before the `.now_and_reset`!") self._has_start = False end_time = datetime.now() print(f"End: {pre_msg} {end_time - self._start_time}") self.start() def now(self, pre_msg=""): if not self._has_start: raise AttributeError("You must call the `.start` method before the `.now`!") self._has_start = False end_time = datetime.now() print(f"[{end_time}] {pre_msg} {end_time - self._start_time}") @staticmethod def decorator(start_msg="", end_pre_msg=""): """as a decorator""" _temp_obj = TimeRecoder() def _timer(func): @functools.wraps(func) def wrapper(*args, **kwargs): _temp_obj.start(start_msg) results = func(*args, **kwargs) _temp_obj.now(end_pre_msg) return results return wrapper return _timer
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/recorder/tensorboard.py
utils/recorder/tensorboard.py
# -*- coding: utf-8 -*- # @Time : 2020/12/19 # @Author : Lart Pang # @GitHub : https://github.com/lartpang from torch.utils.tensorboard import SummaryWriter from torchvision.utils import make_grid from utils.misc import check_mkdir class TBRecorder(object): __slots__ = ["tb"] def __init__(self, tb_path): check_mkdir(tb_path, delete_if_exists=True) self.tb = SummaryWriter(tb_path) def record_curve(self, name, data, curr_iter): if not isinstance(data, (tuple, list)): self.tb.add_scalar(f"data/{name}", data, curr_iter) else: for idx, data_item in enumerate(data): self.tb.add_scalar(f"data/{name}_{idx}", data_item, curr_iter) def record_image(self, name, data, curr_iter): data_grid = make_grid(data, nrow=data.size(0), padding=5) self.tb.add_image(name, data_grid, curr_iter) def record_images(self, data_container: dict, curr_iter): for name, data in data_container.items(): data_grid = make_grid(data, nrow=data.size(0), padding=5) self.tb.add_image(name, data_grid, curr_iter) def record_histogram(self, name, data, curr_iter): self.tb.add_histogram(name, data, curr_iter) def close_tb(self): self.tb.close()
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/recorder/__init__.py
utils/recorder/__init__.py
# -*- coding: utf-8 -*- # @Time : 2020/12/19 # @Author : Lart Pang # @GitHub : https://github.com/lartpang from .excel_recorder import MetricExcelRecorder from .meter_recorder import AvgMeter from .metric_caller import CalTotalMetric from .msg_logger import TxtLogger from .tensorboard import TBRecorder from .timer import TimeRecoder from .visualize_results import plot_results
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/recorder/msg_logger.py
utils/recorder/msg_logger.py
# -*- coding: utf-8 -*- # @Time : 2020/12/19 # @Author : Lart Pang # @GitHub : https://github.com/lartpang class TxtLogger(object): __slots__ = ["_path"] def __init__(self, path): self._path = path def record(self, msg, show=True): with open(self._path, "a") as f: f.write(str(msg) + "\n") if show: print(msg)
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/recorder/visualize_results.py
utils/recorder/visualize_results.py
import matplotlib import matplotlib.pyplot as plt import numpy as np import torch import torchvision.transforms.functional as tv_tf from torchvision.utils import make_grid matplotlib.use("agg") @torch.no_grad() def plot_results(data_container, save_path=None): """Plot the results conresponding to the batched images based on the `make_grid` method from `torchvision`. Args: data_container (dict): Dict containing data you want to plot. save_path (str): Path of the exported image. """ axes = plt.subplots(nrows=len(data_container), ncols=1)[1].ravel() plt.subplots_adjust(hspace=0.03, left=0.05, bottom=0.01, right=0.99, top=0.99) for subplot_id, (name, data) in enumerate(data_container.items()): grid = make_grid(data, nrow=data.shape[0], padding=2, normalize=False) grid_image = np.asarray(tv_tf.to_pil_image(grid)) axes[subplot_id].imshow(grid_image) axes[subplot_id].set_ylabel(name) axes[subplot_id].set(xticklabels=[], yticklabels=[], xticks=[], yticks=[]) if save_path is not None: plt.savefig(save_path) else: plt.show() if __name__ == "__main__": matplotlib.use("tkagg") data_container = dict( image=torch.randn(4, 1, 320, 320), mask=torch.randn(4, 1, 320, 320), prediction=torch.rand(4, 1, 320, 320), ) plot_results(data_container=data_container, save_path=None)
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/recorder/metric_caller.py
utils/recorder/metric_caller.py
# -*- coding: utf-8 -*- # @Time : 2020/12/19 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import numpy as np from py_sod_metrics.sod_metrics import Emeasure, Fmeasure, MAE, Smeasure, WeightedFmeasure class CalTotalMetric(object): __slots__ = ["cal_mae", "cal_fm", "cal_sm", "cal_em", "cal_wfm"] def __init__(self): self.cal_mae = MAE() self.cal_fm = Fmeasure() self.cal_sm = Smeasure() self.cal_em = Emeasure() self.cal_wfm = WeightedFmeasure() def step(self, pred: np.ndarray, gt: np.ndarray, gt_path: str): assert pred.ndim == gt.ndim and pred.shape == gt.shape, (pred.shape, gt.shape, gt_path) assert pred.dtype == np.uint8, pred.dtype assert gt.dtype == np.uint8, gt.dtype self.cal_mae.step(pred, gt) self.cal_fm.step(pred, gt) self.cal_sm.step(pred, gt) self.cal_em.step(pred, gt) self.cal_wfm.step(pred, gt) def get_results(self, bit_width: int = 3) -> dict: fm = self.cal_fm.get_results()["fm"] wfm = self.cal_wfm.get_results()["wfm"] sm = self.cal_sm.get_results()["sm"] em = self.cal_em.get_results()["em"] mae = self.cal_mae.get_results()["mae"] results = { "Smeasure": sm, "wFmeasure": wfm, "MAE": mae, "adpEm": em["adp"], "meanEm": em["curve"].mean(), "maxEm": em["curve"].max(), "adpFm": fm["adp"], "meanFm": fm["curve"].mean(), "maxFm": fm["curve"].max(), } def _round_w_zero_padding(_x): _x = str(_x.round(bit_width)) _x += "0" * (bit_width - len(_x.split(".")[-1])) return _x results = {name: _round_w_zero_padding(metric) for name, metric in results.items()} return results
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/io/params.py
utils/io/params.py
# -*- coding: utf-8 -*- # @Time : 2020/12/19 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import os import torch from torch import nn def save_params( model, state_net_path, model_ema=None, full_net_path=None, exp_name=None, next_epoch=-1, optimizer=None, scheduler=None, total_epoch=-1, save_num_models=1, scaler=None, ): """ :: if isinstance(model, dict): model_state = model else: model_state = model.module.state_dict() if hasattr(model, "module") else model.state_dict() opti_state = (optimizer if isinstance(optimizer, dict) else optimizer.state_dict()) if optimizer else None sche_state = (scheduler if isinstance(scheduler, dict) else scheduler.state_dict()) if scheduler else None scaler_state = (scaler if isinstance(scaler, dict) else scaler.state_dict()) if scaler else None """ if isinstance(model, dict): model_state = model else: model_state = model.module.state_dict() if hasattr(model, "module") else model.state_dict() if full_net_path: if next_epoch > 0 and exp_name: opti_state = (optimizer if isinstance(optimizer, dict) else optimizer.state_dict()) if optimizer else None sche_state = (scheduler if isinstance(scheduler, dict) else scheduler.state_dict()) if scheduler else None scaler_state = (scaler if isinstance(scaler, dict) else scaler.state_dict()) if scaler else None ema_model_state = ( (model_ema if isinstance(model_ema, dict) else model_ema.module.state_dict()) if model_ema else None ) torch.save( dict( arch=exp_name, epoch=next_epoch, net_state=model_state, ema_net_state=ema_model_state, opti_state=opti_state, sche_state=sche_state, scaler=scaler_state, ), full_net_path, ) else: raise ValueError("!!!NEED: (next_epoch > 0 and exp_name) is True") if total_epoch > 0 and save_num_models > 1 and next_epoch >= total_epoch - save_num_models + 1: print(f"Saving params of the epoch: {next_epoch - 1}") epoch_state_net_path = state_net_path[:-4] + f"_{next_epoch}.pth" torch.save(model_state, epoch_state_net_path) torch.save(model_state, state_net_path) def save_weight(save_path, model): print(f"Saving weight '{save_path}'") if isinstance(model, dict): model_state = model else: model_state = model.module.state_dict() if hasattr(model, "module") else model.state_dict() torch.save(model_state, save_path) print(f"Saved weight '{save_path}' " f"(only contain the net's weight)") def load_specific_params(load_path, names): """ 从保存节点恢复参数 Args: load_path (str): 模型存放路径 names (list): 需要载入的参数名字 [model, optimizer, scheduler, scaler, start_epoch] """ _name_mapping = dict( model="net_state", optimizer="opti_state", scheduler="sche_state", scaler="scaler", start_epoch="epoch", model_ema="ema_net_state", ) assert os.path.exists(load_path) and os.path.isfile(load_path), load_path assert all([n in _name_mapping for n in names]) print(f"Loading parameters from '{load_path}' for {names}") checkpoint = torch.load(load_path, map_location=torch.device("cpu")) parmas_dict = {} for n in names: mapped_name = _name_mapping[n] if checkpoint.get(mapped_name, None) is not None: parmas_dict[n] = checkpoint[mapped_name] else: raise KeyError(f"There is not '{mapped_name}' in {load_path}: {list(checkpoint.keys())}") return parmas_dict def load_weight(load_path, model: nn.Module): """ 从保存节点恢复模型 Args: load_path (str): 模型存放路径 model: your model """ assert os.path.exists(load_path), load_path print(f"Loading weight '{load_path}'") ckpt_dict = torch.load(load_path, map_location="cpu") state_dict = model.state_dict() ckpt_keys = ckpt_dict.keys() state_keys = state_dict.keys() print(f"Unique Keys in model: {sorted(set(state_keys).difference(ckpt_keys))}") print(f"Unique Keys in ckpt: {sorted(set(ckpt_keys).difference(state_keys))}") model.load_state_dict(ckpt_dict, strict=False) print(f"Loaded weight '{load_path}' " f"(only contains the net's weight)")
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/io/image.py
utils/io/image.py
# -*- coding: utf-8 -*- # @Time : 2020/8/19 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import cv2 import numpy as np from utils.ops import minmax def read_gray_array(path, div_255=False, to_normalize=False, thr=-1, dtype=np.float32) -> np.ndarray: """ 1. read the binary image with the suffix `.jpg` or `.png` into a grayscale ndarray 2. (to_normalize=True) rescale the ndarray to [0, 1] 3. (thr >= 0) binarize the ndarray with `thr` 4. return a gray ndarray (np.float32) """ assert path.endswith(".jpg") or path.endswith(".png") assert not div_255 or not to_normalize gray_array = cv2.imread(path, cv2.IMREAD_GRAYSCALE) assert gray_array is not None, f"Image Not Found: {path}" if div_255: gray_array = gray_array / 255 if to_normalize: gray_array = minmax(gray_array, up_bound=255) if thr >= 0: gray_array = gray_array > thr return gray_array.astype(dtype) def read_color_array(path: str): assert path.endswith(".jpg") or path.endswith(".png") bgr_array = cv2.imread(path, cv2.IMREAD_COLOR) assert bgr_array is not None, f"Image Not Found: {path}" rgb_array = cv2.cvtColor(bgr_array, cv2.COLOR_BGR2RGB) return rgb_array
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/io/genaral.py
utils/io/genaral.py
# -*- coding: utf-8 -*- # @Time : 2021/5/17 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import contextlib import json import os from collections import defaultdict def read_data_from_json(json_path: str) -> dict: with open(json_path, mode="r", encoding="utf-8") as f: data = json.load(f) return data def get_data_from_txt(path: str) -> list: """ 读取文件中各行数据,存放到列表中 """ lines = [] with open(path, encoding="utf-8", mode="r") as f: line = f.readline().strip() while line: lines.append(line) line = f.readline().strip() return lines def get_name_list_from_dir(path: str) -> list: """直接从文件夹中读取所有文件不包含扩展名的名字""" return [os.path.splitext(x)[0] for x in os.listdir(path)] def get_datasets_info_with_keys(dataset_infos: list, extra_keys: list) -> dict: """ 从给定的包含数据信息字典的列表中,依据给定的extra_kers和固定获取的key='image'来获取相应的路径 Args: dataset_infos: 数据集字典 extra_keys: 除了'image'之外的需要获取的信息名字 Returns: 包含指定信息的绝对路径列表 """ # total_keys = tuple(set(extra_keys + ["image"])) # e.g. ('image', 'mask') def _get_intersection(list_a: list, list_b: list, to_sort: bool = True): """返回两个列表的交集,并可以随之排序""" intersection_list = list(set(list_a).intersection(set(list_b))) if to_sort: return sorted(intersection_list) return intersection_list def _get_info(dataset_info: dict, extra_keys: list, path_collection: defaultdict): """ 配合get_datasets_info_with_keys使用,针对特定的数据集的信息进行路径获取 Args: dataset_info: 数据集信息字典 extra_keys: 除了'image'之外的需要获取的信息名字 path_collection: 存放收集到的路径信息 """ total_keys = tuple(set(extra_keys + ["image"])) # e.g. ('image', 'mask') dataset_root = dataset_info.get("root", ".") infos = {} for k in total_keys: assert k in dataset_info, f"{k} is not in {dataset_info}" infos[k] = dict(dir=os.path.join(dataset_root, dataset_info[k]["path"]), ext=dataset_info[k]["suffix"]) if (index_file_path := dataset_info.get("index_file", None)) is not None: image_names = get_data_from_txt(index_file_path) else: image_names = get_name_list_from_dir(infos["image"]["dir"]) if "mask" in total_keys: mask_names = get_name_list_from_dir(infos["mask"]["dir"]) image_names = _get_intersection(image_names, mask_names) for i, name in enumerate(image_names): for k in total_keys: path_collection[k].append(os.path.join(infos[k]["dir"], name + infos[k]["ext"])) path_collection = defaultdict(list) for dataset_name, dataset_info in dataset_infos: prev_num = len(path_collection["image"]) _get_info(dataset_info=dataset_info, extra_keys=extra_keys, path_collection=path_collection) curr_num = len(path_collection["image"]) print(f"Loading data from {dataset_name}: {dataset_info['root']} ({curr_num - prev_num})") return path_collection @contextlib.contextmanager def open_w_msg(file_path, mode, encoding=None): """ 提供了打开关闭的显式提示 """ print(f"打开文件{file_path}") f = open(file_path, encoding=encoding, mode=mode) yield f print(f"关闭文件{file_path}") f.close()
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/io/__init__.py
utils/io/__init__.py
# -*- coding: utf-8 -*- # @Time : 2021/5/17 # @Author : Lart Pang # @GitHub : https://github.com/lartpang from .image import read_color_array, read_gray_array from .params import load_specific_params, load_weight, save_params, save_weight
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/ops/tensor_ops.py
utils/ops/tensor_ops.py
# -*- coding: utf-8 -*- # @Time : 2020 # @Author : Lart Pang # @GitHub : https://github.com/lartpang from numbers import Number import torch import torch.nn.functional as F def cus_sample( feat: torch.Tensor, mode=None, factors=None, *, interpolation="bilinear", align_corners=False, ) -> torch.Tensor: """ :param feat: 输入特征 :param mode: size/scale :param factors: shape list for mode=size or scale list for mode=scale :param interpolation: :param align_corners: 具体差异可见https://www.yuque.com/lart/idh721/ugwn46 :return: the resized tensor """ if mode is None: return feat else: if factors is None: raise ValueError( f"factors should be valid data when mode is not None, but it is {factors} now." f"feat.shape: {feat.shape}, mode: {mode}, interpolation: {interpolation}, align_corners: {align_corners}" ) interp_cfg = {} if mode == "size": if isinstance(factors, Number): factors = (factors, factors) assert isinstance(factors, (list, tuple)) and len(factors) == 2 factors = [int(x) for x in factors] if factors == list(feat.shape[2:]): return feat interp_cfg["size"] = factors elif mode == "scale": assert isinstance(factors, (int, float)) if factors == 1: return feat recompute_scale_factor = None if isinstance(factors, float): recompute_scale_factor = False interp_cfg["scale_factor"] = factors interp_cfg["recompute_scale_factor"] = recompute_scale_factor else: raise NotImplementedError(f"mode can not be {mode}") if interpolation == "nearest": if align_corners is False: align_corners = None assert align_corners is None, ( "align_corners option can only be set with the interpolating modes: " "linear | bilinear | bicubic | trilinear, so we will set it to None" ) try: result = F.interpolate(feat, mode=interpolation, align_corners=align_corners, **interp_cfg) except NotImplementedError as e: print( f"shape: {feat.shape}\n" f"mode={mode}\n" f"factors={factors}\n" f"interpolation={interpolation}\n" f"align_corners={align_corners}" ) raise e except Exception as e: raise e return result def upsample_add(*xs: torch.Tensor, interpolation="bilinear", align_corners=False) -> torch.Tensor: """ resize xs[:-1] to the size of xs[-1] and add them together. Args: xs: interpolation: config for cus_sample align_corners: config for cus_sample """ y = xs[-1] for x in xs[:-1]: y = y + cus_sample( x, mode="size", factors=y.size()[2:], interpolation=interpolation, align_corners=align_corners ) return y def upsample_cat(*xs: torch.Tensor, interpolation="bilinear", align_corners=False) -> torch.Tensor: """ resize xs[:-1] to the size of xs[-1] and concat them together. Args: xs: interpolation: config for cus_sample align_corners: config for cus_sample """ y = xs[-1] out = [] for x in xs[:-1]: out.append( cus_sample(x, mode="size", factors=y.size()[2:], interpolation=interpolation, align_corners=align_corners) ) return torch.cat([*out, y], dim=1) def upsample_reduce(b, a, interpolation="bilinear", align_corners=False) -> torch.Tensor: """ 上采样所有特征到最后一个特征的尺度以及前一个特征的通道数 """ _, C, _, _ = b.size() N, _, H, W = a.size() b = cus_sample(b, mode="size", factors=(H, W), interpolation=interpolation, align_corners=align_corners) a = a.reshape(N, -1, C, H, W).mean(1) return b + a def shuffle_channels(x, groups): """ Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,W] -> [N,C,H,W] 一共C个channel要分成g组混合的channel,先把C reshape成(g, C/g)的形状, 然后转置成(C/g, g)最后平坦成C组channel """ N, C, H, W = x.size() x = x.reshape(N, groups, C // groups, H, W).permute(0, 2, 1, 3, 4) return x.reshape(N, C, H, W) def clip_grad(params, mode, clip_cfg: dict): if mode == "norm": if "max_norm" not in clip_cfg: raise ValueError(f"`clip_cfg` must contain `max_norm`.") torch.nn.utils.clip_grad_norm_( params, max_norm=clip_cfg.get("max_norm"), norm_type=clip_cfg.get("norm_type", 2.0) ) elif mode == "value": if "clip_value" not in clip_cfg: raise ValueError(f"`clip_cfg` must contain `clip_value`.") torch.nn.utils.clip_grad_value_(params, clip_value=clip_cfg.get("clip_value")) else: raise NotImplementedError if __name__ == "__main__": a = torch.rand(3, 4, 10, 10) b = torch.rand(3, 2, 5, 5) print(upsample_reduce(b, a).size())
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/ops/array_ops.py
utils/ops/array_ops.py
# -*- coding: utf-8 -*- import os import cv2 import numpy as np def minmax(data_array: np.ndarray, up_bound: float = None) -> np.ndarray: """ :: data_array = (data_array / up_bound) if min_value != max_value: data_array = (data_array - min_value) / (max_value - min_value) :param data_array: :param up_bound: if is not None, data_array will devided by it before the minmax ops. :return: """ if up_bound is not None: data_array = data_array / up_bound max_value = data_array.max() min_value = data_array.min() if max_value != min_value: data_array = (data_array - min_value) / (max_value - min_value) return data_array def clip_to_normalize(data_array: np.ndarray, clip_range: tuple = None) -> np.ndarray: clip_range = sorted(clip_range) if len(clip_range) == 3: clip_min, clip_mid, clip_max = clip_range assert 0 <= clip_min < clip_mid < clip_max <= 1, clip_range lower_array = data_array[data_array < clip_mid] higher_array = data_array[data_array > clip_mid] if lower_array.size > 0: lower_array = np.clip(lower_array, a_min=clip_min, a_max=1) max_lower = lower_array.max() lower_array = minmax(lower_array) * max_lower data_array[data_array < clip_mid] = lower_array if higher_array.size > 0: higher_array = np.clip(higher_array, a_min=0, a_max=clip_max) min_lower = higher_array.min() higher_array = minmax(higher_array) * (1 - min_lower) + min_lower data_array[data_array > clip_mid] = higher_array elif len(clip_range) == 2: clip_min, clip_max = clip_range assert 0 <= clip_min < clip_max <= 1, clip_range if clip_min != 0 and clip_max != 1: data_array = np.clip(data_array, a_min=clip_min, a_max=clip_max) data_array = minmax(data_array) elif clip_range is None: data_array = minmax(data_array) else: raise NotImplementedError return data_array def clip_normalize_scale(array, clip_min=0, clip_max=250, new_min=0, new_max=255): array = np.clip(array, a_min=clip_min, a_max=clip_max) array = minmax(array) * (new_max - new_min) + new_min return array def save_array_as_image(data_array: np.ndarray, save_name: str, save_dir: str, to_minmax: bool = False): """ save the ndarray as a image Args: data_array: np.float32 the max value is less than or equal to 1 save_name: with special suffix save_dir: the dirname of the image path to_minmax: minmax the array """ if not os.path.exists(save_dir): os.makedirs(save_dir) save_path = os.path.join(save_dir, save_name) if data_array.dtype != np.uint8: if data_array.max() > 1: raise Exception("the range of data_array has smoe errors") data_array = (data_array * 255).astype(np.uint8) if to_minmax: data_array = minmax(data_array, up_bound=255) data_array = (data_array * 255).astype(np.uint8) cv2.imwrite(save_path, data_array) def imresize(image_array: np.ndarray, target_h, target_w, interp="linear"): _interp_mapping = dict( linear=cv2.INTER_LINEAR, cubic=cv2.INTER_CUBIC, nearst=cv2.INTER_NEAREST, ) assert interp in _interp_mapping, f"Only support interp: {_interp_mapping.keys()}" resized_image_array = cv2.resize(image_array, dsize=(target_w, target_h), interpolation=_interp_mapping[interp]) return resized_image_array
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/ops/__init__.py
utils/ops/__init__.py
# -*- coding: utf-8 -*- # @Time : 2020/12/19 # @Author : Lart Pang # @GitHub : https://github.com/lartpang from .array_ops import * from .module_ops import * from .tensor_ops import *
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/ops/module_ops.py
utils/ops/module_ops.py
# -*- coding: utf-8 -*- # @Time : 2021/5/17 # @Author : Lart Pang # @GitHub : https://github.com/lartpang from typing import Callable import torch def replace_module( model, source_base_class, *, target_object=None, target_class=None, reload_params_func: Callable = None ): if target_object is None: if target_class is None and reload_params_func is None: raise ValueError("target_class=None and reload_params_func=None can not happen with target_object=None") else: if not (target_class is None and reload_params_func is None): raise ValueError("target_class!=None and reload_params_func!=None can not happen with target_object!=None") for tokens, curr_module in model.named_modules(): if isinstance(curr_module, source_base_class): all_tokens = tokens.split(".") parent_tokens = all_tokens[:-1] target_token = all_tokens[-1] curr_attr = model for t in parent_tokens: curr_attr = getattr(curr_attr, t) if target_class and reload_params_func: target_attr = getattr(curr_attr, target_token) target_object = reload_params_func(target_attr, target_class) setattr(curr_attr, target_token, target_object) @torch.no_grad() def load_params_for_new_conv(conv_layer, new_conv_layer, in_dim: int): o, i, k_h, k_w = new_conv_layer.weight.shape ori_weight = conv_layer.weight if in_dim < 3: new_weight = ori_weight[:, :in_dim] else: new_weight = torch.repeat_interleave(ori_weight, repeats=in_dim // i + 1, dim=1)[:, :in_dim] new_conv_layer.weight = nn.Parameter(new_weight) new_conv_layer.bias = conv_layer.bias
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/pipeline/ema.py
utils/pipeline/ema.py
# -*- coding: utf-8 -*- # @Time : 2021/7/25 # @Author : Lart Pang # @GitHub : https://github.com/lartpang from copy import deepcopy import torch from torch import nn class ModelEma(nn.Module): def __init__(self, model, decay=0.9999, has_set=False, device=None): """Model Exponential Moving Average V2 From timm library. Keep a moving average of everything in the model state_dict (parameters and buffers). V2 of this module is simpler, it does not match params/buffers based on name but simply iterates in order. It works with torchscript (JIT of full model). This is intended to allow functionality like https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage A smoothed version of the weights is necessary for some training schemes to perform well. E.g. Google's hyper-params for training MNASNet, MobileNet-V3, EfficientNet, etc that use RMSprop with a short 2.4-3 epoch decay period and slow LR decay rate of .96-.99 requires EMA smoothing of weights to match results. Pay attention to the decay constant you are using relative to your update count per epoch. To keep EMA from using GPU resources, set device='cpu'. This will save a bit of memory but disable validation of the EMA weights. Validation will have to be done manually in a separate process, or after the training stops converging. This class is sensitive where it is initialized in the sequence of model init, GPU assignment and distributed training wrappers. :param model: :param decay: :param has_set: If the model has a good state, you can set the item to True, otherwise, the update method only work when you has called the set method to initialize self.module with a better state. :param device: """ super().__init__() print(f"[{model.__class__.__name__}] Model Exponential Moving Average with decay: {decay} & device: {device}") # make a copy of the model for accumulating moving average of weights self.module = deepcopy(model) self.module.eval() self.decay = decay self.has_set = has_set self.device = device # perform ema on different device from model if set if self.device is not None: self.module.to(device=device) @torch.no_grad() def _update(self, model, update_fn): if hasattr(model, "module"): model = model.module for ema_v, model_v in zip(self.module.state_dict().values(), model.state_dict().values()): if self.device is not None: model_v = model_v.to(device=self.device) ema_v.copy_(update_fn(ema_v, model_v)) def update(self, model, decay=None): """ Use model to update self.module based on a moving average method. """ if self.has_set: if decay is None: decay = self.decay self._update(model, update_fn=lambda e, m: decay * e + (1.0 - decay) * m) def set(self, model): """ Use model to initialize self.module. """ self._update(model, update_fn=lambda e, m: m) self.has_set = True
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/pipeline/tta.py
utils/pipeline/tta.py
# -*- coding: utf-8 -*- # @Time : 2021/5/31 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import ttach as tta def test_aug(model, data, strategy, reducation="mean", output_key=None): print(f"We will use Test Time Augmentation with {strategy}!") merger = tta.base.Merger(type=reducation, n=len(strategy)) transforms = tta.Compose([getattr(tta, name)(**args) for name, args in strategy.items()]) for transformer in transforms: # augment image aug_data = {name: transformer.augment_image(data_item) for name, data_item in data.items()} # pass to model model_output = model(data=aug_data) # reverse augmentation if output_key is not None: model_output = model_output[output_key] deaug_logits = transformer.deaugment_mask(model_output) # save results merger.append(deaug_logits) logits = merger.result # reduce results as you want, e.g mean/max/min if output_key is not None: logits = {output_key: logits} return logits
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/pipeline/optimizer.py
utils/pipeline/optimizer.py
# -*- coding: utf-8 -*- # @Time : 2020/12/19 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import types from torch import nn from torch.optim import Adam, AdamW, SGD def get_optimizer(mode, params, initial_lr, optim_cfg): if mode == "sgd": optimizer = SGD(params=params, lr=initial_lr, **optim_cfg) elif mode == "adamw": optimizer = AdamW(params=params, lr=initial_lr, **optim_cfg) elif mode == "adam": optimizer = Adam(params=params, lr=initial_lr, **optim_cfg) else: raise NotImplementedError return optimizer def group_params(model, group_mode, initial_lr, optim_cfg): if group_mode == "yolov5": """ norm, weight, bias = [], [], [] # optimizer parameter groups for k, v in model.named_modules(): if hasattr(v, "bias") and isinstance(v.bias, nn.Parameter): bias.append(v.bias) # biases if isinstance(v, nn.BatchNorm2d): norm.append(v.weight) # no decay elif hasattr(v, "weight") and isinstance(v.weight, nn.Parameter): weight.append(v.weight) # apply decay if opt.adam: optimizer = optim.Adam(norm, lr=hyp["lr0"], betas=(hyp["momentum"], 0.999)) # adjust beta1 to momentum else: optimizer = optim.SGD(norm, lr=hyp["lr0"], momentum=hyp["momentum"], nesterov=True) optimizer.add_param_group({"params": weight, "weight_decay": hyp["weight_decay"]}) # add weight with weight_decay optimizer.add_param_group({"params": bias}) # add bias (biases) """ norm, weight, bias = [], [], [] # optimizer parameter groups for k, v in model.named_modules(): if hasattr(v, "bias") and isinstance(v.bias, nn.Parameter): bias.append(v.bias) # conv bias and bn bias if isinstance(v, nn.BatchNorm2d): norm.append(v.weight) # bn weight elif hasattr(v, "weight") and isinstance(v.weight, nn.Parameter): weight.append(v.weight) # conv weight params = [ {"params": bias, "weight_decay": 0.0}, {"params": norm, "weight_decay": 0.0}, {"params": weight}, ] elif group_mode == "r3": params = [ # 不对bias参数执行weight decay操作,weight decay主要的作用就是通过对网络 # 层的参数(包括weight和bias)做约束(L2正则化会使得网络层的参数更加平滑)达 # 到减少模型过拟合的效果。 { "params": [param for name, param in model.named_parameters() if name[-4:] == "bias"], "lr": 2 * initial_lr, "weight_decay": 0, }, { "params": [param for name, param in model.named_parameters() if name[-4:] != "bias"], "lr": initial_lr, "weight_decay": optim_cfg["weight_decay"], }, ] elif group_mode == "all": params = model.parameters() elif group_mode == "finetune": if hasattr(model, "module"): model = model.module assert hasattr(model, "get_grouped_params"), "Cannot get the method get_grouped_params of the model." params_groups = model.get_grouped_params() params = [ {"params": params_groups["pretrained"], "lr": 0.1 * initial_lr}, {"params": params_groups["retrained"], "lr": initial_lr}, ] else: raise NotImplementedError return params def construct_optimizer(model, initial_lr, mode, group_mode, cfg): params = group_params(model, group_mode=group_mode, initial_lr=initial_lr, optim_cfg=cfg) optimizer = get_optimizer(mode=mode, params=params, initial_lr=initial_lr, optim_cfg=cfg) optimizer.lr_groups = types.MethodType(get_lr_groups, optimizer) optimizer.lr_string = types.MethodType(get_lr_strings, optimizer) return optimizer def get_lr_groups(self): return [group["lr"] for group in self.param_groups] def get_lr_strings(self): return ",".join([f"{group['lr']:10.3e}" for group in self.param_groups])
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/pipeline/__init__.py
utils/pipeline/__init__.py
# -*- coding: utf-8 -*- # @Time : 2021/5/31 # @Author : Lart Pang # @GitHub : https://github.com/lartpang from .dataloader import * from .ema import ModelEma from .optimizer import construct_optimizer from .scheduler import Scheduler from .tta import test_aug
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/pipeline/dataloader.py
utils/pipeline/dataloader.py
# -*- coding: utf-8 -*- # @Time : 2021/5/29 # @Author : Lart Pang # @GitHub : https://github.com/lartpang from functools import partial from torch.utils import data from utils import builder, misc def get_tr_loader(cfg, shuffle=True, drop_last=True, pin_memory=True): dataset = builder.build_obj_from_registry( registry_name="DATASETS", obj_name=cfg.datasets.train.dataset_type, obj_cfg=dict( root=[(name, path) for name, path in cfg.datasets.train.path.items()], shape=cfg.datasets.train.shape, extra_scales=cfg.train.ms.extra_scales if cfg.train.ms.enable else None, interp_cfg=cfg.datasets.train.get("interp_cfg", None), ), ) if cfg.use_ddp: train_sampler = data.distributed.DistributedSampler(dataset, shuffle=shuffle) shuffle = False else: train_sampler = None shuffle = shuffle if cfg.train.ms.enable: collate_fn = getattr(dataset, "collate_fn", None) assert collate_fn is not None else: collate_fn = None loader = data.DataLoader( dataset=dataset, batch_size=cfg.train.batch_size, sampler=train_sampler, shuffle=shuffle, num_workers=cfg.train.num_workers, drop_last=drop_last, pin_memory=pin_memory, collate_fn=collate_fn, worker_init_fn=partial(misc.customized_worker_init_fn, base_seed=cfg.base_seed) if cfg.use_custom_worker_init else None, ) print(f"Length of Trainset: {len(dataset)}") return loader def get_te_loader(cfg, shuffle=False, drop_last=False, pin_memory=True) -> list: for i, (te_data_name, te_data_path) in enumerate(cfg.datasets.test.path.items()): dataset = builder.build_obj_from_registry( registry_name="DATASETS", obj_name=cfg.datasets.test.dataset_type, obj_cfg=dict( root=(te_data_name, te_data_path), shape=cfg.datasets.test.shape, interp_cfg=cfg.datasets.test.get("interp_cfg", None), ), ) loader = data.DataLoader( dataset=dataset, batch_size=cfg.test.batch_size, num_workers=cfg.test.num_workers, shuffle=shuffle, drop_last=drop_last, pin_memory=pin_memory, collate_fn=getattr(dataset, "collate_fn", None), worker_init_fn=partial(misc.customized_worker_init_fn, base_seed=cfg.base_seed) if cfg.use_custom_worker_init else None, ) print(f"Testing with testset: {te_data_name}: {len(dataset)}") yield te_data_name, te_data_path, loader
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/utils/pipeline/scheduler.py
utils/pipeline/scheduler.py
# -*- coding: utf-8 -*- # @Time : 2020/12/19 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import copy import math import os.path import warnings from bisect import bisect_right import numpy as np import torch.optim from scipy import signal # helper function ---------------------------------------------------------------------- def linear_increase(low_bound, up_bound, percentage): """low_bound + [0, 1] * (up_bound - low_bound)""" assert 0 <= percentage <= 1, f"percentage({percentage}) must be in [0, 1]" return low_bound + (up_bound - low_bound) * percentage def cos_anneal(low_bound, up_bound, percentage): assert 0 <= percentage <= 1, f"percentage({percentage}) must be in [0, 1]" cos_percentage = (1 + math.cos(math.pi * percentage)) / 2.0 return linear_increase(low_bound, up_bound, percentage=cos_percentage) def poly_anneal(low_bound, up_bound, percentage, lr_decay): assert 0 <= percentage <= 1, f"percentage({percentage}) must be in [0, 1]" poly_percentage = pow((1 - percentage), lr_decay) return linear_increase(low_bound, up_bound, percentage=poly_percentage) def linear_anneal(low_bound, up_bound, percentage): assert 0 <= percentage <= 1, f"percentage({percentage}) must be in [0, 1]" return linear_increase(low_bound, up_bound, percentage=1 - percentage) # coefficient function ---------------------------------------------------------------------- def get_f3_coef_func(num_iters): """ F3Net :param num_iters: The number of iterations for the total process. :return: """ def get_f3_coef(curr_idx): assert 0 <= curr_idx <= num_iters return 1 - abs((curr_idx + 1) / (num_iters + 1) * 2 - 1) return get_f3_coef def get_step_coef_func(gamma, milestones): """ lr = baselr * gamma ** 0 if curr_idx < milestones[0] lr = baselr * gamma ** 1 if milestones[0] <= epoch < milestones[1] ... :param gamma: :param milestones: :return: The function for generating the coefficient. """ if isinstance(milestones, (tuple, list)): milestones = list(sorted(milestones)) return lambda curr_idx: gamma ** bisect_right(milestones, curr_idx) elif isinstance(milestones, int): return lambda curr_idx: gamma ** ((curr_idx + 1) // milestones) else: raise ValueError(f"milestones only can be list/tuple/int, but now it is {type(milestones)}") def get_cos_coef_func(half_cycle, min_coef, max_coef=1): """ :param half_cycle: The number of iterations in a half cycle. :param min_coef: The minimum coefficient of the learning rate. :param max_coef: The maximum coefficient of the learning rate. :return: The function for generating the coefficient. """ def get_cos_coef(curr_idx): recomputed_idx = curr_idx % (half_cycle + 1) # recomputed \in [0, half_cycle] return cos_anneal(low_bound=min_coef, up_bound=max_coef, percentage=recomputed_idx / half_cycle) return get_cos_coef def get_poly_coef_func(num_iters, lr_decay, min_coef, max_coef=1): """ :param num_iters: The number of iterations for the polynomial descent process. :param lr_decay: The decay item of the polynomial descent process. :param min_coef: The minimum coefficient of the learning rate. :param max_coef: The maximum coefficient of the learning rate. :return: The function for generating the coefficient. """ def get_poly_coef(curr_idx): assert 0 <= curr_idx <= num_iters, (curr_idx, num_iters) return poly_anneal(low_bound=min_coef, up_bound=max_coef, percentage=curr_idx / num_iters, lr_decay=lr_decay) return get_poly_coef # coefficient entry function ---------------------------------------------------------------------- def get_scheduler_coef_func(mode, num_iters, cfg): """ the region is a closed interval: [0, num_iters] """ assert num_iters > 0 min_coef = cfg.get("min_coef", 1e-6) if min_coef is None or min_coef == 0: warnings.warn(f"The min_coef ({min_coef}) of the scheduler will be replaced with 1e-6") min_coef = 1e-6 if mode == "step": coef_func = get_step_coef_func(gamma=cfg["gamma"], milestones=cfg["milestones"]) elif mode == "cos": if half_cycle := cfg.get("half_cycle"): half_cycle -= 1 else: half_cycle = num_iters if (num_iters - half_cycle) % (half_cycle + 1) != 0: # idx starts from 0 percentage = ((num_iters - half_cycle) % (half_cycle + 1)) / (half_cycle + 1) * 100 warnings.warn( f"The final annealing process ({percentage:.3f}%) is not complete. " f"Please pay attention to the generated 'lr_coef_curve.png'." ) coef_func = get_cos_coef_func(half_cycle=half_cycle, min_coef=min_coef) elif mode == "poly": coef_func = get_poly_coef_func(num_iters=num_iters, lr_decay=cfg["lr_decay"], min_coef=min_coef) elif mode == "constant": coef_func = lambda x: cfg.get("constant_coef", 1) elif mode == "f3": coef_func = get_f3_coef_func(num_iters=num_iters) else: raise NotImplementedError return coef_func def get_warmup_coef_func(num_iters, min_coef, max_coef=1, mode="linear"): """ the region is a closed interval: [0, num_iters] """ assert num_iters > 0 if mode == "cos": anneal_func = cos_anneal elif mode == "linear": anneal_func = linear_anneal else: raise NotImplementedError def get_warmup_coef(curr_idx): return anneal_func(low_bound=min_coef, up_bound=max_coef, percentage=1 - curr_idx / num_iters) return get_warmup_coef # main class ---------------------------------------------------------------------- class Scheduler: supported_scheduler_modes = ("step", "cos", "poly", "constant", "f3") supported_warmup_modes = ("cos", "linear") def __init__(self, optimizer, num_iters, epoch_length, scheduler_cfg, step_by_batch=True): """A customized wrapper of the scheduler. Args: optimizer (): Optimizer. num_iters (int): The total number of the iterations. epoch_length (int): The number of the iterations of one epoch. scheduler_cfg (dict): The config of the scheduler. step_by_batch (bool, optional): The mode of updating the scheduler. Defaults to True. Raises: NotImplementedError: """ self.optimizer = optimizer self.num_iters = num_iters self.epoch_length = epoch_length self.step_by_batch = step_by_batch self.scheduler_cfg = copy.deepcopy(scheduler_cfg) self.mode = scheduler_cfg.pop("mode") if self.mode not in self.supported_scheduler_modes: raise NotImplementedError( f"{self.mode} is not implemented. " f"Has been supported: {self.supported_scheduler_modes}" ) warmup_cfg = scheduler_cfg.pop("warmup", None) num_warmup_iters = 0 if warmup_cfg is not None and isinstance(warmup_cfg, dict): num_warmup_iters = warmup_cfg["num_iters"] if num_warmup_iters > 0: print(f"Will using warmup") self.warmup_coef_func = get_warmup_coef_func( num_warmup_iters, min_coef=warmup_cfg.get("initial_coef", 0.01), mode=warmup_cfg.get("mode", "linear"), ) self.num_warmup_iters = num_warmup_iters if step_by_batch: num_scheduler_iters = num_iters - num_warmup_iters else: num_scheduler_iters = (num_iters - num_warmup_iters) // epoch_length # the region is a closed interval self.lr_coef_func = get_scheduler_coef_func( mode=self.mode, num_iters=num_scheduler_iters - 1, cfg=scheduler_cfg["cfg"] ) self.num_scheduler_iters = num_scheduler_iters self.last_lr_coef = 0 self.initial_lrs = None def __repr__(self): formatted_string = [ f"{self.__class__.__name__}: (\n", f"num_iters: {self.num_iters}\n", f"epoch_length: {self.epoch_length}\n", f"warmup_iter: [0, {self.num_warmup_iters})\n", f"scheduler_iter: [{self.num_warmup_iters}, {self.num_iters - 1}]\n", f"mode: {self.mode}\n", f"scheduler_cfg: {self.scheduler_cfg}\n", f"initial_lrs: {self.initial_lrs}\n", f"step_by_batch: {self.step_by_batch}\n)", ] return " ".join(formatted_string) def record_lrs(self, param_groups): self.initial_lrs = [g["lr"] for g in param_groups] def update(self, coef: float): assert self.initial_lrs is not None, "Please run .record_lrs(optimizer) first." for curr_group, initial_lr in zip(self.optimizer.param_groups, self.initial_lrs): curr_group["lr"] = coef * initial_lr def step(self, curr_idx): if curr_idx < self.num_warmup_iters: # get maximum value (1.0) when curr_idx == self.num_warmup_iters self.update(coef=self.get_lr_coef(curr_idx)) else: # Start from a value lower than 1 (curr_idx == self.num_warmup_iters) if self.step_by_batch: self.update(coef=self.get_lr_coef(curr_idx)) else: if curr_idx % self.epoch_length == 0: self.update(coef=self.get_lr_coef(curr_idx)) def get_lr_coef(self, curr_idx): coef = None if curr_idx < self.num_warmup_iters: coef = self.warmup_coef_func(curr_idx) else: # when curr_idx == self.num_warmup_iters, coef == 1.0 # down from the largest coef (1.0) if self.step_by_batch: coef = self.lr_coef_func(curr_idx - self.num_warmup_iters) else: if curr_idx % self.epoch_length == 0 or curr_idx == self.num_warmup_iters: # warmup结束后尚未开始按照epoch进行调整的学习率调整,此时需要将系数调整为最大。 coef = self.lr_coef_func((curr_idx - self.num_warmup_iters) // self.epoch_length) if coef is not None: self.last_lr_coef = coef return self.last_lr_coef def plot_lr_coef_curve(self, show=False, save_path=""): try: import matplotlib.pyplot as plt except ImportError as e: print("Please install matplotlib before using the method.") raise e plt.style.use("bmh") fig, ax = plt.subplots() # give plot a title ax.set_title("Learning Rate Coefficient Curve") # make axis labels ax.set_xlabel("Index") ax.set_ylabel("Coefficient") # set ticks ax.set_xticks(np.linspace(0, self.num_iters, 11)) ax.set_yticks(np.linspace(0, 1, 11)) x_data = np.arange(self.num_iters) y_data = np.array([self.get_lr_coef(x) for x in x_data]) ax.plot(x_data, y_data, linewidth=2) maximum_xs = signal.argrelextrema(y_data, comparator=np.greater_equal)[0] maximum_ys = y_data[maximum_xs] minimum_xs = signal.argrelextrema(y_data, comparator=np.less_equal)[0] minimum_ys = y_data[minimum_xs] end_point_xs = np.array([x_data[0], x_data[-1]]) end_point_ys = np.array([y_data[0], y_data[-1]]) for pt in zip( np.concatenate((maximum_xs, minimum_xs, end_point_xs)), np.concatenate((maximum_ys, minimum_ys, end_point_ys)), ): ax.text(pt[0], pt[1], s=f"({pt[0]:d}, {pt[1]:.6e})") if show: plt.show() if save_path: fig.savefig(os.path.join(save_path, "lr_coef_curve.png"), dpi=300) if __name__ == "__main__": model = torch.nn.Conv2d(10, 10, 3, 1, 1) sche = Scheduler( optimizer=torch.optim.SGD(model.parameters(), lr=0.1), num_iters=30300, epoch_length=505, scheduler_cfg=dict( warmup=dict( num_iters=6060, initial_coef=0.01, mode="cos", ), mode="cos", cfg=dict( half_cycle=6060, lr_decay=0.9, min_coef=0.001, ), ), step_by_batch=True, ) print(sche) sche.plot_lr_coef_curve( # save_path="/home/lart/Coding/SOD.torch", show=True, )
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/dataset/base_dataset.py
dataset/base_dataset.py
# -*- coding: utf-8 -*- # @Time : 2021/5/16 # @Author : Lart Pang # @GitHub : https://github.com/lartpang import random from collections import abc import torch from torch.utils.data import DataLoader, Dataset from torch.utils.data._utils.collate import default_collate from utils.ops.tensor_ops import cus_sample class _BaseSODDataset(Dataset): def __init__(self, base_shape: dict, extra_scales: tuple = None, interp_cfg: dict = None): """ :param base_shape: :param extra_scales: for multi-scale training :param interp_cfg: the config of the interpolation, if it is None, the interpolation will not be done. """ super().__init__() self.base_shape = base_shape if extra_scales is not None and interp_cfg is None: raise ValueError("interp_cfg must be True Value when extra_scales is not None.") self.extra_scales = extra_scales self._sizes = [(base_shape["h"], base_shape["w"])] if extra_scales: self._sizes.extend( # 确保是32的整数倍 [ ( s * base_shape["h"] // 32 * 32, s * base_shape["w"] // 32 * 32, ) for s in extra_scales ] ) if not interp_cfg: # None or {} interp_cfg = {} self._combine_func = torch.stack else: print(f"Using multi-scale training strategy with extra scales: {self._sizes}") self._combine_func = torch.cat self._interp_cfg = interp_cfg self._default_cfg = dict(interpolation="bilinear", align_corners=False) def _collate(self, batch, parent_key=None): """ borrow from 'torch.utils.data._utils.collate.default_collate' """ elem = batch[0] elem_type = type(elem) if isinstance(elem, torch.Tensor): interp_cfg = self._interp_cfg.get(parent_key, None) if interp_cfg is None: interp_cfg = self._default_cfg else: interp_cfg["factors"] = self._default_cfg["factors"] batch = [cus_sample(it.unsqueeze(0), mode="size", **interp_cfg) for it in batch] out = None if torch.utils.data.get_worker_info() is not None: # If we're in a background process, concatenate directly into a # shared memory tensor to avoid an extra copy numel = sum([x.numel() for x in batch]) storage = elem.storage()._new_shared(numel) out = elem.new(storage) return self._combine_func(batch, dim=0, out=out) elif isinstance(elem, float): return torch.tensor(batch, dtype=torch.float64) elif isinstance(elem, int): return torch.tensor(batch) elif isinstance(elem, (str, bytes)): return batch elif isinstance(elem, abc.Mapping): return {key: self._collate([d[key] for d in batch], parent_key=key) for key in elem} elif isinstance(elem, tuple) and hasattr(elem, "_fields"): # namedtuple return elem_type(*(self._collate(samples) for samples in zip(*batch))) elif isinstance(elem, abc.Sequence): # check to make sure that the elements in batch have consistent size it = iter(batch) elem_size = len(next(it)) if not all(len(elem) == elem_size for elem in it): raise RuntimeError("each element in list of batch should be of equal size") transposed = zip(*batch) return [self._collate(samples) for samples in transposed] raise TypeError("collate_fn: batch must contain tensors, numbers, dicts or lists; found {}".format(elem_type)) def collate_fn(self, batch): if self._interp_cfg: self._default_cfg["factors"] = random.choice(self._sizes) return self._collate(batch=batch) else: return default_collate(batch=batch)
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/dataset/msi_sod.py
dataset/msi_sod.py
# -*- coding: utf-8 -*- import random from typing import Dict, List, Tuple from PIL import Image from torchvision.transforms import transforms from dataset.base_dataset import _BaseSODDataset from utils.builder import DATASETS from utils.io.genaral import get_datasets_info_with_keys class RandomHorizontallyFlip(object): def __call__(self, img, mask): if random.random() < 0.5: return img.transpose(Image.FLIP_LEFT_RIGHT), mask.transpose(Image.FLIP_LEFT_RIGHT) return img, mask class RandomRotate(object): def __init__(self, degree): self.degree = degree def __call__(self, img, mask): rotate_degree = random.random() * 2 * self.degree - self.degree return img.rotate(rotate_degree, Image.BILINEAR), mask.rotate(rotate_degree, Image.NEAREST) class Compose(object): def __init__(self, transforms): self.transforms = transforms def __call__(self, img, mask): assert img.size == mask.size for t in self.transforms: img, mask = t(img, mask) return img, mask @DATASETS.register(name="msi_sod_te") class MSISOD_TestDataset(_BaseSODDataset): def __init__(self, root: Tuple[str, dict], shape: Dict[str, int], interp_cfg: Dict = None): super().__init__(base_shape=shape, interp_cfg=interp_cfg) self.datasets = get_datasets_info_with_keys(dataset_infos=[root], extra_keys=["mask"]) self.total_image_paths = self.datasets["image"] self.total_mask_paths = self.datasets["mask"] self.to_tensor = transforms.ToTensor() self.to_normalize = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) def __getitem__(self, index): image_path = self.total_image_paths[index] mask_path = self.total_mask_paths[index] image = Image.open(image_path).convert("RGB") base_h = self.base_shape["h"] base_w = self.base_shape["w"] image_1_5 = image.resize((int(base_h * 1.5), int(base_w * 1.5)), resample=Image.BILINEAR) image_1_0 = image.resize((base_h, base_w), resample=Image.BILINEAR) image_0_5 = image.resize((int(base_h * 0.5), int(base_w * 0.5)), resample=Image.BILINEAR) image_1_5 = self.to_normalize(self.to_tensor(image_1_5)) image_1_0 = self.to_normalize(self.to_tensor(image_1_0)) image_0_5 = self.to_normalize(self.to_tensor(image_0_5)) return dict( data={ "image1.5": image_1_5, "image1.0": image_1_0, "image0.5": image_0_5, }, info=dict( mask_path=mask_path, ), ) def __len__(self): return len(self.total_image_paths) @DATASETS.register(name="msi_sod_tr") class MSISOD_TrainDataset(_BaseSODDataset): def __init__( self, root: List[Tuple[str, dict]], shape: Dict[str, int], extra_scales: List = None, interp_cfg: Dict = None ): super().__init__(base_shape=shape, extra_scales=extra_scales, interp_cfg=interp_cfg) self.datasets = get_datasets_info_with_keys(dataset_infos=root, extra_keys=["mask"]) self.total_image_paths = self.datasets["image"] self.total_mask_paths = self.datasets["mask"] self.joint_transform = Compose([RandomHorizontallyFlip(), RandomRotate(10)]) self.to_tensor = transforms.ToTensor() self.image_transform = transforms.ColorJitter(0.1, 0.1, 0.1) self.to_normalize = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) def __getitem__(self, index): image_path = self.total_image_paths[index] mask_path = self.total_mask_paths[index] image = Image.open(image_path).convert("RGB") mask = Image.open(mask_path).convert("L") image, mask = self.joint_transform(image, mask) image = self.image_transform(image) base_h = self.base_shape["h"] base_w = self.base_shape["w"] image_1_5 = image.resize((int(base_h * 1.5), int(base_w * 1.5)), resample=Image.BILINEAR) image_1_0 = image.resize((base_h, base_w), resample=Image.BILINEAR) image_0_5 = image.resize((int(base_h * 0.5), int(base_w * 0.5)), resample=Image.BILINEAR) image_1_5 = self.to_normalize(self.to_tensor(image_1_5)) image_1_0 = self.to_normalize(self.to_tensor(image_1_0)) image_0_5 = self.to_normalize(self.to_tensor(image_0_5)) mask_1_0 = mask.resize((base_h, base_w), resample=Image.BILINEAR) mask_1_0 = self.to_tensor(mask_1_0) mask_1_0 = mask_1_0.ge(0.5).float() # 二值化 return dict( data={ "image1.5": image_1_5, "image1.0": image_1_0, "image0.5": image_0_5, "mask": mask_1_0, } ) def __len__(self): return len(self.total_image_paths)
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/dataset/msi_cod.py
dataset/msi_cod.py
# -*- coding: utf-8 -*- from typing import Dict, List, Tuple import albumentations as A import cv2 import torch from dataset.base_dataset import _BaseSODDataset from dataset.transforms.resize import ms_resize, ss_resize from dataset.transforms.rotate import UniRotate from utils.builder import DATASETS from utils.io.genaral import get_datasets_info_with_keys from utils.io.image import read_color_array, read_gray_array @DATASETS.register(name="msi_cod_te") class MSICOD_TestDataset(_BaseSODDataset): def __init__(self, root: Tuple[str, dict], shape: Dict[str, int], interp_cfg: Dict = None): super().__init__(base_shape=shape, interp_cfg=interp_cfg) self.datasets = get_datasets_info_with_keys(dataset_infos=[root], extra_keys=["mask"]) self.total_image_paths = self.datasets["image"] self.total_mask_paths = self.datasets["mask"] self.image_norm = A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)) def __getitem__(self, index): image_path = self.total_image_paths[index] mask_path = self.total_mask_paths[index] image = read_color_array(image_path) image = self.image_norm(image=image)["image"] base_h = self.base_shape["h"] base_w = self.base_shape["w"] images = ms_resize(image, scales=(0.5, 1.0, 1.5), base_h=base_h, base_w=base_w) image_0_5 = torch.from_numpy(images[0]).permute(2, 0, 1) image_1_0 = torch.from_numpy(images[1]).permute(2, 0, 1) image_1_5 = torch.from_numpy(images[2]).permute(2, 0, 1) return dict( data={ "image1.5": image_1_5, "image1.0": image_1_0, "image0.5": image_0_5, }, info=dict( mask_path=mask_path, ), ) def __len__(self): return len(self.total_image_paths) @DATASETS.register(name="msi_cod_tr") class MSICOD_TrainDataset(_BaseSODDataset): def __init__( self, root: List[Tuple[str, dict]], shape: Dict[str, int], extra_scales: List = None, interp_cfg: Dict = None ): super().__init__(base_shape=shape, extra_scales=extra_scales, interp_cfg=interp_cfg) self.datasets = get_datasets_info_with_keys(dataset_infos=root, extra_keys=["mask"]) self.total_image_paths = self.datasets["image"] self.total_mask_paths = self.datasets["mask"] self.joint_trans = A.Compose( [ A.HorizontalFlip(p=0.5), UniRotate(limit=10, interpolation=cv2.INTER_LINEAR, p=0.5), A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)), ], ) self.reszie = A.Resize def __getitem__(self, index): image_path = self.total_image_paths[index] mask_path = self.total_mask_paths[index] image = read_color_array(image_path) mask = read_gray_array(mask_path, to_normalize=True, thr=0.5) transformed = self.joint_trans(image=image, mask=mask) image = transformed["image"] mask = transformed["mask"] base_h = self.base_shape["h"] base_w = self.base_shape["w"] images = ms_resize(image, scales=(0.5, 1.0, 1.5), base_h=base_h, base_w=base_w) image_0_5 = torch.from_numpy(images[0]).permute(2, 0, 1) image_1_0 = torch.from_numpy(images[1]).permute(2, 0, 1) image_1_5 = torch.from_numpy(images[2]).permute(2, 0, 1) mask = ss_resize(mask, scale=1.0, base_h=base_h, base_w=base_w) mask_1_0 = torch.from_numpy(mask).unsqueeze(0) return dict( data={ "image1.5": image_1_5, "image1.0": image_1_0, "image0.5": image_0_5, "mask": mask_1_0, } ) def __len__(self): return len(self.total_image_paths)
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/dataset/__init__.py
dataset/__init__.py
# -*- coding: utf-8 -*- from .msi_cod import MSICOD_TestDataset, MSICOD_TrainDataset from .msi_sod import MSISOD_TrainDataset, MSISOD_TestDataset
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/dataset/transforms/resize.py
dataset/transforms/resize.py
import albumentations as A import cv2 class UniResize(A.DualTransform): """UniResize the input to the given height and width. Args: height (int): desired height of the output. width (int): desired width of the output. interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4. Default: cv2.INTER_LINEAR. p (float): probability of applying the transform. Default: 1. Targets: image, mask, bboxes, keypoints Image types: uint8, float32 """ def __init__(self, height, width, interpolation=cv2.INTER_LINEAR, always_apply=False, p=1): super(UniResize, self).__init__(always_apply, p) self.height = height self.width = width self.interpolation = interpolation def apply(self, img, interpolation=cv2.INTER_LINEAR, **params): return A.resize(img, height=self.height, width=self.width, interpolation=interpolation) def apply_to_mask(self, img, interpolation=cv2.INTER_LINEAR, **params): return A.resize(img, height=self.height, width=self.width, interpolation=interpolation) def apply_to_bbox(self, bbox, **params): # Bounding box coordinates are scale invariant return bbox def apply_to_keypoint(self, keypoint, **params): height = params["rows"] width = params["cols"] scale_x = self.width / width scale_y = self.height / height return A.keypoint_scale(keypoint, scale_x, scale_y) def get_transform_init_args_names(self): return ("height", "width", "interpolation") def ms_resize(img, scales, base_h=None, base_w=None, interpolation=cv2.INTER_LINEAR): assert isinstance(scales, (list, tuple)) if base_h is None and base_w is None: h = img.shape[0] w = img.shape[1] else: h = base_h w = base_w return [A.resize(img, height=int(h * s), width=int(w * s), interpolation=interpolation) for s in scales] def ss_resize(img, scale, base_h=None, base_w=None, interpolation=cv2.INTER_LINEAR): if base_h is None and base_w is None: h = img.shape[0] w = img.shape[1] else: h = base_h w = base_w return A.resize(img, height=int(h * scale), width=int(w * scale), interpolation=interpolation)
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/dataset/transforms/rotate.py
dataset/transforms/rotate.py
import random import albumentations as A import cv2 class UniRotate(A.DualTransform): """UniRotate the input by an angle selected randomly from the uniform distribution. Args: limit ((int, int) or int): range from which a random angle is picked. If limit is a single int an angle is picked from (-limit, limit). Default: (-90, 90) interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4. Default: cv2.INTER_LINEAR. border_mode (OpenCV flag): flag that is used to specify the pixel extrapolation method. Should be one of: cv2.BORDER_CONSTANT, cv2.BORDER_REPLICATE, cv2.BORDER_REFLECT, cv2.BORDER_WRAP, cv2.BORDER_REFLECT_101. Default: cv2.BORDER_REFLECT_101 value (int, float, list of ints, list of float): padding value if border_mode is cv2.BORDER_CONSTANT. mask_value (int, float, list of ints, list of float): padding value if border_mode is cv2.BORDER_CONSTANT applied for masks. p (float): probability of applying the transform. Default: 0.5. Targets: image, mask, bboxes, keypoints Image types: uint8, float32 """ def __init__( self, limit=90, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101, value=None, mask_value=None, always_apply=False, p=0.5, ): super(UniRotate, self).__init__(always_apply, p) self.limit = A.to_tuple(limit) self.interpolation = interpolation self.border_mode = border_mode self.value = value self.mask_value = mask_value def apply(self, img, angle=0, interpolation=cv2.INTER_LINEAR, **params): return A.rotate(img, angle, interpolation, self.border_mode, self.value) def apply_to_mask(self, img, angle=0, interpolation=cv2.INTER_LINEAR, **params): return A.rotate(img, angle, interpolation, self.border_mode, self.mask_value) def get_params(self): return {"angle": random.uniform(self.limit[0], self.limit[1])} def apply_to_bbox(self, bbox, angle=0, **params): return A.bbox_rotate(bbox, angle, params["rows"], params["cols"]) def apply_to_keypoint(self, keypoint, angle=0, **params): return A.keypoint_rotate(keypoint, angle, **params) def get_transform_init_args_names(self): return ("limit", "interpolation", "border_mode", "value", "mask_value")
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/dataset/transforms/__init__.py
dataset/transforms/__init__.py
# -*- coding: utf-8 -*- # @Time : 2021/8/16 # @Author : Lart Pang # @GitHub : https://github.com/lartpang
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/dataset/transforms/composition.py
dataset/transforms/composition.py
import random import albumentations as A import numpy as np from albumentations.core.composition import BaseCompose class Compose(BaseCompose): """Compose transforms and handle all transformations regarding bounding boxes Args: transforms (list): list of transformations to compose. bbox_params (BboxParams): Parameters for bounding boxes transforms keypoint_params (KeypointParams): Parameters for keypoints transforms additional_targets (dict): Dict with keys - new target name, values - old target name. ex: {'image2': 'image'} p (float): probability of applying all list of transforms. Default: 1.0. """ def __init__(self, transforms, bbox_params=None, keypoint_params=None, additional_targets=None, p=1.0): super(Compose, self).__init__([t for t in transforms if t is not None], p) self.processors = {} if bbox_params: if isinstance(bbox_params, dict): params = A.BboxParams(**bbox_params) elif isinstance(bbox_params, A.BboxParams): params = bbox_params else: raise ValueError("unknown format of bbox_params, please use `dict` or `BboxParams`") self.processors["bboxes"] = A.BboxProcessor(params, additional_targets) if keypoint_params: if isinstance(keypoint_params, dict): params = A.KeypointParams(**keypoint_params) elif isinstance(keypoint_params, A.KeypointParams): params = keypoint_params else: raise ValueError("unknown format of keypoint_params, please use `dict` or `KeypointParams`") self.processors["keypoints"] = A.KeypointsProcessor(params, additional_targets) if additional_targets is None: additional_targets = {} self.additional_targets = additional_targets for proc in self.processors.values(): proc.ensure_transforms_valid(self.transforms) self.add_targets(additional_targets) def __call__(self, *args, force_apply=False, **data): if args: raise KeyError("You have to pass data to augmentations as named arguments, for example: aug(image=image)") self._check_args(**data) assert isinstance(force_apply, (bool, int)), "force_apply must have bool or int type" need_to_run = force_apply or random.random() < self.p for p in self.processors.values(): p.ensure_data_valid(data) transforms = self.transforms if need_to_run else self.transforms.get_always_apply(self.transforms) dual_start_end = transforms.start_end if self.processors else None check_each_transform = any( getattr(item.params, "check_each_transform", False) for item in self.processors.values() ) for idx, t in enumerate(transforms): if dual_start_end is not None and idx == dual_start_end[0]: for p in self.processors.values(): p.preprocess(data) data = t(force_apply=force_apply, **data) if dual_start_end is not None and idx == dual_start_end[1]: for p in self.processors.values(): p.postprocess(data) elif check_each_transform and isinstance(t, A.DualTransform): rows, cols = data["image"].shape[:2] for p in self.processors.values(): if not getattr(p.params, "check_each_transform", False): continue for data_name in p.data_fields: data[data_name] = p.filter(data[data_name], rows, cols) return data def _to_dict(self): dictionary = super(Compose, self)._to_dict() bbox_processor = self.processors.get("bboxes") keypoints_processor = self.processors.get("keypoints") dictionary.update( { "bbox_params": bbox_processor.params._to_dict() if bbox_processor else None, # skipcq: PYL-W0212 "keypoint_params": keypoints_processor.params._to_dict() # skipcq: PYL-W0212 if keypoints_processor else None, "additional_targets": self.additional_targets, } ) return dictionary def get_dict_with_id(self): dictionary = super().get_dict_with_id() bbox_processor = self.processors.get("bboxes") keypoints_processor = self.processors.get("keypoints") dictionary.update( { "bbox_params": bbox_processor.params._to_dict() if bbox_processor else None, # skipcq: PYL-W0212 "keypoint_params": keypoints_processor.params._to_dict() # skipcq: PYL-W0212 if keypoints_processor else None, "additional_targets": self.additional_targets, "params": None, } ) return dictionary def _check_args(self, **kwargs): checked_single = ["image", "mask"] checked_multi = ["masks"] # ["bboxes", "keypoints"] could be almost any type, no need to check them for data_name, data in kwargs.items(): internal_data_name = self.additional_targets.get(data_name, data_name) if internal_data_name in checked_single: if not isinstance(data, np.ndarray): raise TypeError("{} must be numpy array type".format(data_name)) if internal_data_name in checked_multi: if data: if not isinstance(data[0], np.ndarray): raise TypeError("{} must be list of numpy arrays".format(data_name))
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/configs/_base_/train.py
configs/_base_/train.py
train = dict( batch_size=10, num_workers=4, use_amp=True, num_epochs=100, num_iters=30000, epoch_based=True, lr=0.0001, optimizer=dict( mode="adamw", set_to_none=True, group_mode="r3", # ['trick', 'r3', 'all', 'finetune'], cfg=dict(), ), grad_acc_step=1, sche_usebatch=True, scheduler=dict( warmup=dict( num_iters=0, ), mode="poly", cfg=dict( lr_decay=0.9, min_coef=0.001, ), ), save_num_models=1, ms=dict( enable=False, extra_scales=[0.75, 1.25, 1.5], ), grad_clip=dict( enable=False, mode="value", # or 'norm' cfg=dict(), ), ema=dict( enable=False, cmp_with_origin=True, force_cpu=False, decay=0.9998, ), )
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/configs/_base_/common.py
configs/_base_/common.py
has_test = True base_seed = 0 deterministic = True log_interval = dict( # >0 will be logged txt=20, tensorboard=0, ) load_from = "" resume_from = "" model_name = "" experiment_tag = ""
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/configs/_base_/test.py
configs/_base_/test.py
test = dict( batch_size=8, num_workers=2, eval_func="default_test", clip_range=None, tta=dict( # based on the ttach lib enable=False, reducation="mean", # 'mean', 'gmean', 'sum', 'max', 'min', 'tsharpen' cfg=dict( HorizontalFlip=dict(), VerticalFlip=dict(), Rotate90=dict(angles=[0, 90, 180, 270]), Scale=dict( scales=[0.75, 1, 1.5], interpolation="bilinear", align_corners=False, ), Add=dict(values=[0, 10, 20]), Multiply=dict(factors=[1, 2, 5]), FiveCrops=dict(crop_height=224, crop_width=224), Resize=dict( sizes=[0.75, 1, 1.5], original_size=224, interpolation="bilinear", align_corners=False, ), ), ), )
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/configs/_base_/dataset/rgbdsod.py
configs/_base_/dataset/rgbdsod.py
datasets = dict( train=dict( dataset_type="rgbd_sod_tr", shape=dict(h=256, w=256), path=["njudtrdmra_ori", "nlprtrdmra_ori", "dutrgbdtr"], interp_cfg=dict(), ), test=dict( dataset_type="rgbd_sod_te", shape=dict(h=256, w=256), path=["dutrgbdte", "njudtedmra", "nlprtedmra", "lfsd", "rgbd135", "sip", "ssd", "stereo1000"], interp_cfg=dict(), ), )
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/configs/zoomnet/sod_zoomnet.py
configs/zoomnet/sod_zoomnet.py
_base_ = [ "../_base_/common.py", "../_base_/train.py", "../_base_/test.py", ] has_test = True deterministic = True use_custom_worker_init = False model_name = "ZoomNet" train = dict( batch_size=22, num_workers=4, use_amp=True, num_epochs=50, epoch_based=True, lr=0.05, optimizer=dict( mode="sgd", set_to_none=True, group_mode="finetune", cfg=dict( momentum=0.9, weight_decay=5e-4, nesterov=False, ), ), sche_usebatch=True, scheduler=dict( warmup=dict( num_iters=0, initial_coef=0.01, mode="linear", ), mode="f3", cfg=dict( lr_decay=0.9, min_coef=None, ), ), ms=dict( enable=True, extra_scales=[i / 352 for i in [224, 256, 288, 320, 352]], ), ) test = dict( batch_size=22, num_workers=4, show_bar=False, ) datasets = dict( train=dict( dataset_type="msi_sod_tr", shape=dict(h=352, w=352), path=["dutstr"], interp_cfg=dict(), ), test=dict( dataset_type="msi_sod_te", shape=dict(h=352, w=352), path=["pascal-s", "ecssd", "hku-is", "dutste", "dut-omron", "socte"], interp_cfg=dict(), ), )
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
lartpang/ZoomNet
https://github.com/lartpang/ZoomNet/blob/9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8/configs/zoomnet/cod_zoomnet.py
configs/zoomnet/cod_zoomnet.py
_base_ = [ "../_base_/common.py", "../_base_/train.py", "../_base_/test.py", ] has_test = True deterministic = True use_custom_worker_init = False model_name = "ZoomNet" train = dict( batch_size=8, num_workers=4, use_amp=True, num_epochs=40, epoch_based=True, lr=0.05, optimizer=dict( mode="sgd", set_to_none=True, group_mode="finetune", cfg=dict( momentum=0.9, weight_decay=5e-4, nesterov=False, ), ), sche_usebatch=True, scheduler=dict( warmup=dict( num_iters=0, initial_coef=0.01, mode="linear", ), mode="f3", cfg=dict( lr_decay=0.9, min_coef=0.001, ), ), ) test = dict( batch_size=8, num_workers=4, show_bar=False, ) datasets = dict( train=dict( dataset_type="msi_cod_tr", shape=dict(h=384, w=384), path=["cod10k_camo_tr"], interp_cfg=dict(), ), test=dict( dataset_type="msi_cod_te", shape=dict(h=384, w=384), path=["camo_te", "chameleon", "cpd1k_te", "cod10k_te", "nc4k"], interp_cfg=dict(), ), )
python
MIT
9c65e6ca8c5ec2f23c4ad0c0413881f78546d4f8
2026-01-05T07:13:20.623530Z
false
MTG/freesound-python
https://github.com/MTG/freesound-python/blob/73cf6d14f7ce8174d943bdc78ff30f99878a5db8/setup.py
setup.py
from distutils.core import setup setup( name="freesound-python", version="1.1", py_modules=["freesound"], install_requires=["requests<3.0,>2.27"], python_requires=">=3.6", )
python
MIT
73cf6d14f7ce8174d943bdc78ff30f99878a5db8
2026-01-05T07:13:25.198220Z
false
MTG/freesound-python
https://github.com/MTG/freesound-python/blob/73cf6d14f7ce8174d943bdc78ff30f99878a5db8/freesound.py
freesound.py
""" A python client for the Freesound API. Find the API documentation at https://www.freesound.org/docs/api/. Apply for an API key at https://www.freesound.org/api/apply/. The client automatically maps function arguments to http parameters of the API. JSON results are converted to python objects. The main object types (Sound, User, Pack) are augmented with the corresponding API calls. Note that POST resources are not supported. Downloading full quality sounds requires Oauth2 authentication (see https://freesound.org/docs/api/authentication.html). Oauth2 authentication is supported, but you are expected to implement the workflow. """ import re from pathlib import Path from urllib.parse import quote from requests import Session, Request, JSONDecodeError, HTTPError CONTENT_CHUNK_SIZE = 10 * 1024 class URIS: HOST = 'freesound.org' BASE = 'https://' + HOST + '/apiv2' SEARCH = '/search/' SOUND = '/sounds/<sound_id>/' SOUND_ANALYSIS = '/sounds/<sound_id>/analysis/' SIMILAR_SOUNDS = '/sounds/<sound_id>/similar/' COMMENTS = '/sounds/<sound_id>/comments/' DOWNLOAD = '/sounds/<sound_id>/download/' UPLOAD = '/sounds/upload/' DESCRIBE = '/sounds/<sound_id>/describe/' PENDING = '/sounds/pending_uploads/' BOOKMARK = '/sounds/<sound_id>/bookmark/' RATE = '/sounds/<sound_id>/rate/' COMMENT = '/sounds/<sound_id>/comment/' AUTHORIZE = '/oauth2/authorize/' LOGOUT = '/api-auth/logout/' LOGOUT_AUTHORIZE = '/oauth2/logout_and_authorize/' ME = '/me/' ME_BOOKMARK_CATEGORIES = '/me/bookmark_categories/' ME_BOOKMARK_CATEGORY_SOUNDS = '/me/bookmark_categories/<category_id>/sounds/' USER = '/users/<username>/' USER_SOUNDS = '/users/<username>/sounds/' USER_PACKS = '/users/<username>/packs/' PACK = '/packs/<pack_id>/' PACK_SOUNDS = '/packs/<pack_id>/sounds/' PACK_DOWNLOAD = '/packs/<pack_id>/download/' @classmethod def uri(cls, uri, *args): for a in args: uri = re.sub(r'<[\w_]+>', quote(str(a)), uri, 1) return cls.BASE + uri class FreesoundTokenAuth: """Attaches HTTP Token Authentication header to the given Request object.""" def __init__(self, token, auth_type="token"): if auth_type == "oauth": self.header = "Bearer " + token else: self.header = "Token " + token def __call__(self, r): r.headers['Authorization'] = self.header return r class FreesoundClient: """ Start here, create a FreesoundClient and set an authentication token using set_token >>> c = FreesoundClient() >>> c.set_token("<your_api_key>") """ def __init__(self): self.auth = None # should be set later self.session = Session() def get_sound(self, sound_id, **params): """ Get a sound object by id Relevant params: fields https://freesound.org/docs/api/resources_apiv2.html#sound-resources >>> sound = c.get_sound(6) """ uri = URIS.uri(URIS.SOUND, sound_id) return FSRequest.request(uri, params, self, Sound) def search(self, **params): """ Search sounds using a text query and/or filter. Returns an iterable Pager object. The fields parameter allows you to specify the information you want in the results list https://freesound.org/docs/api/resources_apiv2.html#text-search >>> sounds = c.search( >>> query="dubstep", filter="tag:loop", fields="id,name,url" >>> ) >>> for snd in sounds: print snd.name """ if 'fields' not in params: # If no fields parameter is specified, add fields parameter # with default Freesound fields for a query plus the previews # URIs. This will simplify the process of retrieving previews # as it will ensure that the preview URIs are already loaded in # the Sound objects resulting from a search query. params['fields'] = 'id,name,tags,username,license,previews' if 'similar_to' in params: # If similar_to parameter is specified and it is specified as # a vector, then change it to a list and limit float precssion # to avoid too long URL if isinstance(params['similar_to'], (list, tuple)): vector = params['similar_to'] vector_str = ','.join(['{0:.5f}'.format(v) for v in vector]) params['similar_to'] = '[' + vector_str + ']' uri = URIS.uri(URIS.SEARCH) return FSRequest.request(uri, params, self, Pager) def get_user(self, username): """ Get a user object by username https://freesound.org/docs/api/resources_apiv2.html#user-instance >>> u = c.get_user("xserra") """ uri = URIS.uri(URIS.USER, username) return FSRequest.request(uri, {}, self, User) def get_pack(self, pack_id): """ Get a user object by username https://freesound.org/docs/api/resources_apiv2.html#pack-instance >>> p = c.get_pack(3416) """ uri = URIS.uri(URIS.PACK, pack_id) return FSRequest.request(uri, {}, self, Pack) def get_my_bookmark_categories(self, **params): """ Get bookmark categories for the authenticated user. Relevant params: page, page_size https://freesound.org/docs/api/resources_apiv2.html#my-bookmark-categories Requires OAuth2 authentication. >>> c.get_my_bookmark_categories() """ uri = URIS.uri(URIS.ME_BOOKMARK_CATEGORIES) return FSRequest.request(uri, params, self, GenericPager) def get_my_bookmark_category_sounds(self, category_id, **params): """ Get sounds in a bookmark category for the authenticated user. Relevant params: page, page_size, fields https://freesound.org/docs/api/resources_apiv2.html#my-bookmark-category-sounds Requires OAuth2 authentication. >>> c.get_my_bookmark_category_sounds(0) """ uri = URIS.uri(URIS.ME_BOOKMARK_CATEGORY_SOUNDS, category_id) return FSRequest.request(uri, params, self, Pager) def set_token(self, token, auth_type="token"): """ Set your API key or Oauth2 token https://freesound.org/docs/api/authentication.html >>> c.set_token("<your_api_key>") """ self.auth = FreesoundTokenAuth(token, auth_type) class FreesoundObject: """ Base object, automatically populated from parsed json dictionary """ def __init__(self, json_dict, client): self.client = client self.json_dict = json_dict def replace_dashes(d): for k, v in list(d.items()): if "-" in k: d[k.replace("-", "_")] = d[k] del d[k] if isinstance(v, dict): replace_dashes(v) replace_dashes(json_dict) self.__dict__.update(json_dict) for k, v in json_dict.items(): if isinstance(v, dict): self.__dict__[k] = FreesoundObject(v, client) def as_dict(self): return self.json_dict class FreesoundException(Exception): """ Freesound API exception """ def __init__(self, http_code, detail): self.code = http_code self.detail = detail def __str__(self): return '<FreesoundException: code=%s, detail="%s">' % \ (self.code, self.detail) class FSRequest: """ Makes requests to the freesound API. Should not be used directly. """ @staticmethod def request( uri, params, client, wrapper=FreesoundObject, method='GET', ): req = Request(method, uri, params=params, auth=client.auth) prepared = client.session.prepare_request(req) resp = client.session.send(prepared) try: resp.raise_for_status() except HTTPError as e: raise FreesoundException(resp.status_code, resp.reason) from e try: result = resp.json() except JSONDecodeError as e: raise FreesoundException(0, "Couldn't parse response") from e if wrapper: return wrapper(result, client) return result @staticmethod def retrieve(url, client, path, reporthook=None): """ :param reporthook: a callback which is called when a block of data has been downloaded. The callback should have a signature such as def updateProgress(self, count, blockSize, totalSize) For further reference, check the urllib docs. """ resp = client.session.get(url, auth=client.auth) try: resp.raise_for_status() except HTTPError as e: raise FreesoundException(resp.status_code, resp.reason) from e content_length = resp.headers.get("Content-Length", -1) if reporthook is not None: reporthook(0, CONTENT_CHUNK_SIZE, content_length) with open(path, "wb") as fh: for i, chunk in enumerate(resp.iter_content(CONTENT_CHUNK_SIZE), start=1): if reporthook is not None: reporthook(i, CONTENT_CHUNK_SIZE, content_length) fh.write(chunk) class Pager(FreesoundObject): """ Paginates search results. Can be used in for loops to iterate its results array. """ def __getitem__(self, key): return Sound(self.results[key], self.client) def next_page(self): """ Get a Pager with the next results page. """ return FSRequest.request(self.next, {}, self.client, Pager) def previous_page(self): """ Get a Pager with the previous results page. """ return FSRequest.request(self.previous, {}, self.client, Pager) class GenericPager(Pager): """ Paginates results for objects different from Sound. """ def __getitem__(self, key): return FreesoundObject(self.results[key], self.client) class Sound(FreesoundObject): """ Freesound Sound resources >>> sound = c.get_sound(6) """ def retrieve(self, directory, name=None, reporthook=None): """ Download the original sound file (requires Oauth2 authentication). https://freesound.org/docs/api/resources_apiv2.html#download-sound-oauth2-required >>> sound.retrieve("/tmp") :param reporthook: a callback which is called when a block of data has been downloaded. The callback should have a signature such as def updateProgress(self, count, blockSize, totalSize) For further reference, check the urllib docs. """ filename = (name if name else self.name).replace('/', '_') path = Path(directory, filename) uri = URIS.uri(URIS.DOWNLOAD, self.id) return FSRequest.retrieve(uri, self.client, path, reporthook) def retrieve_preview(self, directory, name=None, quality='lq', file_format='mp3'): """ Download the sound preview. If no quality or file format is specified, preview_lq_mp3 is returned. Parameters: directory (str): The directory where the sound preview will be downloaded. name (str, optional): The name of the downloaded sound preview file. If no file extension is specified or if it mismatches the chosen one in file_format, then the file_format is added as a file extension. quality (str, optional): The quality of the audio preview. Available values: 'lq' (low quality) or 'hq' (high quality). file_format (str, optional): The desired file format of the audio preview. Available values: 'mp3','ogg' (only!). >>> sound.retrieve_preview("/tmp") """ preview_type = 'preview_' + quality + '_' + file_format preview_attr = getattr(self.previews, preview_type) try: if name: if name.split('.')[-1] != file_format: file_name = name + '.' + file_format else: file_name = name else: file_name = preview_attr.split("/")[-1] path = Path(directory, file_name) except AttributeError as exc: raise FreesoundException( '-', 'Preview uris are not present in your sound object. Please add' ' them using the fields parameter in your request. See ' ' https://www.freesound.org/docs/api/resources_apiv2.html#response-sound-list.' # noqa ) from exc return FSRequest.retrieve(preview_attr, self.client, path) def get_analysis(self, fields=None): """ Get content-based descriptors. https://freesound.org/docs/api/resources_apiv2.html#sound-analysis Example: >>> analysis_object = sound.get_analysis() >>> mffc_mean = analysis_object.mfcc # <-- access analysis results by using object properties >>> mffc_mean = analysis_object.as_dict()['mfcc'] # <-- Is possible to convert it to a Dictionary """ uri = URIS.uri(URIS.SOUND_ANALYSIS, self.id) return FSRequest.request(uri, {}, self.client, FreesoundObject) def get_analysis_frames(self): """ Get analysis frames. Returns a list of all computed descriptors for all frames as a FreesoundObject. https://freesound.org/docs/api/analysis_docs.html#analysis-docs Example: >>> analysis_frames_object = sound.get_analysis_frames() >>> pitch_by_frames = analysis_frames_object.lowlevel.pich # <-- access analysis results by using object properties >>> pitch_by_frames = analysis_frames_object.as_dict()['lowlevel']['pich'] # <-- Is possible to convert it to a Dictionary """ uri = self.analysis_frames return FSRequest.request(uri, params=None, client=self.client, wrapper=FreesoundObject) def get_similar(self, **params): """ Get similar sounds based on similarity spaces. Relevant params: page, page_size, fields, similarity_space https://freesound.org/docs/api/resources_apiv2.html#similar-sounds >>> s = sound.get_similar() """ uri = URIS.uri(URIS.SIMILAR_SOUNDS, self.id) return FSRequest.request(uri, params, self.client, Pager) def get_comments(self, **params): """ Get user comments. Relevant params: page, page_size https://freesound.org/docs/api/resources_apiv2.html#sound-comments >>> comments = sound.get_comments() """ uri = URIS.uri(URIS.COMMENTS, self.id) return FSRequest.request(uri, params, self.client, GenericPager) def __repr__(self): return f'<Sound: id="{self.id}", name="{self.name}">' class User(FreesoundObject): """ Freesound User resources. >>> u = c.get_user("xserra") """ def get_sounds(self, **params): """ Get user sounds. Relevant params: page, page_size, fields https://freesound.org/docs/api/resources_apiv2.html#user-sounds >>> u.get_sounds() """ uri = URIS.uri(URIS.USER_SOUNDS, self.username) return FSRequest.request(uri, params, self.client, Pager) def get_packs(self, **params): """ Get user packs. Relevant params: page, page_size https://freesound.org/docs/api/resources_apiv2.html#user-packs >>> u.get_packs() """ uri = URIS.uri(URIS.USER_PACKS, self.username) return FSRequest.request(uri, params, self.client, GenericPager) def __repr__(self): return '<User: "%s">' % self.username class Pack(FreesoundObject): """ Freesound Pack resources. >>> p = c.get_pack(3416) """ def get_sounds(self, **params): """ Get pack sounds Relevant params: page, page_size, fields https://freesound.org/docs/api/resources_apiv2.html#pack-sounds >>> sounds = p.get_sounds() """ uri = URIS.uri(URIS.PACK_SOUNDS, self.id) return FSRequest.request(uri, params, self.client, Pager) def __repr__(self): return '<Pack: name="%s">' % self.name
python
MIT
73cf6d14f7ce8174d943bdc78ff30f99878a5db8
2026-01-05T07:13:25.198220Z
false
MTG/freesound-python
https://github.com/MTG/freesound-python/blob/73cf6d14f7ce8174d943bdc78ff30f99878a5db8/examples.py
examples.py
import os import sys import freesound api_key = os.getenv('FREESOUND_API_KEY', None) if api_key is None: print("You need to set your API key as an environment variable") print("named FREESOUND_API_KEY") sys.exit(-1) freesound_client = freesound.FreesoundClient() freesound_client.set_token(api_key) # Get sound info example print("Sound info:") print("-----------") sound = freesound_client.get_sound(6) print("Getting sound:", sound.name) print("Url:", sound.url) print("Description:", sound.description) print("Tags:", " ".join(sound.tags)) print() # Get sound info example specifying some request parameters print("Sound info specifying some request parameters:") print("-----------") sound = freesound_client.get_sound( 6, fields="id,name,username,duration,spectral_centroid") print("Getting sound:", sound.name) print("Username:", sound.username) print("Duration:", str(sound.duration), "(s)") print("Spectral centroid:",str(sound.spectral_centroid), "(Hz)") print() # Get sound analysis example print("Get analysis:") print("-------------") analysis = sound.get_analysis() mfcc = analysis.mfcc print("Mfccs:", mfcc) # you can also get the original json (this applies to any FreesoundObject): print(analysis.as_dict()) print() # Get similar sounds example print("Similar sounds: ") print("---------------") results_pager = sound.get_similar() for similar_sound in results_pager: print("\t-", similar_sound.name, "by", similar_sound.username) print() # Search Example print("Searching for 'violoncello':") print("----------------------------") results_pager = freesound_client.search( query="violoncello", filter="tag:tenuto duration:[1.0 TO 15.0]", sort="rating_desc", fields="id,name,previews,username" ) print("Num results:", results_pager.count) print("\t----- PAGE 1 -----") for sound in results_pager: print("\t-", sound.name, "by", sound.username) print("\t----- PAGE 2 -----") results_pager = results_pager.next_page() for sound in results_pager: print("\t-", sound.name, "by", sound.username) print() # Search all sounds that match some audio descriptor filter print("Filter by audio descriptors:") print("---------------------") results_pager = freesound_client.search( filter="spectral_centroid:[1000 TO 2000] AND pitch:[200 TO 300]", fields="name,username,spectral_centroid,pitch", ) print("Num results:", results_pager.count) for sound in results_pager: print("\t-", sound.name, "by", sound.username, "with spectral centroid of", sound.spectral_centroid, "Hz and pitch of", sound.pitch, "Hz") print() # We can use the search endpoint for a similarity search which also filters results print("Searching for similar sounds and filtering by a descriptor value:") print("---------------") results_pager = freesound_client.search( page_size=10, fields="name,username", similar_to=6, filter="pitch:[110 TO 180]" ) for similar_sound in results_pager: print("\t-", similar_sound.name, "by", similar_sound.username) print() # Find sounds simialar to a target vector extracted from an existing sound which might not be in Freesound # Note that "similarity_space" must match with the similarity space used to extract the target vector print("Searching for sounds similar to a target vector:") print("---------------") target_vector = [0.84835537,-0.06019006,0.35139768,-0.01221892,-0.23172645,-0.03798686,-0.03869437,0.02199453,-0.10143687,-0.03342770,0.05464298,-0.02654354,0.05424048,0.04912830,0.01449411,-0.02995046,0.04584143,0.03731462,0.06914231,-0.00702387,-0.02202889,0.01644059,-0.00153376,0.11042101,0.05432773,0.05736105,-0.03779107,-0.00909068,-0.08996461,-0.04300615,0.05610843,0.02214170,-0.02155820,0.05158299,-0.00717155,-0.04345755,-0.00519616,0.02887811,-0.02205723,0.01658933,0.02485796,-0.06228176,0.03574570,-0.04556302,-0.00497004,0.00300936,-0.01974736,-0.01391953,-0.02898939,0.01041939,-0.02836645,0.00853050,-0.03129587,0.00454572,0.00898315,-0.01371797,-0.00918297,-0.01049032,0.02800968,-0.04248178,0.02648444,-0.01034762,0.02105908,-0.01137279,0.02845560,-0.04284714,0.00797986,0.00973879,-0.00850114,-0.01093731,-0.00629640,-0.01862817,0.00829806,0.01137537,0.02601988,0.03015542,-0.01091145,0.00547907,-0.00426657,0.01001693,0.00793383,0.00082211,-0.02848534,-0.00823537,0.01392606,-0.02012341,-0.00788319,0.02797560,-0.01470957,-0.01917517,-0.01177181,0.00952904,-0.00223396,-0.01586017,-0.00566903,0.01150901,-0.00361810,-0.00257769,-0.01509761,0.00552032] results_pager = freesound_client.search( page_size=10, fields="name,username", similar_to=target_vector, similarity_space="freesound_classic" ) for similar_sound in results_pager: print("\t-", similar_sound.name, "by", similar_sound.username) print() # Search sounds and sort them by distance to a given audio descriptors target print("Sort sounds by distance to audio descriptors target:") print("---------------") results_pager = freesound_client.search( filter="pitch_var:[* TO 20]", sort='pitch_salience:1.0,pitch:440' ) for sound in results_pager: print("\t-", sound.name, "by", sound.username, "distance:", sound.distance_to_target) print() # Getting sounds from a user example print("User sounds:") print("-----------") user = freesound_client.get_user("InspectorJ") print("User name:", user.username) results_pager = user.get_sounds() print("Num results:", results_pager.count) print("\t----- PAGE 1 -----") for sound in results_pager: print("\t-", sound.name, "by", sound.username) print("\t----- PAGE 2 -----") results_pager = results_pager.next_page() for sound in results_pager: print("\t-", sound.name, "by", sound.username) print() # Getting sounds from a user example specifying some request parameters print("User sounds specifying some request parameters:") print("-----------") user = freesound_client.get_user("Headphaze") print("User name:", user.username) results_pager = user.get_sounds( page_size=10, fields="name,username,samplerate,duration" ) print("Num results:", results_pager.count) print("\t----- PAGE 1 -----") for sound in results_pager: print( "\t-", sound.name, "by", sound.username, ) print( ", with sample rate of", sound.samplerate, "Hz and duration of", ) print(sound.duration, "s") print("\t----- PAGE 2 -----") results_pager = results_pager.next_page() for sound in results_pager: print( "\t-", sound.name, "by", sound.username, ) print( ", with sample rate of", sound.samplerate, "Hz and duration of", ) print(sound.duration, "s") print() # Getting sounds from a pack example specifying some request parameters print("Pack sounds specifying some request parameters:") print("-----------") pack = freesound_client.get_pack(3524) print("Pack name:", pack.name) results_pager = pack.get_sounds( page_size=5, fields="id,name,username,duration,spectral_flatness" ) print("Num results:", results_pager.count) print("\t----- PAGE 1 -----") for sound in results_pager: print( "\t-", sound.name, "by", sound.username, ", with duration of", ) print( sound.duration, "s and a spectral flatness of", ) print(sound.spectral_flatness) print("\t----- PAGE 2 -----") results_pager = results_pager.next_page() for sound in results_pager: print( "\t-", sound.name, "by", sound.username, ", with duration of", ) print( sound.duration, "s and a spectral flatness of", ) print(sound.spectral_flatness) print()
python
MIT
73cf6d14f7ce8174d943bdc78ff30f99878a5db8
2026-01-05T07:13:25.198220Z
false
MTG/freesound-python
https://github.com/MTG/freesound-python/blob/73cf6d14f7ce8174d943bdc78ff30f99878a5db8/download_bookmarks_example.py
download_bookmarks_example.py
# Downloads all bookmarks in a user's categories on freesound, # Requires OAUTH key, follow instructions at - # https://freesound.org/docs/api/authentication.html#oauth2-authentication # Make sure you use the actual oauth token and not the authorisation token in # step 2 import os import sys import freesound access_token = os.getenv('FREESOUND_ACCESS_TOKEN', None) if access_token is None: print("You need to set your ACCESS TOKEN as an environment variable") print("named FREESOUND_ACCESS_TOKEN") sys.exit(-1) freesound_client = freesound.FreesoundClient() freesound_client.set_token(access_token, "oauth") path_name = os.path.join(os.getcwd(), "tmp") os.makedirs(path_name, exist_ok=True) bookmarks_results_pager = freesound_client.get_my_bookmark_categories(page_size=100) print("Num categories:", bookmarks_results_pager.count) for bookmark in bookmarks_results_pager: print("\tCategory:", bookmark.name) print("\tNum sounds:", bookmark.num_sounds) sounds_results_pager = freesound_client.get_my_bookmark_category_sounds( bookmark.id, fields="id,name,type", page_size=1 ) while True: for sound in sounds_results_pager: print("\t\tDownloading:", sound.name) # Some sound filenames already end with the type... if sound.name.lower().endswith(sound.type.lower()): filename = sound.name else: filename = f"{sound.name}.{sound.type}" sound.retrieve(path_name, name=filename) if not sounds_results_pager.next: break sounds_results_pager = sounds_results_pager.next_page()
python
MIT
73cf6d14f7ce8174d943bdc78ff30f99878a5db8
2026-01-05T07:13:25.198220Z
false
cwjokaka/bilibili_member_crawler
https://github.com/cwjokaka/bilibili_member_crawler/blob/a4b9cb64b073ec452f1b12b5225539e53996689b/bilibili_member_crawler.py
bilibili_member_crawler.py
import random import requests from distributor import Distributor from variable import USER_AGENTS, THREADS_NUM, FETCH_MID_FROM, FETCH_MID_TO, USE_PROXY_POOL, PROXY_POOL_URL, PROXIES from worker import Worker class BilibiliMemberCrawler: """ B站爬虫入口,用于初始化配置与开启线程 """ @classmethod def start(cls): cls.init() # 开启任务分发线程 Distributor(FETCH_MID_FROM, FETCH_MID_TO + 1).start() # 开启爬虫线程 for i in range(0, THREADS_NUM): Worker(f'Worker-{i}').start() @staticmethod def init(): """ 读取并初始化浏览器agent """ with open('user-agents.txt', 'rb') as uaf: for ua in uaf.readlines(): if ua: USER_AGENTS.append(ua.strip()[:-1]) random.shuffle(USER_AGENTS) # 初始化本地代理池 if USE_PROXY_POOL: try: resp = requests.get(PROXY_POOL_URL) if resp.status_code == 200: proxies = resp.json() for proxy in proxies: PROXIES.append(proxy['proxy']) print(f'初始化本地代理池成功,共{len(PROXIES)}个') except Exception as e: print(f'初始化本地代理池失败!!{e}') if __name__ == '__main__': BilibiliMemberCrawler.start()
python
MIT
a4b9cb64b073ec452f1b12b5225539e53996689b
2026-01-05T07:13:29.310919Z
false
cwjokaka/bilibili_member_crawler
https://github.com/cwjokaka/bilibili_member_crawler/blob/a4b9cb64b073ec452f1b12b5225539e53996689b/res_manager.py
res_manager.py
from queue import Queue class ResManager: def __init__(self, max_size=4096) -> None: super().__init__() self._queue = Queue(max_size) def get_task(self): return self._queue.get() def put_task(self, url): self._queue.put(url) res_manager = ResManager(max_size=4096)
python
MIT
a4b9cb64b073ec452f1b12b5225539e53996689b
2026-01-05T07:13:29.310919Z
false
cwjokaka/bilibili_member_crawler
https://github.com/cwjokaka/bilibili_member_crawler/blob/a4b9cb64b073ec452f1b12b5225539e53996689b/worker.py
worker.py
import time from threading import Thread import MySQLdb import random import requests from requests import ConnectTimeout, ReadTimeout from typing import Optional from requests.exceptions import ProxyError, ChunkedEncodingError from exception.request_exception import RequestException from exception.sql_already_exists_exception import SqlAlreadyExistsException from exception.sql_insert_exception import SqlInsertException from exception.user_not_found_exception import UserNotFoundException from res_manager import res_manager from variable import * class Worker(Thread): def __init__(self, name) -> None: super().__init__(name=name) self.headers = { 'Host': 'api.bilibili.com', 'Origin': PAGE_URL, 'Referer': f'{PAGE_URL}/{random.randint(1, 100000)}', 'User-Agent': random.choice(USER_AGENTS), 'Accept': 'application/json', 'Connection': 'close', 'X-Requested-With': 'XMLHttpRequest' } self.cur_proxy = {'https': f'https://{random.choice(PROXIES)}'} def run(self) -> None: print(f'爬虫线程:{self.name}开始执行...') conn = MySQLdb.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASSWORD, db=DB_NAME, port=DB_PORT, charset='utf8') cur = conn.cursor() while True: mid = res_manager.get_task() while True: self._update_req_info() try: self._crawl(mid, cur) break except RequestException: # 如果是请求上的异常,则重试 # print(f'重新爬取用户:{mid}') continue except SqlInsertException as e: # 数据插入异常, 则插入异常记录 self._insert_failure_record(cur, mid, 0, e.msg) break except UserNotFoundException as e: self._insert_failure_record(cur, mid, 0, e.msg) break except SqlAlreadyExistsException: break except Exception as e: continue conn.commit() time.sleep(random.uniform(FETCH_INTERVAL_MIN, FETCH_INTERVAL_MAX)) def _crawl(self, mid, cur): """ 抓取并持久化用户信息 :param mid: B站用户id :param cur: mysql游标 :return: None """ if self._is_member_exist(cur, mid): print(f'数据库中已存在此用户mid:{mid}, 忽略') return member_info = self._get_member_by_mid(mid) if member_info is None: return mid = member_info['mid'] name = member_info['name'] sign = member_info['sign'].replace("'", "\\\'") rank = member_info['rank'] level = member_info['level'] jointime = member_info['jointime'] moral = member_info['moral'] silence = member_info['silence'] birthday = member_info['birthday'] coins = member_info['coins'] fans_badge = member_info['fans_badge'] vip_type = member_info['vip']['type'] vip_status = member_info['vip']['status'] try: cur.execute(f"INSERT INTO bilibili_member " f"(mid, name, sign, `rank`, `level`, jointime, moral, silence, birthday, coins, fans_badge, vip_type, vip_status) " f"VALUES " f"({mid}, '{name}', '{sign}', {rank}, {level}, {jointime}, {moral}, {silence}, '{birthday}', " f"{coins}, {fans_badge}, {vip_type}, {vip_status})" ) print(f'成功插入用户数据: {mid}, 当前代理:{self.cur_proxy["https"]}') except MySQLdb.ProgrammingError as e: print(f'插入用户: {mid} 数据出错:{e}') raise SqlInsertException(str(e)) except MySQLdb.IntegrityError: print(f'用户: {mid} 数据已存在,不作插入') raise SqlAlreadyExistsException('数据已存在') def _get_member_by_mid(self, mid: int) -> Optional[dict]: """ 根据用户id获取其信息 :param mid: B站用户id :return: 用户详情 or None """ get_params = { 'mid': mid, 'jsonp': 'jsonp' } try: res_json = requests.get(API_MEMBER_INFO, params=get_params, timeout=WAIT_MAX, proxies=self.cur_proxy, headers=self.headers).json() except ConnectTimeout as e: print(f'获取用户id: {mid} 详情失败: 请求接口超时, 当前代理:{self.cur_proxy["https"]}') raise RequestException(str(e)) except ReadTimeout as e: print(f'获取用户id: {mid} 详情失败: 接口读取超时, 当前代理:{self.cur_proxy["https"]}') raise RequestException(str(e)) except ValueError as e: # 解析json失败基本上就是ip被封了 print(f'获取用户id: {mid} 详情失败: 解析json出错, 当前代理:{self.cur_proxy["https"]}') raise RequestException(str(e)) except ProxyError as e: print(f'获取用户id: {mid} 详情失败: 连接代理失败, 当前代理:{self.cur_proxy["https"]}') raise RequestException(str(e)) except requests.ConnectionError as e: # 可以断定就是代理IP地址无效 print(f'获取用户id: {mid} 详情失败: 连接错误, 当前代理:{self.cur_proxy["https"]}') raise RequestException(str(e)) except ChunkedEncodingError as e: print(f'获取用户id: {mid} 详情失败: 远程主机强迫关闭了一个现有的连接, 当前代理:{self.cur_proxy["https"]}') raise RequestException(str(e)) else: if res_json['code'] == -404: print(f'找不到用户mid:{mid}') raise UserNotFoundException(f'找不到用户mid:{mid}') if 'data' in res_json: return res_json['data'] print(f'获取用户id: {mid} 详情失败: data字段不存在!') return def _update_req_info(self): """ 更新请求信息, 主要用于防反爬 :return: """ self.headers.update({ 'Referer': f'{PAGE_URL}/{random.randint(1, 100000)}', 'User-Agent': random.choice(USER_AGENTS), }) self.cur_proxy.update({ 'https': f'https://{random.choice(PROXIES)}', 'http': f'http://{random.choice(PROXIES)}', }) @staticmethod def _insert_failure_record(cur, mid, state, remark): remark = remark.replace("'", "\\\'") try: cur.execute( "INSERT INTO failure_record (mid, remark, state) " f"VALUES ({mid}, '{remark}', '{state}')" ) except MySQLdb.ProgrammingError as e: print(f'插入失败日志: {mid} 数据出错:{e}') except MySQLdb.IntegrityError: print(f'失败日志: {mid} 数据已存在,不作插入') @staticmethod def _is_member_exist(cur, mid): cur.execute( "SELECT COUNT(*) FROM bilibili_member " f"WHERE mid={mid}" ) return cur.fetchone()[0] == 1
python
MIT
a4b9cb64b073ec452f1b12b5225539e53996689b
2026-01-05T07:13:29.310919Z
false
cwjokaka/bilibili_member_crawler
https://github.com/cwjokaka/bilibili_member_crawler/blob/a4b9cb64b073ec452f1b12b5225539e53996689b/variable.py
variable.py
# 用户信息页面URL PAGE_URL = 'http://space.bilibili.com' # 获取用户信息接口 API_MEMBER_INFO = 'http://api.bilibili.com/x/space/acc/info' # MySQL配置 DB_HOST = 'localhost' DB_PORT = 3306 DB_USER = 'root' DB_PASSWORD = '123456' DB_NAME = 'bilibili' # 使用https://github.com/jhao104/proxy_pool的代理池,也可自行部署其服务,然后把PROXY_POOL_URL的地址改成localhost USE_PROXY_POOL = True # https://github.com/jhao104/proxy_pool的测试服务器地址 PROXY_POOL_URL = 'http://118.24.52.95/get_all' # 代理设置(需要自行添加), 如果 PROXIES = \ ["211.152.33.24:59523", "211.152.33.24:59523", "103.35.64.12:3128", "117.127.16.206:8080", "51.77.162.148:3128" ,"119.41.236.180:8010", "124.42.68.152:90", "94.177.246.142:8080", "51.15.117.119:8080", "66.7.113.39:3128" ,"94.247.62.184:8080", "123.117.70.143:8060", "117.141.155.241:53281", "94.177.214.178:8080", "111.231.90.122:8888" , "210.22.5.117:3128", "51.79.57.158:3128", "58.17.125.215:53281" ] # 浏览器agent列表, 初始化时会加附加上user-agents.txt里的内容 USER_AGENTS = [ 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:67.0) Gecko/20100101 Firefox/67.0' ] # 抓取等待最大时间(s) WAIT_MAX = 2 # 开启抓取线程的数量 THREADS_NUM = 128 # 每条线程抓取的间隔范围(s) FETCH_INTERVAL_MIN = 0.01 FETCH_INTERVAL_MAX = 0.05 # 想要抓取的用户id范围 FETCH_MID_FROM = 1 FETCH_MID_TO = 5000
python
MIT
a4b9cb64b073ec452f1b12b5225539e53996689b
2026-01-05T07:13:29.310919Z
false
cwjokaka/bilibili_member_crawler
https://github.com/cwjokaka/bilibili_member_crawler/blob/a4b9cb64b073ec452f1b12b5225539e53996689b/distributor.py
distributor.py
from threading import Thread from res_manager import res_manager class Distributor(Thread): """ 任务分发线程,负责下发任务(用户mid)到队列 """ def __init__(self, start: int, end: int): super().__init__() self._start = start self._end = end def run(self) -> None: print('Distributor开始执行...') for mid in range(self._start, self._end): res_manager.put_task(mid) print('Distributor执行完毕')
python
MIT
a4b9cb64b073ec452f1b12b5225539e53996689b
2026-01-05T07:13:29.310919Z
false
cwjokaka/bilibili_member_crawler
https://github.com/cwjokaka/bilibili_member_crawler/blob/a4b9cb64b073ec452f1b12b5225539e53996689b/exception/bilibili_exception.py
exception/bilibili_exception.py
class BilibiliException(Exception): def __init__(self, msg) -> None: self.msg = msg def __str__(self): return self.msg
python
MIT
a4b9cb64b073ec452f1b12b5225539e53996689b
2026-01-05T07:13:29.310919Z
false
cwjokaka/bilibili_member_crawler
https://github.com/cwjokaka/bilibili_member_crawler/blob/a4b9cb64b073ec452f1b12b5225539e53996689b/exception/request_exception.py
exception/request_exception.py
from exception.bilibili_exception import BilibiliException class RequestException(BilibiliException): def __init__(self, msg) -> None: super().__init__(msg)
python
MIT
a4b9cb64b073ec452f1b12b5225539e53996689b
2026-01-05T07:13:29.310919Z
false