index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
23,310 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_reply.py | 434,436 | 344,445 | de_json | ReplyParameters | 437,445 | 436,445 | class ReplyParameters(TelegramObject):
"""
Describes reply parameters for the message that is being sent.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`message_id` is equal.
.. versionadded:: 20.8
Args:
messa... | class ReplyParameters(TelegramObject):
"""
Describes reply parameters for the message that is being sent.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`message_id` is equal.
.. versionadded:: 20.8
Args:
messa... | data = cls._parse_data(data)
if data is None:
return None
data["quote_entities"] = tuple(MessageEntity.de_list(data.get("quote_entities"), bot))
return super().de_json(data=data, bot=bot)
| """See :obj:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
if data is None:
return None
data["quote_entities"] = tuple(MessageEntity.de_list(data.get("quote_entities"), bot))
return super().de_json(data=data, bot=bot)
| 16 | 1,368 | 82 | 1,450 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,311 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_reply.py | 331,333 | 268,344 | de_json | TextQuote | 334,344 | 333,344 | class TextQuote(TelegramObject):
"""
This object contains information about the quoted part of a message that is replied to
by the given message.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`text` and :attr:`position` are... | class TextQuote(TelegramObject):
"""
This object contains information about the quoted part of a message that is replied to
by the given message.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`text` and :attr:`position` are... | data = cls._parse_data(data)
if data is None:
return None
data["entities"] = tuple(MessageEntity.de_list(data.get("entities"), bot))
return super().de_json(data=data, bot=bot)
| """See :obj:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
if data is None:
return None
data["entities"] = tuple(MessageEntity.de_list(data.get("entities"), bot))
return super().de_json(data=data, bot=bot)
| 16 | 748 | 82 | 830 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,313 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_story.py | 73,75 | 31,83 | de_json | Story | 76,83 | 75,83 | class Story(TelegramObject):
"""
This object represents a story.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`chat` and :attr:`id` are equal.
.. versionadded:: 20.5
.. versionchanged:: 21.0
Added attributes ... | class Story(TelegramObject):
"""
This object represents a story.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`chat` and :attr:`id` are equal.
.. versionadded:: 20.5
.. versionchanged:: 21.0
Added attributes ... | data = cls._parse_data(data)
if not data:
return None
data["chat"] = Chat.de_json(data.get("chat", {}), bot)
return super().de_json(data=data, bot=bot)
| """See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
if not data:
return None
data["chat"] = Chat.de_json(data.get("chat", {}), bot)
return super().de_json(data=data, bot=bot)
| 16 | 420 | 72 | 492 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,316 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_userprofilephotos.py | 72,74 | 30,83 | de_json | UserProfilePhotos | 75,83 | 74,83 | class UserProfilePhotos(TelegramObject):
"""This object represents a user's profile pictures.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`total_count` and :attr:`photos` are equal.
Args:
total_count (:obj:`int`): To... | class UserProfilePhotos(TelegramObject):
"""This object represents a user's profile pictures.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`total_count` and :attr:`photos` are equal.
Args:
total_count (:obj:`int`): To... | data = cls._parse_data(data)
if not data:
return None
data["photos"] = [PhotoSize.de_list(photo, bot) for photo in data["photos"]]
return super().de_json(data=data, bot=bot)
| """See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
if not data:
return None
data["photos"] = [PhotoSize.de_list(photo, bot) for photo in data["photos"]]
return super().de_json(data=data, bot=bot)
| 19 | 477 | 80 | 557 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,317 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_utils/argumentparsing.py | 46,49 | 1,62 | parse_lpo_and_dwpp | 52,62 | 49,62 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | if disable_web_page_preview and link_preview_options:
raise ValueError(
"Parameters `disable_web_page_preview` and `link_preview_options` are mutually "
"exclusive."
)
if disable_web_page_preview is not None:
link_preview_options = LinkPreviewOptions(is_disabled=... | """Wrapper around warn_about_deprecated_arg_return_new_arg. Takes care of converting
disable_web_page_preview to LinkPreviewOptions.
"""
if disable_web_page_preview and link_preview_options:
raise ValueError(
"Parameters `disable_web_page_preview` and `link_preview_options` are mutua... | 25 | 579 | 124 | 703 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | |
23,319 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_utils/defaultvalue.py | 99,101 | 36,122 | get_value | DefaultValue | 101,102 | 101,102 | class DefaultValue(Generic[DVType]):
"""Wrapper for immutable default arguments that allows to check, if the default value was set
explicitly. Usage::
default_one = DefaultValue(1)
def f(arg=default_one):
if arg is default_one:
print('`arg` is the default')
... | class DefaultValue(Generic[DVType]):
"""Wrapper for immutable default arguments that allows to check, if the default value was set
explicitly. Usage::
default_one = DefaultValue(1)
def f(arg=default_one):
if arg is default_one:
print('`arg` is the default')
... | def get_value(obj: "DefaultValue[OT]") -> OT: ...
| def get_value(obj: "DefaultValue[OT]") -> OT: ...
| 6 | 648 | 23 | 671 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,320 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_utils/enum.py | 35,36 | 1,77 | get_member | 39,48 | 36,48 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | try:
return enum_cls(value)
except ValueError:
return default
# Python 3.11 and above has a different output for mixin classes for IntEnum, StrEnum and IntFlag
# see https://docs.python.org/3.11/library/enum.html#notes. We want e.g. str(StrEnumTest.FOO) to
# return "foo" instead of "StrEnumTes... | """Tries to call ``enum_cls(value)`` to convert the value into an enumeration member.
If that fails, the ``default`` is returned.
"""
try:
return enum_cls(value)
except ValueError:
return default
# Python 3.11 and above has a different output for mixin classes for IntEnum, StrEnum ... | 45 | 747 | 128 | 875 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | |
23,321 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_utils/files.py | 89,96 | 1,151 | parse_file_input | 129,151 | 96,151 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | # Importing on file-level yields cyclic Import Errors
from telegram import InputFile # pylint: disable=import-outside-toplevel
if isinstance(file_input, str) and file_input.startswith("file://"):
if not local_mode:
raise ValueError("Specified file input is a file URI, but local mode is... | """
Parses input for sending files:
* For string input, if the input is an absolute path of a local file:
* if ``local_mode`` is ``True``, adds the ``file://`` prefix. If the input is a relative
path of a local file, computes the absolute path and adds the ``file://`` prefix.
* if ... | 85 | 1,429 | 326 | 1,755 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | |
23,322 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_utils/logging.py | 30,31 | 1,51 | get_logger | 45,51 | 31,51 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | parts = file_name.split("_")
if parts[1].startswith("utils") and class_name is None:
name = parts[0].rstrip(".")
else:
name = f"{parts[0]}{class_name or parts[1].capitalize()}"
return logging.getLogger(name)
| """Returns a logger with an appropriate name.
Use as follows::
logger = get_logger(__name__)
If for example `__name__` is `telegram.ext._updater`, the logger will be named
`telegram.ext.Updater`. If `class_name` is passed, this will result in
`telegram.ext.<class_name>`. Useful e.g. for Ca... | 20 | 514 | 89 | 603 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | |
23,323 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_utils/markup.py | 33,34 | 1,50 | check_keyboard_type | 37,50 | 34,50 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | # string and bytes may actually be used for ReplyKeyboardMarkup in which case each button
# would contain a single character. But that use case should be discouraged and we don't
# allow it here.
if not isinstance(keyboard, Sequence) or isinstance(keyboard, (str, bytes)):
return False
for r... | """Checks if the keyboard provided is of the correct type - A sequence of sequences.
Implicitly tested in the init-tests of `{Inline, Reply}KeyboardMarkup`
"""
# string and bytes may actually be used for ReplyKeyboardMarkup in which case each button
# would contain a single character. But that use c... | 74 | 440 | 165 | 605 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | |
23,324 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_utils/repr.py | 29,30 | 1,46 | build_repr_with_selected_attrs | 37,44 | 30,44 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | return (
f"{obj.__class__.__name__}"
# square brackets emphasize that an object cannot be instantiated with these params
f"[{', '.join(_stringify(name, value) for name, value in kwargs.items())}]"
)
| """Create ``__repr__`` string in the style ``Classname[arg1=1, arg2=2]``.
The square brackets emphasize the fact that an object cannot be instantiated
from this string.
Attributes that are to be used in the representation, are passed as kwargs.
"""
return (
f"{obj.__class__.__name__}"
... | 25 | 475 | 76 | 551 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | |
23,325 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_utils/strings.py | 28,29 | 1,39 | to_camel_case | 37,39 | 29,39 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | components = snake_str.split("_")
return components[0] + "".join(x.title() for x in components[1:])
| """Converts a snake_case string to camelCase.
Args:
snake_str (:obj:`str`): The string to convert.
Returns:
:obj:`str`: The converted string.
"""
components = snake_str.split("_")
return components[0] + "".join(x.title() for x in components[1:])
| 11 | 403 | 39 | 442 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | |
23,326 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_utils/warnings.py | 34,35 | 1,48 | warn | 47,48 | 35,48 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | warnings.warn(message, category=category, stacklevel=stacklevel + 1)
| """
Helper function used as a shortcut for warning with default values.
.. versionadded:: 20.0
Args:
message (:obj:`str`): Specify the warnings message to pass to ``warnings.warn()``.
category (:obj:`Type[Warning]`, optional): Specify the Warning class to pass to
``warnings... | 5 | 563 | 21 | 584 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | |
23,327 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_utils/warnings_transition.py | 51,60 | 1,109 | warn_about_deprecated_arg_return_new_arg | 69,93 | 60,93 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | if deprecated_arg and new_arg and deprecated_arg != new_arg:
base_message = build_deprecation_warning_message(
deprecated_name=deprecated_arg_name,
new_name=new_arg_name,
object_type="parameter",
bot_api_version=bot_api_version,
)
raise ValueEr... | """A helper function for the transition in API when argument is renamed.
Checks the `deprecated_arg` and `new_arg` objects; warns if non-None `deprecated_arg` object
was passed. Returns `new_arg` object (either the one originally passed by the user or the one
that user passed as `deprecated_arg`).
... | 51 | 933 | 248 | 1,181 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | |
23,328 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_version.py | 36,37 | 25,53 | _rl_shorthand | Version | 37,43 | 37,43 | class Version(NamedTuple):
"""Copies the behavior of sys.version_info.
serial is always 0 for stable releases.
"""
major: int
minor: int
micro: int
releaselevel: str # Literal['alpha', 'beta', 'candidate', 'final']
serial: int
def _rl_shorthand(self) -> str:
FILL_FUNC_BODY def ... | class Version(NamedTuple):
"""Copies the behavior of sys.version_info.
serial is always 0 for stable releases.
"""
major: int
minor: int
micro: int
releaselevel: str # Literal['alpha', 'beta', 'candidate', 'final']
serial: int
def _rl_shorthand(self) -> str:
FILL_FUNC_BODY def ... | return {
"alpha": "a",
"beta": "b",
"candidate": "rc",
}[self.releaselevel]
| return {
"alpha": "a",
"beta": "b",
"candidate": "rc",
}[self.releaselevel]
| 9 | 202 | 45 | 247 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,329 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_videochat.py | 126,130 | 87,140 | de_json | VideoChatParticipantsInvited | 131,140 | 130,140 | class VideoChatParticipantsInvited(TelegramObject):
"""
This object represents a service message about new members invited to a video chat.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal, if their :attr:`users` are equal.
.. versionadded::... | class VideoChatParticipantsInvited(TelegramObject):
"""
This object represents a service message about new members invited to a video chat.
Objects of this class are comparable in terms of equality.
Two objects of this class are considered equal, if their :attr:`users` are equal.
.. versionadded::... | data = cls._parse_data(data)
if not data:
return None
data["users"] = User.de_list(data.get("users", []), bot)
return super().de_json(data=data, bot=bot)
| """See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
if not data:
return None
data["users"] = User.de_list(data.get("users", []), bot)
return super().de_json(data=data, bot=bot)
| 16 | 423 | 76 | 499 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,330 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_videochat.py | 179,181 | 140,193 | de_json | VideoChatScheduled | 182,193 | 181,193 | class VideoChatScheduled(TelegramObject):
"""This object represents a service message about a video chat scheduled in the chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`start_date` are equal.
.. versionchanged:: 20.0
... | class VideoChatScheduled(TelegramObject):
"""This object represents a service message about a video chat scheduled in the chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`start_date` are equal.
.. versionchanged:: 20.0
... | data = cls._parse_data(data)
if not data:
return None
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["start_date"] = from_timestamp(data["start_date"], tzinfo=loc_tzinfo)
return super().de_json(... | """See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
if not data:
return None
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["start_date"] = from_timestamp(data["start_... | 30 | 423 | 116 | 539 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,331 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/_webhookinfo.py | 164,166 | 32,181 | de_json | WebhookInfo | 167,181 | 166,181 | class WebhookInfo(TelegramObject):
"""This object represents a Telegram WebhookInfo.
Contains information about the current status of a webhook.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`url`, :attr:`has_custom_certificat... | class WebhookInfo(TelegramObject):
"""This object represents a Telegram WebhookInfo.
Contains information about the current status of a webhook.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`url`, :attr:`has_custom_certificat... | data = cls._parse_data(data)
if not data:
return None
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["last_error_date"] = from_timestamp(data.get("last_error_date"), tzinfo=loc_tzinfo)
data["last... | """See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
if not data:
return None
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["last_error_date"] = from_timestamp(data.ge... | 36 | 1,665 | 171 | 1,836 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,336 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_baseupdateprocessor.py | 138,144 | 28,156 | process_update | BaseUpdateProcessor | 152,156 | 144,156 | class BaseUpdateProcessor(AsyncContextManager["BaseUpdateProcessor"], ABC):
"""An abstract base class for update processors. You can use this class to implement
your own update processor.
Instances of this class can be used as asyncio context managers, where
.. code:: python
async with proces... | class BaseUpdateProcessor(AsyncContextManager["BaseUpdateProcessor"], ABC):
"""An abstract base class for update processors. You can use this class to implement
your own update processor.
Instances of this class can be used as asyncio context managers, where
.. code:: python
async with proces... | async with self._semaphore:
await self.do_process_update(update, coroutine)
| """Calls :meth:`do_process_update` with a semaphore to limit the number of concurrent
updates.
Args:
update (:obj:`object`): The update to be processed.
coroutine (:term:`Awaitable`): The coroutine that will be awaited to process the
update.
"""
... | 6 | 1,113 | 33 | 1,146 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,337 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_baseupdateprocessor.py | 166,171 | 156,185 | do_process_update | SimpleUpdateProcessor | 178,180 | 171,180 | class SimpleUpdateProcessor(BaseUpdateProcessor):
"""Instance of :class:`telegram.ext.BaseUpdateProcessor` that immediately awaits the
coroutine, i.e. does not apply any additional processing. This is used by default when
:attr:`telegram.ext.ApplicationBuilder.concurrent_updates` is :obj:`int`.
.. vers... | class SimpleUpdateProcessor(BaseUpdateProcessor):
"""Instance of :class:`telegram.ext.BaseUpdateProcessor` that immediately awaits the
coroutine, i.e. does not apply any additional processing. This is used by default when
:attr:`telegram.ext.ApplicationBuilder.concurrent_updates` is :obj:`int`.
.. vers... | await coroutine
| """Immediately awaits the coroutine, i.e. does not apply any additional processing.
Args:
update (:obj:`object`): The update to be processed.
coroutine (:term:`Awaitable`): The coroutine that will be awaited to process the
update.
"""
await corout... | 2 | 279 | 9 | 288 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,340 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_callbackdatacache.py | 94,95 | 81,105 | update_access_time | _KeyboardData | 96,98 | 95,98 | class _KeyboardData:
__slots__ = ("access_time", "button_data", "keyboard_uuid")
def __init__(
self,
keyboard_uuid: str,
access_time: Optional[float] = None,
button_data: Optional[Dict[str, object]] = None,
):
self.keyboard_uuid = keyboard_uuid
self.button_da... | class _KeyboardData:
__slots__ = ("access_time", "button_data", "keyboard_uuid")
def __init__(
self,
keyboard_uuid: str,
access_time: Optional[float] = None,
button_data: Optional[Dict[str, object]] = None,
):
self.keyboard_uuid = keyboard_uuid
self.button_da... | self.access_time = time.time()
| """Updates the access time with the current time."""
self.access_time = time.time()
| 3 | 242 | 15 | 257 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published... |
23,344 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_handlers/basehandler.py | 134,141 | 35,175 | handle_update | BaseHandler | 156,159 | 141,159 | class BaseHandler(Generic[UT, CCT], ABC):
"""The base class for all update handlers. Create custom handlers by inheriting from it.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See its docs for more... | class BaseHandler(Generic[UT, CCT], ABC):
"""The base class for all update handlers. Create custom handlers by inheriting from it.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See its docs for more... | self.collect_additional_context(context, update, application, check_result)
return await self.callback(update, context)
| """
This method is called if it was determined that an update should indeed
be handled by this instance. Calls :attr:`callback` along with its respectful
arguments. To work with the :class:`telegram.ext.ConversationHandler`, this method
returns the value returned from :attr:`call... | 8 | 1,576 | 37 | 1,613 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,345 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_handlers/businessconnectionhandler.py | 79,80 | 32,96 | check_update | BusinessConnectionHandler | 89,96 | 80,96 | class BusinessConnectionHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram
:attr:`Business Connections <telegram.Update.business_connection>`.
.. versionadded:: 21.1
Args:
callback (:term:`coroutine function`): The callback function for this handler. Will be
cal... | class BusinessConnectionHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram
:attr:`Business Connections <telegram.Update.business_connection>`.
.. versionadded:: 21.1
Args:
callback (:term:`coroutine function`): The callback function for this handler. Will be
cal... | if isinstance(update, Update) and update.business_connection:
if not self._user_ids and not self._usernames:
return True
if update.business_connection.user.id in self._user_ids:
return True
return update.business_connection.user.username in sel... | """Determines whether an update should be passed to this handler's :attr:`callback`.
Args:
update (:class:`telegram.Update` | :obj:`object`): Incoming update.
Returns:
:obj:`bool`
"""
if isinstance(update, Update) and update.business_connection:
... | 25 | 622 | 90 | 712 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,346 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_handlers/businessmessagesdeletedhandler.py | 79,80 | 32,96 | check_update | BusinessMessagesDeletedHandler | 89,96 | 80,96 | class BusinessMessagesDeletedHandler(BaseHandler[Update, CCT]):
"""Handler class to handle
:attr:`deleted Telegram Business messages <telegram.Update.deleted_business_messages>`.
.. versionadded:: 21.1
Args:
callback (:term:`coroutine function`): The callback function for this handler. Will be... | class BusinessMessagesDeletedHandler(BaseHandler[Update, CCT]):
"""Handler class to handle
:attr:`deleted Telegram Business messages <telegram.Update.deleted_business_messages>`.
.. versionadded:: 21.1
Args:
callback (:term:`coroutine function`): The callback function for this handler. Will be... | if isinstance(update, Update) and update.deleted_business_messages:
if not self._chat_ids and not self._usernames:
return True
if update.deleted_business_messages.chat.id in self._chat_ids:
return True
return update.deleted_business_messages.ch... | """Determines whether an update should be passed to this handler's :attr:`callback`.
Args:
update (:class:`telegram.Update` | :obj:`object`): Incoming update.
Returns:
:obj:`bool`
"""
if isinstance(update, Update) and update.deleted_business_messages:
... | 25 | 628 | 99 | 727 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,347 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_handlers/chatjoinrequesthandler.py | 95,96 | 31,112 | check_update | ChatJoinRequestHandler | 105,112 | 96,112 | class ChatJoinRequestHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram updates that contain
:attr:`telegram.Update.chat_join_request`.
Note:
If neither of :paramref:`username` and the :paramref:`chat_id` are passed, this handler
accepts *any* join request. Otherwise, th... | class ChatJoinRequestHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram updates that contain
:attr:`telegram.Update.chat_join_request`.
Note:
If neither of :paramref:`username` and the :paramref:`chat_id` are passed, this handler
accepts *any* join request. Otherwise, th... | if isinstance(update, Update) and update.chat_join_request:
if not self._chat_ids and not self._usernames:
return True
if update.chat_join_request.chat.id in self._chat_ids:
return True
return update.chat_join_request.from_user.username in self... | """Determines whether an update should be passed to this handler's :attr:`callback`.
Args:
update (:class:`telegram.Update` | :obj:`object`): Incoming update.
Returns:
:obj:`bool`
"""
if isinstance(update, Update) and update.chat_join_request:
... | 25 | 816 | 98 | 914 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,348 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_handlers/chatmemberhandler.py | 92,93 | 31,111 | check_update | ChatMemberHandler | 102,111 | 93,111 | class ChatMemberHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram updates that contain a chat member update.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See its docs for more ... | class ChatMemberHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram updates that contain a chat member update.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See its docs for more ... | if isinstance(update, Update):
if not (update.my_chat_member or update.chat_member):
return False
if self.chat_member_types == self.ANY_CHAT_MEMBER:
return True
if self.chat_member_types == self.CHAT_MEMBER:
return bool(update.c... | """Determines whether an update should be passed to this handler's :attr:`callback`.
Args:
update (:class:`telegram.Update` | :obj:`object`): Incoming update.
Returns:
:obj:`bool`
"""
if isinstance(update, Update):
if not (update.my_chat_mem... | 26 | 950 | 115 | 1,065 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,350 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_handlers/messagehandler.py | 88,89 | 35,112 | check_update | MessageHandler | 98,102 | 89,102 | class MessageHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram messages. They might contain text, media or status
updates.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See ... | class MessageHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram messages. They might contain text, media or status
updates.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See ... | if isinstance(update, Update):
return self.filters.check_update(update) or False
return None
| """Determines whether an update should be passed to this handler's :attr:`callback`.
Args:
update (:class:`telegram.Update` | :obj:`object`): Incoming update.
Returns:
:obj:`bool`
"""
if isinstance(update, Update):
return self.filters.check_... | 9 | 912 | 35 | 947 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,351 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_handlers/pollanswerhandler.py | 61,62 | 27,72 | check_update | PollAnswerHandler | 71,72 | 62,72 | class PollAnswerHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram updates that contain a
:attr:`poll answer <telegram.Update.poll_answer>`.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.Callb... | class PollAnswerHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram updates that contain a
:attr:`poll answer <telegram.Update.poll_answer>`.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.Callb... | return isinstance(update, Update) and bool(update.poll_answer)
| """Determines whether an update should be passed to this handler's :attr:`callback`.
Args:
update (:class:`telegram.Update` | :obj:`object`): Incoming update.
Returns:
:obj:`bool`
"""
return isinstance(update, Update) and bool(update.poll_answer)
| 5 | 480 | 21 | 501 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,352 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_handlers/pollhandler.py | 61,62 | 27,72 | check_update | PollHandler | 71,72 | 62,72 | class PollHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram updates that contain a
:attr:`poll <telegram.Update.poll>`.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See its... | class PollHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram updates that contain a
:attr:`poll <telegram.Update.poll>`.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See its... | return isinstance(update, Update) and bool(update.poll)
| """Determines whether an update should be passed to this handler's :attr:`callback`.
Args:
update (:class:`telegram.Update` | :obj:`object`): Incoming update.
Returns:
:obj:`bool`
"""
return isinstance(update, Update) and bool(update.poll)
| 5 | 475 | 19 | 494 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,353 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_handlers/precheckoutqueryhandler.py | 85,86 | 34,103 | check_update | PreCheckoutQueryHandler | 95,103 | 86,103 | class PreCheckoutQueryHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram :attr:`telegram.Update.pre_checkout_query`.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See its docs fo... | class PreCheckoutQueryHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram :attr:`telegram.Update.pre_checkout_query`.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See its docs fo... | if isinstance(update, Update) and update.pre_checkout_query:
invoice_payload = update.pre_checkout_query.invoice_payload
if self.pattern:
if self.pattern.match(invoice_payload):
return True
else:
return True
return F... | """Determines whether an update should be passed to this handler's :attr:`callback`.
Args:
update (:class:`telegram.Update` | :obj:`object`): Incoming update.
Returns:
:obj:`bool`
"""
if isinstance(update, Update) and update.pre_checkout_query:
... | 19 | 714 | 88 | 802 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,354 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_handlers/prefixhandler.py | 146,149 | 36,185 | check_update | PrefixHandler | 158,171 | 149,171 | class PrefixHandler(BaseHandler[Update, CCT]):
"""Handler class to handle custom prefix commands.
This is an intermediate handler between :class:`MessageHandler` and :class:`CommandHandler`.
It supports configurable commands with the same options as :class:`CommandHandler`. It will
respond to every com... | class PrefixHandler(BaseHandler[Update, CCT]):
"""Handler class to handle custom prefix commands.
This is an intermediate handler between :class:`MessageHandler` and :class:`CommandHandler`.
It supports configurable commands with the same options as :class:`CommandHandler`. It will
respond to every com... | if isinstance(update, Update) and update.effective_message:
message = update.effective_message
if message.text:
text_list = message.text.split()
if text_list[0].lower() not in self.commands:
return None
filter_result = ... | """Determines whether an update should be passed to this handler's :attr:`callback`.
Args:
update (:class:`telegram.Update` | :obj:`object`): Incoming update.
Returns:
:obj:`list`: The list of args for the handler.
"""
if isinstance(update, Update) and ... | 32 | 1,713 | 127 | 1,840 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,355 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_handlers/shippingqueryhandler.py | 60,61 | 27,71 | check_update | ShippingQueryHandler | 70,71 | 61,71 | class ShippingQueryHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram :attr:`telegram.Update.shipping_query`.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See its docs for more ... | class ShippingQueryHandler(BaseHandler[Update, CCT]):
"""Handler class to handle Telegram :attr:`telegram.Update.shipping_query`.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See its docs for more ... | return isinstance(update, Update) and bool(update.shipping_query)
| """Determines whether an update should be passed to this handler's :attr:`callback`.
Args:
update (:class:`telegram.Update` | :obj:`object`): Incoming update.
Returns:
:obj:`bool`
"""
return isinstance(update, Update) and bool(update.shipping_query)
| 5 | 468 | 21 | 489 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,356 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_handlers/stringcommandhandler.py | 98,105 | 32,109 | collect_additional_context | StringCommandHandler | 108,109 | 105,109 | class StringCommandHandler(BaseHandler[str, CCT]):
"""Handler class to handle string commands. Commands are string updates that start with
``/``. The handler will add a :obj:`list` to the
:class:`CallbackContext` named :attr:`CallbackContext.args`. It will contain a list of strings,
which is the text fo... | class StringCommandHandler(BaseHandler[str, CCT]):
"""Handler class to handle string commands. Commands are string updates that start with
``/``. The handler will add a :obj:`list` to the
:class:`CallbackContext` named :attr:`CallbackContext.args`. It will contain a list of strings,
which is the text fo... | context.args = check_result
| """Add text after the command to :attr:`CallbackContext.args` as list, split on single
whitespaces.
"""
context.args = check_result
| 3 | 859 | 10 | 869 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,357 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_handlers/typehandler.py | 83,84 | 32,96 | check_update | TypeHandler | 93,96 | 84,96 | class TypeHandler(BaseHandler[UT, CCT]):
"""Handler class to handle updates of custom types.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See its docs for more info.
Args:
type (:exter... | class TypeHandler(BaseHandler[UT, CCT]):
"""Handler class to handle updates of custom types.
Warning:
When setting :paramref:`block` to :obj:`False`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See its docs for more info.
Args:
type (:exter... | if not self.strict:
return isinstance(update, self.type)
return type(update) is self.type # pylint: disable=unidiomatic-typecheck
| """Determines whether an update should be passed to this handler's :attr:`callback`.
Args:
update (:obj:`object`): Incoming update.
Returns:
:obj:`bool`
"""
if not self.strict:
return isinstance(update, self.type)
return type(update)... | 13 | 721 | 48 | 769 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,362 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_picklepersistence.py | 89,90 | 70,104 | persistent_id | _BotPickler | 93,104 | 90,104 | class _BotPickler(pickle.Pickler):
__slots__ = ("_bot",)
def __init__(self, bot: Bot, *args: Any, **kwargs: Any):
self._bot = bot
super().__init__(*args, **kwargs)
def reducer_override(
self, obj: TelegramObj
) -> Tuple[Callable, Tuple[Type[TelegramObj], dict]]:
"""
... | class _BotPickler(pickle.Pickler):
__slots__ = ("_bot",)
def __init__(self, bot: Bot, *args: Any, **kwargs: Any):
self._bot = bot
super().__init__(*args, **kwargs)
def reducer_override(
self, obj: TelegramObj
) -> Tuple[Callable, Tuple[Type[TelegramObj], dict]]:
"""
... | if obj is self._bot:
return _REPLACED_KNOWN_BOT
if isinstance(obj, Bot):
warn(
"Unknown bot instance found. Will be replaced by `None` during unpickling",
stacklevel=2,
)
return _REPLACED_UNKNOWN_BOT
return None # p... | """Used to 'mark' the Bot, so it can be replaced later. See
https://docs.python.org/3/library/pickle.html#pickle.Pickler.persistent_id for more info
"""
if obj is self._bot:
return _REPLACED_KNOWN_BOT
if isinstance(obj, Bot):
warn(
"Unknown... | 31 | 270 | 108 | 378 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,363 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_picklepersistence.py | 111,112 | 104,120 | persistent_load | _BotUnpickler | 113,120 | 112,120 | class _BotUnpickler(pickle.Unpickler):
__slots__ = ("_bot",)
def __init__(self, bot: Bot, *args: Any, **kwargs: Any):
self._bot = bot
super().__init__(*args, **kwargs)
def persistent_load(self, pid: str) -> Optional[Bot]:
FILL_FUNC_BODY | class _BotUnpickler(pickle.Unpickler):
__slots__ = ("_bot",)
def __init__(self, bot: Bot, *args: Any, **kwargs: Any):
self._bot = bot
super().__init__(*args, **kwargs)
def persistent_load(self, pid: str) -> Optional[Bot]:
"""Replaces the bot with the current bot if known, else it i... | if pid == _REPLACED_KNOWN_BOT:
return self._bot
if pid == _REPLACED_UNKNOWN_BOT:
return None
raise pickle.UnpicklingError("Found unknown persistent id when unpickling!")
| """Replaces the bot with the current bot if known, else it is replaced by :obj:`None`."""
if pid == _REPLACED_KNOWN_BOT:
return self._bot
if pid == _REPLACED_UNKNOWN_BOT:
return None
raise pickle.UnpicklingError("Found unknown persistent id when unpickling!")
| 19 | 129 | 79 | 208 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,365 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_utils/_update_parsing.py | 42,43 | 1,51 | parse_username | 46,51 | 43,51 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | if username is None:
return frozenset()
if isinstance(username, str):
return frozenset({username[1:] if username.startswith("@") else username})
return frozenset({usr[1:] if usr.startswith("@") else usr for usr in username})
| """Accepts a username or collection of usernames and returns a frozenset of usernames.
Strips the leading ``@`` if present.
"""
if username is None:
return frozenset()
if isinstance(username, str):
return frozenset({username[1:] if username.startswith("@") else username})
return ... | 25 | 524 | 82 | 606 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | |
23,366 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_utils/stack.py | 68,69 | 1,77 | _was_called_by | 69,77 | 69,77 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | # https://stackoverflow.com/a/57712700/10606962
if Path(frame.f_code.co_filename).resolve() == caller:
return True
while frame.f_back:
frame = frame.f_back
if Path(frame.f_code.co_filename).resolve() == caller:
return True
return False
| # https://stackoverflow.com/a/57712700/10606962
if Path(frame.f_code.co_filename).resolve() == caller:
return True
while frame.f_back:
frame = frame.f_back
if Path(frame.f_code.co_filename).resolve() == caller:
return True
return False
| 21 | 671 | 109 | 780 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | |
23,367 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/ext/_utils/trackingdict.py | 112,113 | 38,125 | clear | TrackingDict | 113,118 | 113,118 | class TrackingDict(UserDict, Generic[_KT, _VT]):
"""Mutable mapping that keeps track of which keys where accessed with write access.
Read-access is not tracked.
Note:
* ``setdefault()`` and ``pop`` are considered writing only depending on whether the
key is present
* deleting va... | class TrackingDict(UserDict, Generic[_KT, _VT]):
"""Mutable mapping that keeps track of which keys where accessed with write access.
Read-access is not tracked.
Note:
* ``setdefault()`` and ``pop`` are considered writing only depending on whether the
key is present
* deleting va... | self.__track_write(set(super().keys()))
super().clear()
# Mypy seems a bit inconsistent about what it wants as types for `default` and return value
# so we just ignore a bit
| self.__track_write(set(super().keys()))
super().clear()
# Mypy seems a bit inconsistent about what it wants as types for `default` and return value
# so we just ignore a bit
| 26 | 942 | 59 | 1,001 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
23,371 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/request/_requestdata.py | 64,66 | 28,123 | json_parameters | RequestData | 74,80 | 66,80 | @final
class RequestData:
"""Instances of this class collect the data needed for one request to the Bot API, including
all parameters and files to be sent along with the request.
.. versionadded:: 20.0
Warning:
How exactly instances of this are created should be considered an implementation de... | @final
class RequestData:
"""Instances of this class collect the data needed for one request to the Bot API, including
all parameters and files to be sent along with the request.
.. versionadded:: 20.0
Warning:
How exactly instances of this are created should be considered an implementation de... | return {
param.name: param.json_value
for param in self._parameters
if param.json_value is not None
}
| """Gives the parameters as mapping of parameter name to the respective JSON encoded
value.
Tip:
By default, this property uses the standard library's :func:`json.dumps`.
To use a custom library for JSON encoding, you can directly encode the keys of
:attr:`par... | 14 | 1,071 | 44 | 1,115 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published... |
23,372 | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot | /home/hieuvd/dung_repo/raw/stars_01/python-telegram-bot_python-telegram-bot/python-telegram-bot/telegram/request/_requestparameter.py | 88,92 | 34,171 | _value_and_input_files_from_input | RequestParameter | 111,150 | 92,150 | @final
@dataclass(repr=True, eq=False, order=False, frozen=True)
class RequestParameter:
"""Instances of this class represent a single parameter to be sent along with a request to
the Bot API.
.. versionadded:: 20.0
Warning:
This class intended is to be used internally by the library and *not*... | @final
@dataclass(repr=True, eq=False, order=False, frozen=True)
class RequestParameter:
"""Instances of this class represent a single parameter to be sent along with a request to
the Bot API.
.. versionadded:: 20.0
Warning:
This class intended is to be used internally by the library and *not*... | if isinstance(value, datetime):
return to_timestamp(value), []
if isinstance(value, StringEnum):
return value.value, []
if isinstance(value, InputFile):
if value.attach_uri:
return value.attach_uri, [value]
return None, [value]
... | """Converts `value` into something that we can json-dump. Returns two values:
1. the JSON-dumpable value. Maybe be `None` in case the value is an InputFile which must
not be uploaded via an attach:// URI
2. A list of InputFiles that should be uploaded for this value
Note that... | 146 | 1,195 | 467 | 1,662 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published... | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2024
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published... |
23,396 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/misc/generate_table.py | 14,15 | 1,36 | wrap_row | 15,18 | 15,18 | import segmentation_models_pytorch as smp
encoders = smp.encoders.encoders
WIDTH = 32
COLUMNS = [
"Encoder",
"Weights",
"Params, M",
]
def wrap_row(r):
FILL_FUNC_BODYheader = "|".join([column.ljust(WIDTH, " ") for column in COLUMNS])
separator = "|".join(["-" * WIDTH] + [":" + "-" * (WIDTH - 2) + ":"] ... | import segmentation_models_pytorch as smp
encoders = smp.encoders.encoders
WIDTH = 32
COLUMNS = [
"Encoder",
"Weights",
"Params, M",
]
def wrap_row(r):
FILL_FUNC_BODYheader = "|".join([column.ljust(WIDTH, " ") for column in COLUMNS])
separator = "|".join(["-" * WIDTH] + [":" + "-" * (WIDTH - 2) + ":"] ... | return "|{}|".format(r)
| return "|{}|".format(r)
| 2 | 343 | 17 | 360 | import segmentation_models_pytorch as smp
encoders = smp.encoders.encoders
WIDTH = 32
COLUMNS = [
"Encoder",
"Weights",
"Params, M",
]
def wrap_row(r):
FILL_FUNC_BODYheader = "|".join([column.ljust(WIDTH, " ") for column in COLUMNS])
separator = "|".join(["-" * WIDTH] + [":" + "-" * (WIDTH - 2) + ":"] ... | import segmentation_models_pytorch as smp
encoders = smp.encoders.encoders
WIDTH = 32
COLUMNS = [
"Encoder",
"Weights",
"Params, M",
]
def wrap_row(r):
FILL_FUNC_BODYheader = "|".join([column.ljust(WIDTH, " ") for column in COLUMNS])
separator = "|".join(["-" * WIDTH] + [":" + "-" * (WIDTH - 2) + ":"] ... | |
23,397 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/misc/generate_table_timm.py | 20,21 | 1,57 | make_table | 21,39 | 21,39 | import timm
from tqdm import tqdm
def check_features_and_reduction(name):
encoder = timm.create_model(name, features_only=True, pretrained=False)
if not encoder.feature_info.reduction() == [2, 4, 8, 16, 32]:
raise ValueError
def has_dilation_support(name):
try:
timm.create_model(name, fe... | import timm
from tqdm import tqdm
def check_features_and_reduction(name):
encoder = timm.create_model(name, features_only=True, pretrained=False)
if not encoder.feature_info.reduction() == [2, 4, 8, 16, 32]:
raise ValueError
def has_dilation_support(name):
try:
timm.create_model(name, fe... | names = data.keys()
max_len1 = max([len(x) for x in names]) + 2
max_len2 = len("support dilation") + 2
l1 = "+" + "-" * max_len1 + "+" + "-" * max_len2 + "+\n"
l2 = "+" + "=" * max_len1 + "+" + "=" * max_len2 + "+\n"
top = "| " + "Encoder name".ljust(max_len1 - 2) + " | " + "Support dilation".c... | names = data.keys()
max_len1 = max([len(x) for x in names]) + 2
max_len2 = len("support dilation") + 2
l1 = "+" + "-" * max_len1 + "+" + "-" * max_len2 + "+\n"
l2 = "+" + "=" * max_len1 + "+" + "=" * max_len2 + "+\n"
top = "| " + "Encoder name".ljust(max_len1 - 2) + " | " + "Support dilation".c... | 114 | 374 | 296 | 670 | import timm
from tqdm import tqdm
def check_features_and_reduction(name):
encoder = timm.create_model(name, features_only=True, pretrained=False)
if not encoder.feature_info.reduction() == [2, 4, 8, 16, 32]:
raise ValueError
def has_dilation_support(name):
try:
timm.create_model(name, fe... | import timm
from tqdm import tqdm
def check_features_and_reduction(name):
encoder = timm.create_model(name, features_only=True, pretrained=False)
if not encoder.feature_info.reduction() == [2, 4, 8, 16, 32]:
raise ValueError
def has_dilation_support(name):
try:
timm.create_model(name, fe... | |
23,398 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/base/initialization.py | 4,5 | 1,28 | initialize_decoder | 5,22 | 5,22 | import torch.nn as nn
def initialize_decoder(module):
FILL_FUNC_BODYdef initialize_head(module):
for m in module.modules():
if isinstance(m, (nn.Linear, nn.Conv2d)):
nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
| import torch.nn as nn
def initialize_decoder(module):
FILL_FUNC_BODYdef initialize_head(module):
for m in module.modules():
if isinstance(m, (nn.Linear, nn.Conv2d)):
nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
| for m in module.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_uniform_(m.weight, mode="fan_in", nonlinearity="relu")
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
... | for m in module.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_uniform_(m.weight, mode="fan_in", nonlinearity="relu")
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
... | 35 | 113 | 212 | 325 | import torch.nn as nn
def initialize_decoder(module):
FILL_FUNC_BODYdef initialize_head(module):
for m in module.modules():
if isinstance(m, (nn.Linear, nn.Conv2d)):
nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
| import torch.nn as nn
def initialize_decoder(module):
FILL_FUNC_BODYdef initialize_head(module):
for m in module.modules():
if isinstance(m, (nn.Linear, nn.Conv2d)):
nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
| |
23,399 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/base/model.py | 12,13 | 5,57 | check_input_shape | SegmentationModel | 13,24 | 13,24 | class SegmentationModel(torch.nn.Module):
def initialize(self):
init.initialize_decoder(self.decoder)
init.initialize_head(self.segmentation_head)
if self.classification_head is not None:
init.initialize_head(self.classification_head)
def check_input_shape(self, x):
FILL_FUN... | class SegmentationModel(torch.nn.Module):
def initialize(self):
init.initialize_decoder(self.decoder)
init.initialize_head(self.segmentation_head)
if self.classification_head is not None:
init.initialize_head(self.classification_head)
def check_input_shape(self, x):
FILL_FUN... |
h, w = x.shape[-2:]
output_stride = self.encoder.output_stride
if h % output_stride != 0 or w % output_stride != 0:
new_h = (h // output_stride + 1) * output_stride if h % output_stride != 0 else h
new_w = (w // output_stride + 1) * output_stride if w % output_stride != ... |
h, w = x.shape[-2:]
output_stride = self.encoder.output_stride
if h % output_stride != 0 or w % output_stride != 0:
new_h = (h // output_stride + 1) * output_stride if h % output_stride != 0 else h
new_w = (w // output_stride + 1) * output_stride if w % output_stride != ... | 78 | 380 | 195 | 575 | import torch
from . import initialization as init
class SegmentationModel(torch.nn.Module):
def initialize(self):
init.initialize_decoder(self.decoder)
init.initialize_head(self.segmentation_head)
if self.classification_head is not None:
init.initialize_head(self.classification... | import torch
from . import initialization as init
class SegmentationModel(torch.nn.Module):
def initialize(self):
init.initialize_decoder(self.decoder)
init.initialize_head(self.segmentation_head)
if self.classification_head is not None:
init.initialize_head(self.classification... |
23,400 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/base/modules.py | 115,116 | 84,119 | forward | Activation | 116,119 | 116,119 | class Activation(nn.Module):
def __init__(self, name, **params):
super().__init__()
if name is None or name == "identity":
self.activation = nn.Identity(**params)
elif name == "sigmoid":
self.activation = nn.Sigmoid()
elif name == "softmax2d":
se... | class Activation(nn.Module):
def __init__(self, name, **params):
super().__init__()
if name is None or name == "identity":
self.activation = nn.Identity(**params)
elif name == "sigmoid":
self.activation = nn.Sigmoid()
elif name == "softmax2d":
se... | return self.activation(x)
| return self.activation(x)
| 2 | 360 | 15 | 375 | import torch
import torch.nn as nn
try:
from inplace_abn import InPlaceABN
except ImportError:
InPlaceABN = None
class Conv2dReLU(nn.Sequential):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
padding=0,
stride=1,
use_batchnorm=True,
... | import torch
import torch.nn as nn
try:
from inplace_abn import InPlaceABN
except ImportError:
InPlaceABN = None
class Conv2dReLU(nn.Sequential):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
padding=0,
stride=1,
use_batchnorm=True,
... |
23,401 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/base/modules.py | 71,72 | 66,75 | forward | ArgMax | 72,75 | 72,75 | class ArgMax(nn.Module):
def __init__(self, dim=None):
super().__init__()
self.dim = dim
def forward(self, x):
FILL_FUNC_BODY | class ArgMax(nn.Module):
def __init__(self, dim=None):
super().__init__()
self.dim = dim
def forward(self, x):
FILL_FUNC_BODY | return torch.argmax(x, dim=self.dim)
| return torch.argmax(x, dim=self.dim)
| 3 | 56 | 22 | 78 | import torch
import torch.nn as nn
try:
from inplace_abn import InPlaceABN
except ImportError:
InPlaceABN = None
class Conv2dReLU(nn.Sequential):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
padding=0,
stride=1,
use_batchnorm=True,
... | import torch
import torch.nn as nn
try:
from inplace_abn import InPlaceABN
except ImportError:
InPlaceABN = None
class Conv2dReLU(nn.Sequential):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
padding=0,
stride=1,
use_batchnorm=True,
... |
23,402 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/base/modules.py | 130,131 | 119,132 | forward | Attention | 131,132 | 131,132 | class Attention(nn.Module):
def __init__(self, name, **params):
super().__init__()
if name is None:
self.attention = nn.Identity(**params)
elif name == "scse":
self.attention = SCSEModule(**params)
else:
raise ValueError("Attention {} is not imple... | class Attention(nn.Module):
def __init__(self, name, **params):
super().__init__()
if name is None:
self.attention = nn.Identity(**params)
elif name == "scse":
self.attention = SCSEModule(**params)
else:
raise ValueError("Attention {} is not imple... | return self.attention(x)
| return self.attention(x)
| 2 | 115 | 10 | 125 | import torch
import torch.nn as nn
try:
from inplace_abn import InPlaceABN
except ImportError:
InPlaceABN = None
class Conv2dReLU(nn.Sequential):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
padding=0,
stride=1,
use_batchnorm=True,
... | import torch
import torch.nn as nn
try:
from inplace_abn import InPlaceABN
except ImportError:
InPlaceABN = None
class Conv2dReLU(nn.Sequential):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
padding=0,
stride=1,
use_batchnorm=True,
... |
23,403 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/base/modules.py | 80,81 | 75,84 | forward | Clamp | 81,84 | 81,84 | class Clamp(nn.Module):
def __init__(self, min=0, max=1):
super().__init__()
self.min, self.max = min, max
def forward(self, x):
FILL_FUNC_BODY | class Clamp(nn.Module):
def __init__(self, min=0, max=1):
super().__init__()
self.min, self.max = min, max
def forward(self, x):
FILL_FUNC_BODY | return torch.clamp(x, self.min, self.max)
| return torch.clamp(x, self.min, self.max)
| 4 | 66 | 24 | 90 | import torch
import torch.nn as nn
try:
from inplace_abn import InPlaceABN
except ImportError:
InPlaceABN = None
class Conv2dReLU(nn.Sequential):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
padding=0,
stride=1,
use_batchnorm=True,
... | import torch
import torch.nn as nn
try:
from inplace_abn import InPlaceABN
except ImportError:
InPlaceABN = None
class Conv2dReLU(nn.Sequential):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
padding=0,
stride=1,
use_batchnorm=True,
... |
23,404 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/base/modules.py | 62,63 | 50,66 | forward | SCSEModule | 63,66 | 63,66 | class SCSEModule(nn.Module):
def __init__(self, in_channels, reduction=16):
super().__init__()
self.cSE = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(in_channels, in_channels // reduction, 1),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels // reduc... | class SCSEModule(nn.Module):
def __init__(self, in_channels, reduction=16):
super().__init__()
self.cSE = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(in_channels, in_channels // reduction, 1),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels // reduc... | return x * self.cSE(x) + x * self.sSE(x)
| return x * self.cSE(x) + x * self.sSE(x)
| 8 | 201 | 27 | 228 | import torch
import torch.nn as nn
try:
from inplace_abn import InPlaceABN
except ImportError:
InPlaceABN = None
class Conv2dReLU(nn.Sequential):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
padding=0,
stride=1,
use_batchnorm=True,
... | import torch
import torch.nn as nn
try:
from inplace_abn import InPlaceABN
except ImportError:
InPlaceABN = None
class Conv2dReLU(nn.Sequential):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
padding=0,
stride=1,
use_batchnorm=True,
... |
23,405 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/deeplabv3/decoder.py | 184,185 | 155,192 | forward | ASPP | 185,192 | 185,192 | class ASPP(nn.Module):
def __init__(self, in_channels, out_channels, atrous_rates, separable=False):
super(ASPP, self).__init__()
modules = []
modules.append(
nn.Sequential(
nn.Conv2d(in_channels, out_channels, 1, bias=False),
nn.BatchNorm2d(out_ch... | class ASPP(nn.Module):
def __init__(self, in_channels, out_channels, atrous_rates, separable=False):
super(ASPP, self).__init__()
modules = []
modules.append(
nn.Sequential(
nn.Conv2d(in_channels, out_channels, 1, bias=False),
nn.BatchNorm2d(out_ch... | res = []
for conv in self.convs:
res.append(conv(x))
res = torch.cat(res, dim=1)
return self.project(res)
| res = []
for conv in self.convs:
res.append(conv(x))
res = torch.cat(res, dim=1)
return self.project(res)
| 14 | 389 | 58 | 447 | """
BSD 3-Clause License
Copyright (c) Soumith Chintala 2016,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of con... | """
BSD 3-Clause License
Copyright (c) Soumith Chintala 2016,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of con... |
23,406 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/deeplabv3/decoder.py | 148,149 | 139,155 | forward | ASPPPooling | 149,155 | 149,155 | class ASPPPooling(nn.Sequential):
def __init__(self, in_channels, out_channels):
super().__init__(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(),
)
def forward(sel... | class ASPPPooling(nn.Sequential):
def __init__(self, in_channels, out_channels):
super().__init__(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(),
)
def forward(sel... | size = x.shape[-2:]
for mod in self:
x = mod(x)
return F.interpolate(x, size=size, mode="bilinear", align_corners=False)
| size = x.shape[-2:]
for mod in self:
x = mod(x)
return F.interpolate(x, size=size, mode="bilinear", align_corners=False)
| 15 | 131 | 63 | 194 | """
BSD 3-Clause License
Copyright (c) Soumith Chintala 2016,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of con... | """
BSD 3-Clause License
Copyright (c) Soumith Chintala 2016,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of con... |
23,407 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/deeplabv3/decoder.py | 50,51 | 40,54 | forward | DeepLabV3Decoder | 51,54 | 51,54 | class DeepLabV3Decoder(nn.Sequential):
def __init__(self, in_channels, out_channels=256, atrous_rates=(12, 24, 36)):
super().__init__(
ASPP(in_channels, out_channels, atrous_rates),
nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False),
nn.BatchNorm2d(out_channe... | class DeepLabV3Decoder(nn.Sequential):
def __init__(self, in_channels, out_channels=256, atrous_rates=(12, 24, 36)):
super().__init__(
ASPP(in_channels, out_channels, atrous_rates),
nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False),
nn.BatchNorm2d(out_channe... | return super().forward(features[-1])
| return super().forward(features[-1])
| 2 | 174 | 16 | 190 | """
BSD 3-Clause License
Copyright (c) Soumith Chintala 2016,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of con... | """
BSD 3-Clause License
Copyright (c) Soumith Chintala 2016,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of con... |
23,408 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/deeplabv3/decoder.py | 98,99 | 54,107 | forward | DeepLabV3PlusDecoder | 99,107 | 99,107 | class DeepLabV3PlusDecoder(nn.Module):
def __init__(
self,
encoder_channels,
out_channels=256,
atrous_rates=(12, 24, 36),
output_stride=16,
):
super().__init__()
if output_stride not in {8, 16}:
raise ValueError("Output stride should be 8 or 16... | class DeepLabV3PlusDecoder(nn.Module):
def __init__(
self,
encoder_channels,
out_channels=256,
atrous_rates=(12, 24, 36),
output_stride=16,
):
super().__init__()
if output_stride not in {8, 16}:
raise ValueError("Output stride should be 8 or 16... | aspp_features = self.aspp(features[-1])
aspp_features = self.up(aspp_features)
high_res_features = self.block1(features[-4])
concat_features = torch.cat([aspp_features, high_res_features], dim=1)
fused_features = self.block2(concat_features)
return fused_features
| aspp_features = self.aspp(features[-1])
aspp_features = self.up(aspp_features)
high_res_features = self.block1(features[-4])
concat_features = torch.cat([aspp_features, high_res_features], dim=1)
fused_features = self.block2(concat_features)
return fused_features
| 19 | 539 | 109 | 648 | """
BSD 3-Clause License
Copyright (c) Soumith Chintala 2016,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of con... | """
BSD 3-Clause License
Copyright (c) Soumith Chintala 2016,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of con... |
23,409 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/fpn/decoder.py | 16,17 | 6,23 | forward | Conv3x3GNReLU | 17,23 | 17,23 | class Conv3x3GNReLU(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False):
super().__init__()
self.upsample = upsample
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, (3, 3), stride=1, padding=1, bias=False),
nn.GroupNorm(32, out_c... | class Conv3x3GNReLU(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False):
super().__init__()
self.upsample = upsample
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, (3, 3), stride=1, padding=1, bias=False),
nn.GroupNorm(32, out_c... | x = self.block(x)
if self.upsample:
x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True)
return x
| x = self.block(x)
if self.upsample:
x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True)
return x
| 13 | 161 | 63 | 224 | import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv3x3GNReLU(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False):
super().__init__()
self.upsample = upsample
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, (3, 3),... | import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv3x3GNReLU(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False):
super().__init__()
self.upsample = upsample
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, (3, 3),... |
23,410 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/fpn/decoder.py | 28,29 | 23,35 | forward | FPNBlock | 29,35 | 29,35 | class FPNBlock(nn.Module):
def __init__(self, pyramid_channels, skip_channels):
super().__init__()
self.skip_conv = nn.Conv2d(skip_channels, pyramid_channels, kernel_size=1)
def forward(self, x, skip=None):
FILL_FUNC_BODY | class FPNBlock(nn.Module):
def __init__(self, pyramid_channels, skip_channels):
super().__init__()
self.skip_conv = nn.Conv2d(skip_channels, pyramid_channels, kernel_size=1)
def forward(self, x, skip=None):
FILL_FUNC_BODY | x = F.interpolate(x, scale_factor=2, mode="nearest")
skip = self.skip_conv(skip)
x = x + skip
return x
| x = F.interpolate(x, scale_factor=2, mode="nearest")
skip = self.skip_conv(skip)
x = x + skip
return x
| 15 | 96 | 55 | 151 | import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv3x3GNReLU(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False):
super().__init__()
self.upsample = upsample
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, (3, 3),... | import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv3x3GNReLU(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False):
super().__init__()
self.upsample = upsample
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, (3, 3),... |
23,411 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/fpn/decoder.py | 101,102 | 67,114 | forward | FPNDecoder | 102,114 | 102,114 | class FPNDecoder(nn.Module):
def __init__(
self,
encoder_channels,
encoder_depth=5,
pyramid_channels=256,
segmentation_channels=128,
dropout=0.2,
merge_policy="add",
):
super().__init__()
self.out_channels = segmentation_channels if merge_... | class FPNDecoder(nn.Module):
def __init__(
self,
encoder_channels,
encoder_depth=5,
pyramid_channels=256,
segmentation_channels=128,
dropout=0.2,
merge_policy="add",
):
super().__init__()
self.out_channels = segmentation_channels if merge_... | c2, c3, c4, c5 = features[-4:]
p5 = self.p5(c5)
p4 = self.p4(p5, c4)
p3 = self.p3(p4, c3)
p2 = self.p2(p3, c2)
feature_pyramid = [seg_block(p) for seg_block, p in zip(self.seg_blocks, [p5, p4, p3, p2])]
x = self.merge(feature_pyramid)
x = self.dropout(x)... | c2, c3, c4, c5 = features[-4:]
p5 = self.p5(c5)
p4 = self.p4(p5, c4)
p3 = self.p3(p4, c3)
p2 = self.p2(p3, c2)
feature_pyramid = [seg_block(p) for seg_block, p in zip(self.seg_blocks, [p5, p4, p3, p2])]
x = self.merge(feature_pyramid)
x = self.dropout(x)... | 41 | 442 | 167 | 609 | import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv3x3GNReLU(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False):
super().__init__()
self.upsample = upsample
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, (3, 3),... | import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv3x3GNReLU(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False):
super().__init__()
self.upsample = upsample
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, (3, 3),... |
23,412 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/fpn/decoder.py | 58,59 | 51,67 | forward | MergeBlock | 59,67 | 59,67 | class MergeBlock(nn.Module):
def __init__(self, policy):
super().__init__()
if policy not in ["add", "cat"]:
raise ValueError("`merge_policy` must be one of: ['add', 'cat'], got {}".format(policy))
self.policy = policy
def forward(self, x):
FILL_FUNC_BODY | class MergeBlock(nn.Module):
def __init__(self, policy):
super().__init__()
if policy not in ["add", "cat"]:
raise ValueError("`merge_policy` must be one of: ['add', 'cat'], got {}".format(policy))
self.policy = policy
def forward(self, x):
FILL_FUNC_BODY | if self.policy == "add":
return sum(x)
elif self.policy == "cat":
return torch.cat(x, dim=1)
else:
raise ValueError("`merge_policy` must be one of: ['add', 'cat'], got {}".format(self.policy))
| if self.policy == "add":
return sum(x)
elif self.policy == "cat":
return torch.cat(x, dim=1)
else:
raise ValueError("`merge_policy` must be one of: ['add', 'cat'], got {}".format(self.policy))
| 24 | 97 | 86 | 183 | import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv3x3GNReLU(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False):
super().__init__()
self.upsample = upsample
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, (3, 3),... | import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv3x3GNReLU(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False):
super().__init__()
self.upsample = upsample
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, (3, 3),... |
23,413 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/fpn/decoder.py | 47,48 | 35,51 | forward | SegmentationBlock | 48,51 | 48,51 | class SegmentationBlock(nn.Module):
def __init__(self, in_channels, out_channels, n_upsamples=0):
super().__init__()
blocks = [Conv3x3GNReLU(in_channels, out_channels, upsample=bool(n_upsamples))]
if n_upsamples > 1:
for _ in range(1, n_upsamples):
blocks.append... | class SegmentationBlock(nn.Module):
def __init__(self, in_channels, out_channels, n_upsamples=0):
super().__init__()
blocks = [Conv3x3GNReLU(in_channels, out_channels, upsample=bool(n_upsamples))]
if n_upsamples > 1:
for _ in range(1, n_upsamples):
blocks.append... | return self.block(x)
| return self.block(x)
| 2 | 173 | 14 | 187 | import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv3x3GNReLU(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False):
super().__init__()
self.upsample = upsample
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, (3, 3),... | import torch
import torch.nn as nn
import torch.nn.functional as F
class Conv3x3GNReLU(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False):
super().__init__()
self.upsample = upsample
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, (3, 3),... |
23,414 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/linknet/decoder.py | 40,41 | 20,47 | forward | DecoderBlock | 41,47 | 41,47 | class DecoderBlock(nn.Module):
def __init__(self, in_channels, out_channels, use_batchnorm=True):
super().__init__()
self.block = nn.Sequential(
modules.Conv2dReLU(
in_channels,
in_channels // 4,
kernel_size=1,
use_batchnor... | class DecoderBlock(nn.Module):
def __init__(self, in_channels, out_channels, use_batchnorm=True):
super().__init__()
self.block = nn.Sequential(
modules.Conv2dReLU(
in_channels,
in_channels // 4,
kernel_size=1,
use_batchnor... | x = self.block(x)
if skip is not None:
x = x + skip
return x
| x = self.block(x)
if skip is not None:
x = x + skip
return x
| 15 | 221 | 37 | 258 | import torch.nn as nn
from segmentation_models_pytorch.base import modules
class TransposeX2(nn.Sequential):
def __init__(self, in_channels, out_channels, use_batchnorm=True):
super().__init__()
layers = [
nn.ConvTranspose2d(in_channels, out_channels, kernel_size=4, stride=2, padding=... | import torch.nn as nn
from segmentation_models_pytorch.base import modules
class TransposeX2(nn.Sequential):
def __init__(self, in_channels, out_channels, use_batchnorm=True):
super().__init__()
layers = [
nn.ConvTranspose2d(in_channels, out_channels, kernel_size=4, stride=2, padding=... |
23,415 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/linknet/decoder.py | 68,69 | 47,80 | forward | LinknetDecoder | 69,80 | 69,80 | class LinknetDecoder(nn.Module):
def __init__(
self,
encoder_channels,
prefinal_channels=32,
n_blocks=5,
use_batchnorm=True,
):
super().__init__()
# remove first skip
encoder_channels = encoder_channels[1:]
# reverse channels to start from... | class LinknetDecoder(nn.Module):
def __init__(
self,
encoder_channels,
prefinal_channels=32,
n_blocks=5,
use_batchnorm=True,
):
super().__init__()
# remove first skip
encoder_channels = encoder_channels[1:]
# reverse channels to start from... | features = features[1:] # remove first skip
features = features[::-1] # reverse channels to start from head of encoder
x = features[0]
skips = features[1:]
for i, decoder_block in enumerate(self.blocks):
skip = skips[i] if i < len(skips) else None
x = ... | features = features[1:] # remove first skip
features = features[::-1] # reverse channels to start from head of encoder
x = features[0]
skips = features[1:]
for i, decoder_block in enumerate(self.blocks):
skip = skips[i] if i < len(skips) else None
x = ... | 45 | 211 | 117 | 328 | import torch.nn as nn
from segmentation_models_pytorch.base import modules
class TransposeX2(nn.Sequential):
def __init__(self, in_channels, out_channels, use_batchnorm=True):
super().__init__()
layers = [
nn.ConvTranspose2d(in_channels, out_channels, kernel_size=4, stride=2, padding=... | import torch.nn as nn
from segmentation_models_pytorch.base import modules
class TransposeX2(nn.Sequential):
def __init__(self, in_channels, out_channels, use_batchnorm=True):
super().__init__()
layers = [
nn.ConvTranspose2d(in_channels, out_channels, kernel_size=4, stride=2, padding=... |
23,416 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/manet/decoder.py | 122,123 | 104,131 | forward | DecoderBlock | 123,131 | 123,131 | class DecoderBlock(nn.Module):
def __init__(self, in_channels, skip_channels, out_channels, use_batchnorm=True):
super().__init__()
self.conv1 = md.Conv2dReLU(
in_channels + skip_channels,
out_channels,
kernel_size=3,
padding=1,
use_batchno... | class DecoderBlock(nn.Module):
def __init__(self, in_channels, skip_channels, out_channels, use_batchnorm=True):
super().__init__()
self.conv1 = md.Conv2dReLU(
in_channels + skip_channels,
out_channels,
kernel_size=3,
padding=1,
use_batchno... | x = F.interpolate(x, scale_factor=2, mode="nearest")
if skip is not None:
x = torch.cat([x, skip], dim=1)
x = self.conv1(x)
x = self.conv2(x)
return x
| x = F.interpolate(x, scale_factor=2, mode="nearest")
if skip is not None:
x = torch.cat([x, skip], dim=1)
x = self.conv1(x)
x = self.conv2(x)
return x
| 23 | 197 | 85 | 282 | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class PAB(nn.Module):
def __init__(self, in_channels, out_channels, pab_channels=64):
super(PAB, self).__init__()
# Series of 1x1 conv to generate attention feature maps
... | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class PAB(nn.Module):
def __init__(self, in_channels, out_channels, pab_channels=64):
super(PAB, self).__init__()
# Series of 1x1 conv to generate attention feature maps
... |
23,417 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/manet/decoder.py | 175,176 | 131,189 | forward | MAnetDecoder | 176,189 | 176,189 | class MAnetDecoder(nn.Module):
def __init__(
self,
encoder_channels,
decoder_channels,
n_blocks=5,
reduction=16,
use_batchnorm=True,
pab_channels=64,
):
super().__init__()
if n_blocks != len(decoder_channels):
raise ValueError(... | class MAnetDecoder(nn.Module):
def __init__(
self,
encoder_channels,
decoder_channels,
n_blocks=5,
reduction=16,
use_batchnorm=True,
pab_channels=64,
):
super().__init__()
if n_blocks != len(decoder_channels):
raise ValueError(... |
features = features[1:] # remove first skip with same spatial resolution
features = features[::-1] # reverse channels to start from head of encoder
head = features[0]
skips = features[1:]
x = self.center(head)
for i, decoder_block in enumerate(self.blocks):
... |
features = features[1:] # remove first skip with same spatial resolution
features = features[::-1] # reverse channels to start from head of encoder
head = features[0]
skips = features[1:]
x = self.center(head)
for i, decoder_block in enumerate(self.blocks):
... | 52 | 501 | 134 | 635 | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class PAB(nn.Module):
def __init__(self, in_channels, out_channels, pab_channels=64):
super(PAB, self).__init__()
# Series of 1x1 conv to generate attention feature maps
... | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class PAB(nn.Module):
def __init__(self, in_channels, out_channels, pab_channels=64):
super(PAB, self).__init__()
# Series of 1x1 conv to generate attention feature maps
... |
23,418 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/manet/decoder.py | 90,91 | 41,104 | forward | MFAB | 91,104 | 91,104 | class MFAB(nn.Module):
def __init__(self, in_channels, skip_channels, out_channels, use_batchnorm=True, reduction=16):
# MFAB is just a modified version of SE-blocks, one for skip, one for input
super(MFAB, self).__init__()
self.hl_conv = nn.Sequential(
md.Conv2dReLU(
... | class MFAB(nn.Module):
def __init__(self, in_channels, skip_channels, out_channels, use_batchnorm=True, reduction=16):
# MFAB is just a modified version of SE-blocks, one for skip, one for input
super(MFAB, self).__init__()
self.hl_conv = nn.Sequential(
md.Conv2dReLU(
... | x = self.hl_conv(x)
x = F.interpolate(x, scale_factor=2, mode="nearest")
attention_hl = self.SE_hl(x)
if skip is not None:
attention_ll = self.SE_ll(skip)
attention_hl = attention_hl + attention_ll
x = x * attention_hl
x = torch.cat([x, ski... | x = self.hl_conv(x)
x = F.interpolate(x, scale_factor=2, mode="nearest")
attention_hl = self.SE_hl(x)
if skip is not None:
attention_ll = self.SE_ll(skip)
attention_hl = attention_hl + attention_ll
x = x * attention_hl
x = torch.cat([x, ski... | 42 | 593 | 152 | 745 | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class PAB(nn.Module):
def __init__(self, in_channels, out_channels, pab_channels=64):
super(PAB, self).__init__()
# Series of 1x1 conv to generate attention feature maps
... | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class PAB(nn.Module):
def __init__(self, in_channels, out_channels, pab_channels=64):
super(PAB, self).__init__()
# Series of 1x1 conv to generate attention feature maps
... |
23,419 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/manet/decoder.py | 20,21 | 8,41 | forward | PAB | 21,41 | 21,41 | class PAB(nn.Module):
def __init__(self, in_channels, out_channels, pab_channels=64):
super(PAB, self).__init__()
# Series of 1x1 conv to generate attention feature maps
self.pab_channels = pab_channels
self.in_channels = in_channels
self.top_conv = nn.Conv2d(in_channels, pab... | class PAB(nn.Module):
def __init__(self, in_channels, out_channels, pab_channels=64):
super(PAB, self).__init__()
# Series of 1x1 conv to generate attention feature maps
self.pab_channels = pab_channels
self.in_channels = in_channels
self.top_conv = nn.Conv2d(in_channels, pab... | bsize = x.size()[0]
h = x.size()[2]
w = x.size()[3]
x_top = self.top_conv(x)
x_center = self.center_conv(x)
x_bottom = self.bottom_conv(x)
x_top = x_top.flatten(2)
x_center = x_center.flatten(2).transpose(1, 2)
x_bottom = x_bottom.flatten(2).trans... | bsize = x.size()[0]
h = x.size()[2]
w = x.size()[3]
x_top = self.top_conv(x)
x_center = self.center_conv(x)
x_bottom = self.bottom_conv(x)
x_top = x_top.flatten(2)
x_center = x_center.flatten(2).transpose(1, 2)
x_bottom = x_bottom.flatten(2).trans... | 63 | 269 | 293 | 562 | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class PAB(nn.Module):
def __init__(self, in_channels, out_channels, pab_channels=64):
super(PAB, self).__init__()
# Series of 1x1 conv to generate attention feature maps
... | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class PAB(nn.Module):
def __init__(self, in_channels, out_channels, pab_channels=64):
super(PAB, self).__init__()
# Series of 1x1 conv to generate attention feature maps
... |
23,420 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/pan/decoder.py | 36,37 | 6,46 | forward | ConvBnRelu | 37,46 | 37,46 | class ConvBnRelu(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
groups: int = 1,
bias: bool = True,
add_relu: bool = True,
interpolate... | class ConvBnRelu(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
groups: int = 1,
bias: bool = True,
add_relu: bool = True,
interpolate... | x = self.conv(x)
x = self.bn(x)
if self.add_relu:
x = self.activation(x)
if self.interpolate:
x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True)
return x
| x = self.conv(x)
x = self.bn(x)
if self.add_relu:
x = self.activation(x)
if self.interpolate:
x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True)
return x
| 21 | 299 | 98 | 397 | import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBnRelu(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
groups: int = 1,
... | import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBnRelu(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
groups: int = 1,
... |
23,421 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/pan/decoder.py | 100,101 | 46,125 | forward | FPABlock | 101,125 | 101,125 | class FPABlock(nn.Module):
def __init__(self, in_channels, out_channels, upscale_mode="bilinear"):
super(FPABlock, self).__init__()
self.upscale_mode = upscale_mode
if self.upscale_mode == "bilinear":
self.align_corners = True
else:
self.align_corners = False... | class FPABlock(nn.Module):
def __init__(self, in_channels, out_channels, upscale_mode="bilinear"):
super(FPABlock, self).__init__()
self.upscale_mode = upscale_mode
if self.upscale_mode == "bilinear":
self.align_corners = True
else:
self.align_corners = False... | h, w = x.size(2), x.size(3)
b1 = self.branch1(x)
upscale_parameters = dict(mode=self.upscale_mode, align_corners=self.align_corners)
b1 = F.interpolate(b1, size=(h, w), **upscale_parameters)
mid = self.mid(x)
x1 = self.down1(x)
x2 = self.down2(x1)
x3 = se... | h, w = x.size(2), x.size(3)
b1 = self.branch1(x)
upscale_parameters = dict(mode=self.upscale_mode, align_corners=self.align_corners)
b1 = F.interpolate(b1, size=(h, w), **upscale_parameters)
mid = self.mid(x)
x1 = self.down1(x)
x2 = self.down2(x1)
x3 = se... | 83 | 675 | 323 | 998 | import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBnRelu(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
groups: int = 1,
... | import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBnRelu(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
groups: int = 1,
... |
23,422 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/pan/decoder.py | 144,145 | 125,158 | forward | GAUBlock | 150,158 | 145,158 | class GAUBlock(nn.Module):
def __init__(self, in_channels: int, out_channels: int, upscale_mode: str = "bilinear"):
super(GAUBlock, self).__init__()
self.upscale_mode = upscale_mode
self.align_corners = True if upscale_mode == "bilinear" else None
self.conv1 = nn.Sequential(
... | class GAUBlock(nn.Module):
def __init__(self, in_channels: int, out_channels: int, upscale_mode: str = "bilinear"):
super(GAUBlock, self).__init__()
self.upscale_mode = upscale_mode
self.align_corners = True if upscale_mode == "bilinear" else None
self.conv1 = nn.Sequential(
... | h, w = x.size(2), x.size(3)
y_up = F.interpolate(y, size=(h, w), mode=self.upscale_mode, align_corners=self.align_corners)
x = self.conv2(x)
y = self.conv1(y)
z = torch.mul(x, y)
return y_up + z
| """
Args:
x: low level feature
y: high level feature
"""
h, w = x.size(2), x.size(3)
y_up = F.interpolate(y, size=(h, w), mode=self.upscale_mode, align_corners=self.align_corners)
x = self.conv2(x)
y = self.conv1(y)
z = torch.mul(x,... | 26 | 285 | 114 | 399 | import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBnRelu(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
groups: int = 1,
... | import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBnRelu(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
groups: int = 1,
... |
23,423 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/pan/decoder.py | 179,180 | 158,187 | forward | PANDecoder | 180,187 | 180,187 | class PANDecoder(nn.Module):
def __init__(self, encoder_channels, decoder_channels, upscale_mode: str = "bilinear"):
super().__init__()
self.fpa = FPABlock(in_channels=encoder_channels[-1], out_channels=decoder_channels)
self.gau3 = GAUBlock(
in_channels=encoder_channels[-2],
... | class PANDecoder(nn.Module):
def __init__(self, encoder_channels, decoder_channels, upscale_mode: str = "bilinear"):
super().__init__()
self.fpa = FPABlock(in_channels=encoder_channels[-1], out_channels=decoder_channels)
self.gau3 = GAUBlock(
in_channels=encoder_channels[-2],
... | bottleneck = features[-1]
x5 = self.fpa(bottleneck) # 1/32
x4 = self.gau3(features[-2], x5) # 1/16
x3 = self.gau2(features[-3], x4) # 1/8
x2 = self.gau1(features[-4], x3) # 1/4
return x2
| bottleneck = features[-1]
x5 = self.fpa(bottleneck) # 1/32
x4 = self.gau3(features[-2], x5) # 1/16
x3 = self.gau2(features[-3], x4) # 1/8
x2 = self.gau1(features[-4], x3) # 1/4
return x2
| 28 | 274 | 120 | 394 | import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBnRelu(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
groups: int = 1,
... | import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBnRelu(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
groups: int = 1,
... |
23,424 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/pspnet/decoder.py | 18,19 | 8,25 | forward | PSPBlock | 19,25 | 19,25 | class PSPBlock(nn.Module):
def __init__(self, in_channels, out_channels, pool_size, use_bathcnorm=True):
super().__init__()
if pool_size == 1:
use_bathcnorm = False # PyTorch does not support BatchNorm for 1x1 shape
self.pool = nn.Sequential(
nn.AdaptiveAvgPool2d(out... | class PSPBlock(nn.Module):
def __init__(self, in_channels, out_channels, pool_size, use_bathcnorm=True):
super().__init__()
if pool_size == 1:
use_bathcnorm = False # PyTorch does not support BatchNorm for 1x1 shape
self.pool = nn.Sequential(
nn.AdaptiveAvgPool2d(out... | h, w = x.size(2), x.size(3)
x = self.pool(x)
x = F.interpolate(x, size=(h, w), mode="bilinear", align_corners=True)
return x
| h, w = x.size(2), x.size(3)
x = self.pool(x)
x = F.interpolate(x, size=(h, w), mode="bilinear", align_corners=True)
return x
| 17 | 185 | 74 | 259 | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules
class PSPBlock(nn.Module):
def __init__(self, in_channels, out_channels, pool_size, use_bathcnorm=True):
super().__init__()
if pool_size == 1:
use_bathcnorm = False ... | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules
class PSPBlock(nn.Module):
def __init__(self, in_channels, out_channels, pool_size, use_bathcnorm=True):
super().__init__()
if pool_size == 1:
use_bathcnorm = False ... |
23,425 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/pspnet/decoder.py | 72,73 | 47,79 | forward | PSPDecoder | 73,79 | 73,79 | class PSPDecoder(nn.Module):
def __init__(
self,
encoder_channels,
use_batchnorm=True,
out_channels=512,
dropout=0.2,
):
super().__init__()
self.psp = PSPModule(
in_channels=encoder_channels[-1],
sizes=(1, 2, 3, 6),
use... | class PSPDecoder(nn.Module):
def __init__(
self,
encoder_channels,
use_batchnorm=True,
out_channels=512,
dropout=0.2,
):
super().__init__()
self.psp = PSPModule(
in_channels=encoder_channels[-1],
sizes=(1, 2, 3, 6),
use... | x = features[-1]
x = self.psp(x)
x = self.conv(x)
x = self.dropout(x)
return x
| x = features[-1]
x = self.psp(x)
x = self.conv(x)
x = self.dropout(x)
return x
| 14 | 241 | 51 | 292 | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules
class PSPBlock(nn.Module):
def __init__(self, in_channels, out_channels, pool_size, use_bathcnorm=True):
super().__init__()
if pool_size == 1:
use_bathcnorm = False ... | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules
class PSPBlock(nn.Module):
def __init__(self, in_channels, out_channels, pool_size, use_bathcnorm=True):
super().__init__()
if pool_size == 1:
use_bathcnorm = False ... |
23,426 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/pspnet/decoder.py | 41,42 | 25,47 | forward | PSPModule | 42,47 | 42,47 | class PSPModule(nn.Module):
def __init__(self, in_channels, sizes=(1, 2, 3, 6), use_bathcnorm=True):
super().__init__()
self.blocks = nn.ModuleList(
[
PSPBlock(
in_channels,
in_channels // len(sizes),
size,
... | class PSPModule(nn.Module):
def __init__(self, in_channels, sizes=(1, 2, 3, 6), use_bathcnorm=True):
super().__init__()
self.blocks = nn.ModuleList(
[
PSPBlock(
in_channels,
in_channels // len(sizes),
size,
... | xs = [block(x) for block in self.blocks] + [x]
x = torch.cat(xs, dim=1)
return x
| xs = [block(x) for block in self.blocks] + [x]
x = torch.cat(xs, dim=1)
return x
| 15 | 147 | 47 | 194 | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules
class PSPBlock(nn.Module):
def __init__(self, in_channels, out_channels, pool_size, use_bathcnorm=True):
super().__init__()
if pool_size == 1:
use_bathcnorm = False ... | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules
class PSPBlock(nn.Module):
def __init__(self, in_channels, out_channels, pool_size, use_bathcnorm=True):
super().__init__()
if pool_size == 1:
use_bathcnorm = False ... |
23,427 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/unet/decoder.py | 35,36 | 8,46 | forward | DecoderBlock | 36,46 | 36,46 | class DecoderBlock(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
out_channels,
use_batchnorm=True,
attention_type=None,
):
super().__init__()
self.conv1 = md.Conv2dReLU(
in_channels + skip_channels,
out_channel... | class DecoderBlock(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
out_channels,
use_batchnorm=True,
attention_type=None,
):
super().__init__()
self.conv1 = md.Conv2dReLU(
in_channels + skip_channels,
out_channel... | x = F.interpolate(x, scale_factor=2, mode="nearest")
if skip is not None:
x = torch.cat([x, skip], dim=1)
x = self.attention1(x)
x = self.conv1(x)
x = self.conv2(x)
x = self.attention2(x)
return x
| x = F.interpolate(x, scale_factor=2, mode="nearest")
if skip is not None:
x = torch.cat([x, skip], dim=1)
x = self.attention1(x)
x = self.conv1(x)
x = self.conv2(x)
x = self.attention2(x)
return x
| 29 | 276 | 109 | 385 | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class DecoderBlock(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
out_channels,
use_batchnorm=True,
attention_type=None,
)... | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class DecoderBlock(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
out_channels,
use_batchnorm=True,
attention_type=None,
)... |
23,428 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/unet/decoder.py | 108,109 | 65,122 | forward | UnetDecoder | 109,122 | 109,122 | class UnetDecoder(nn.Module):
def __init__(
self,
encoder_channels,
decoder_channels,
n_blocks=5,
use_batchnorm=True,
attention_type=None,
center=False,
):
super().__init__()
if n_blocks != len(decoder_channels):
raise ValueErr... | class UnetDecoder(nn.Module):
def __init__(
self,
encoder_channels,
decoder_channels,
n_blocks=5,
use_batchnorm=True,
attention_type=None,
center=False,
):
super().__init__()
if n_blocks != len(decoder_channels):
raise ValueErr... |
features = features[1:] # remove first skip with same spatial resolution
features = features[::-1] # reverse channels to start from head of encoder
head = features[0]
skips = features[1:]
x = self.center(head)
for i, decoder_block in enumerate(self.blocks):
... |
features = features[1:] # remove first skip with same spatial resolution
features = features[::-1] # reverse channels to start from head of encoder
head = features[0]
skips = features[1:]
x = self.center(head)
for i, decoder_block in enumerate(self.blocks):
... | 52 | 462 | 134 | 596 | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class DecoderBlock(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
out_channels,
use_batchnorm=True,
attention_type=None,
)... | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class DecoderBlock(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
out_channels,
use_batchnorm=True,
attention_type=None,
)... |
23,429 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/unetplusplus/decoder.py | 35,36 | 8,46 | forward | DecoderBlock | 36,46 | 36,46 | class DecoderBlock(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
out_channels,
use_batchnorm=True,
attention_type=None,
):
super().__init__()
self.conv1 = md.Conv2dReLU(
in_channels + skip_channels,
out_channel... | class DecoderBlock(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
out_channels,
use_batchnorm=True,
attention_type=None,
):
super().__init__()
self.conv1 = md.Conv2dReLU(
in_channels + skip_channels,
out_channel... | x = F.interpolate(x, scale_factor=2, mode="nearest")
if skip is not None:
x = torch.cat([x, skip], dim=1)
x = self.attention1(x)
x = self.conv1(x)
x = self.conv2(x)
x = self.attention2(x)
return x
| x = F.interpolate(x, scale_factor=2, mode="nearest")
if skip is not None:
x = torch.cat([x, skip], dim=1)
x = self.attention1(x)
x = self.conv1(x)
x = self.conv2(x)
x = self.attention2(x)
return x
| 29 | 276 | 109 | 385 | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class DecoderBlock(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
out_channels,
use_batchnorm=True,
attention_type=None,
)... | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class DecoderBlock(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
out_channels,
use_batchnorm=True,
attention_type=None,
)... |
23,430 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/decoders/unetplusplus/decoder.py | 120,121 | 65,140 | forward | UnetPlusPlusDecoder | 121,140 | 121,140 | class UnetPlusPlusDecoder(nn.Module):
def __init__(
self,
encoder_channels,
decoder_channels,
n_blocks=5,
use_batchnorm=True,
attention_type=None,
center=False,
):
super().__init__()
if n_blocks != len(decoder_channels):
raise ... | class UnetPlusPlusDecoder(nn.Module):
def __init__(
self,
encoder_channels,
decoder_channels,
n_blocks=5,
use_batchnorm=True,
attention_type=None,
center=False,
):
super().__init__()
if n_blocks != len(decoder_channels):
raise ... |
features = features[1:] # remove first skip with same spatial resolution
features = features[::-1] # reverse channels to start from head of encoder
# start building dense connections
dense_x = {}
for layer_idx in range(len(self.in_channels) - 1):
for depth_idx in r... |
features = features[1:] # remove first skip with same spatial resolution
features = features[::-1] # reverse channels to start from head of encoder
# start building dense connections
dense_x = {}
for layer_idx in range(len(self.in_channels) - 1):
for depth_idx in r... | 93 | 700 | 413 | 1,113 | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class DecoderBlock(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
out_channels,
use_batchnorm=True,
attention_type=None,
)... | import torch
import torch.nn as nn
import torch.nn.functional as F
from segmentation_models_pytorch.base import modules as md
class DecoderBlock(nn.Module):
def __init__(
self,
in_channels,
skip_channels,
out_channels,
use_batchnorm=True,
attention_type=None,
)... |
23,431 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/_base.py | 26,27 | 9,66 | set_in_channels | EncoderMixin | 28,37 | 27,37 | class EncoderMixin:
"""Add encoder functionality such as:
- output channels specification of feature tensors (produced by encoder)
- patching first convolution for arbitrary input channels
"""
_output_stride = 32
@property
def out_channels(self):
"""Return channels dimensions for e... | class EncoderMixin:
"""Add encoder functionality such as:
- output channels specification of feature tensors (produced by encoder)
- patching first convolution for arbitrary input channels
"""
_output_stride = 32
@property
def out_channels(self):
"""Return channels dimensions for e... | if in_channels == 3:
return
self._in_channels = in_channels
if self._out_channels[0] == 3:
self._out_channels = tuple([in_channels] + list(self._out_channels)[1:])
utils.patch_first_conv(model=self, new_in_channels=in_channels, pretrained=pretrained)
| """Change first convolution channels"""
if in_channels == 3:
return
self._in_channels = in_channels
if self._out_channels[0] == 3:
self._out_channels = tuple([in_channels] + list(self._out_channels)[1:])
utils.patch_first_conv(model=self, new_in_channels... | 20 | 425 | 115 | 540 | import torch
import torch.nn as nn
from typing import List
from collections import OrderedDict
from . import _utils as utils
class EncoderMixin:
"""Add encoder functionality such as:
- output channels specification of feature tensors (produced by encoder)
- patching first convolution for arbitrary input ... | import torch
import torch.nn as nn
from typing import List
from collections import OrderedDict
from . import _utils as utils
class EncoderMixin:
"""Add encoder functionality such as:
- output channels specification of feature tensors (produced by encoder)
- patching first convolution for arbitrary input ... |
23,432 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/_preprocessing.py | 4,5 | 1,22 | preprocess_input | 5,22 | 5,22 | import numpy as np
def preprocess_input(x, mean=None, std=None, input_space="RGB", input_range=None, **kwargs):
FILL_FUNC_BODY | import numpy as np
def preprocess_input(x, mean=None, std=None, input_space="RGB", input_range=None, **kwargs):
FILL_FUNC_BODY |
if input_space == "BGR":
x = x[..., ::-1].copy()
if input_range is not None:
if x.max() > 1 and input_range[1] == 1:
x = x / 255.0
if mean is not None:
mean = np.array(mean)
x = x - mean
if std is not None:
std = np.array(std)
x = x / std
... |
if input_space == "BGR":
x = x[..., ::-1].copy()
if input_range is not None:
if x.max() > 1 and input_range[1] == 1:
x = x / 255.0
if mean is not None:
mean = np.array(mean)
x = x - mean
if std is not None:
std = np.array(std)
x = x / std
... | 54 | 52 | 142 | 194 | import numpy as np
def preprocess_input(x, mean=None, std=None, input_space="RGB", input_range=None, **kwargs):
FILL_FUNC_BODY | import numpy as np
def preprocess_input(x, mean=None, std=None, input_space="RGB", input_range=None, **kwargs):
FILL_FUNC_BODY | |
23,433 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/_utils.py | 40,41 | 1,52 | replace_strides_with_dilation | 42,52 | 41,52 | import torch
import torch.nn as nn
def patch_first_conv(model, new_in_channels, default_in_channels=3, pretrained=True):
"""Change first convolution layer input channels.
In case:
in_channels == 1 or in_channels == 2 -> reuse original weights
in_channels > 3 -> make random kaiming normal initi... | import torch
import torch.nn as nn
def patch_first_conv(model, new_in_channels, default_in_channels=3, pretrained=True):
"""Change first convolution layer input channels.
In case:
in_channels == 1 or in_channels == 2 -> reuse original weights
in_channels > 3 -> make random kaiming normal initi... | for mod in module.modules():
if isinstance(mod, nn.Conv2d):
mod.stride = (1, 1)
mod.dilation = (dilation_rate, dilation_rate)
kh, kw = mod.kernel_size
mod.padding = ((kh // 2) * dilation_rate, (kh // 2) * dilation_rate)
# Kostyl for EfficientNet
... | """Patch Conv2d modules replacing strides with dilation"""
for mod in module.modules():
if isinstance(mod, nn.Conv2d):
mod.stride = (1, 1)
mod.dilation = (dilation_rate, dilation_rate)
kh, kw = mod.kernel_size
mod.padding = ((kh // 2) * dilation_rate, (kh ... | 41 | 461 | 147 | 608 | import torch
import torch.nn as nn
def patch_first_conv(model, new_in_channels, default_in_channels=3, pretrained=True):
"""Change first convolution layer input channels.
In case:
in_channels == 1 or in_channels == 2 -> reuse original weights
in_channels > 3 -> make random kaiming normal initi... | import torch
import torch.nn as nn
def patch_first_conv(model, new_in_channels, default_in_channels=3, pretrained=True):
"""Change first convolution layer input channels.
In case:
in_channels == 1 or in_channels == 2 -> reuse original weights
in_channels > 3 -> make random kaiming normal initi... | |
23,434 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/dpn.py | 56,57 | 36,76 | forward | DPNEncoder | 57,70 | 57,70 | class DPNEncoder(DPN, EncoderMixin):
def __init__(self, stage_idxs, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._stage_idxs = stage_idxs
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.last_linear
def ge... | class DPNEncoder(DPN, EncoderMixin):
def __init__(self, stage_idxs, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._stage_idxs = stage_idxs
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.last_linear
def ge... |
stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
if isinstance(x, (list, tuple)):
features.append(F.relu(torch.cat(x, dim=1), inplace=True))
else:
features.append(x)
return fe... |
stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
if isinstance(x, (list, tuple)):
features.append(F.relu(torch.cat(x, dim=1), inplace=True))
else:
features.append(x)
return fe... | 26 | 362 | 113 | 475 | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... |
23,436 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/efficientnet.py | 55,56 | 32,85 | forward | EfficientNetEncoder | 56,79 | 56,79 | class EfficientNetEncoder(EfficientNet, EncoderMixin):
def __init__(self, stage_idxs, out_channels, model_name, depth=5):
blocks_args, global_params = get_model_params(model_name, override_params=None)
super().__init__(blocks_args, global_params)
self._stage_idxs = stage_idxs
self.... | class EfficientNetEncoder(EfficientNet, EncoderMixin):
def __init__(self, stage_idxs, out_channels, model_name, depth=5):
blocks_args, global_params = get_model_params(model_name, override_params=None)
super().__init__(blocks_args, global_params)
self._stage_idxs = stage_idxs
self.... | stages = self.get_stages()
block_number = 0.0
drop_connect_rate = self._global_params.drop_connect_rate
features = []
for i in range(self._depth + 1):
# Identity and Sequential stages
if i < 2:
x = stages[i](x)
# Block stage... | stages = self.get_stages()
block_number = 0.0
drop_connect_rate = self._global_params.drop_connect_rate
features = []
for i in range(self._depth + 1):
# Identity and Sequential stages
if i < 2:
x = stages[i](x)
# Block stage... | 58 | 360 | 192 | 552 | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... |
23,437 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/inceptionresnetv2.py | 68,69 | 33,85 | forward | InceptionResNetV2Encoder | 69,79 | 69,79 | class InceptionResNetV2Encoder(InceptionResNetV2, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
# correct paddings
for m in self.modules():
... | class InceptionResNetV2Encoder(InceptionResNetV2, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
# correct paddings
for m in self.modules():
... |
stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
|
stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
| 18 | 528 | 65 | 593 | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... |
23,438 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/inceptionv4.py | 67,68 | 33,84 | forward | InceptionV4Encoder | 68,78 | 68,78 | class InceptionV4Encoder(InceptionV4, EncoderMixin):
def __init__(self, stage_idxs, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._stage_idxs = stage_idxs
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
# correct paddin... | class InceptionV4Encoder(InceptionV4, EncoderMixin):
def __init__(self, stage_idxs, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._stage_idxs = stage_idxs
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
# correct paddin... |
stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
|
stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
| 18 | 482 | 65 | 547 | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... |
23,440 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/mix_transformer.py | 90,91 | 52,114 | forward | Attention | 91,114 | 91,114 | class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, sr_ratio=1):
super().__init__()
assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
self.dim = dim
self.num_heads = num_hea... | class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, sr_ratio=1):
super().__init__()
assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}."
self.dim = dim
self.num_heads = num_hea... | B, N, C = x.shape
q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
if self.sr_ratio > 1:
x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
x_ = self.norm(x_)
kv = se... | B, N, C = x.shape
q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
if self.sr_ratio > 1:
x_ = x.permute(0, 2, 1).reshape(B, C, H, W)
x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)
x_ = self.norm(x_)
kv = se... | 100 | 609 | 415 | 1,024 | # ---------------------------------------------------------------
# Copyright (c) 2021, NVIDIA Corporation. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# ---------------------------------------------------------------
import math
import torch
import torch.nn as nn
from functools ... | # ---------------------------------------------------------------
# Copyright (c) 2021, NVIDIA Corporation. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# ---------------------------------------------------------------
import math
import torch
import torch.nn as nn
from functools ... |
23,441 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/mix_transformer.py | 148,149 | 114,170 | _init_weights | Block | 149,163 | 149,163 | class Block(nn.Module):
def __init__(
self,
dim,
num_heads,
mlp_ratio=4.0,
qkv_bias=False,
qk_scale=None,
drop=0.0,
attn_drop=0.0,
drop_path=0.0,
act_layer=nn.GELU,
norm_layer=nn.LayerNorm,
sr_ratio=1,
):
sup... | class Block(nn.Module):
def __init__(
self,
dim,
num_heads,
mlp_ratio=4.0,
qkv_bias=False,
qk_scale=None,
drop=0.0,
attn_drop=0.0,
drop_path=0.0,
act_layer=nn.GELU,
norm_layer=nn.LayerNorm,
sr_ratio=1,
):
sup... | if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
... | if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
... | 45 | 471 | 236 | 707 | # ---------------------------------------------------------------
# Copyright (c) 2021, NVIDIA Corporation. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# ---------------------------------------------------------------
import math
import torch
import torch.nn as nn
from functools ... | # ---------------------------------------------------------------
# Copyright (c) 2021, NVIDIA Corporation. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# ---------------------------------------------------------------
import math
import torch
import torch.nn as nn
from functools ... |
23,442 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/mix_transformer.py | 441,442 | 436,454 | forward | DWConv | 442,454 | 442,454 | class DWConv(nn.Module):
def __init__(self, dim=768):
super(DWConv, self).__init__()
self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
def forward(self, x, H, W):
FILL_FUNC_BODY | class DWConv(nn.Module):
def __init__(self, dim=768):
super(DWConv, self).__init__()
self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
def forward(self, x, H, W):
FILL_FUNC_BODY | B, N, C = x.shape
x = x.transpose(1, 2).view(B, C, H, W)
x = self.dwconv(x)
x = x.flatten(2).transpose(1, 2)
return x
# ---------------------------------------------------------------
# End of NVIDIA code
# ---------------------------------------------------------------
| B, N, C = x.shape
x = x.transpose(1, 2).view(B, C, H, W)
x = self.dwconv(x)
x = x.flatten(2).transpose(1, 2)
return x
# ---------------------------------------------------------------
# End of NVIDIA code
# ---------------------------------------------------------------
| 30 | 100 | 104 | 204 | # ---------------------------------------------------------------
# Copyright (c) 2021, NVIDIA Corporation. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# ---------------------------------------------------------------
import math
import torch
import torch.nn as nn
from functools ... | # ---------------------------------------------------------------
# Copyright (c) 2021, NVIDIA Corporation. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# ---------------------------------------------------------------
import math
import torch
import torch.nn as nn
from functools ... |
23,444 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/mix_transformer.py | 471,472 | 457,485 | forward | MixVisionTransformerEncoder | 472,479 | 472,479 | class MixVisionTransformerEncoder(MixVisionTransformer, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
def make_dilated(self, *args, **kwargs):
rai... | class MixVisionTransformerEncoder(MixVisionTransformer, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
def make_dilated(self, *args, **kwargs):
rai... |
# create dummy output for the first block
B, C, H, W = x.shape
dummy = torch.empty([B, 0, H // 2, W // 2], dtype=x.dtype, device=x.device)
return [x, dummy] + self.forward_features(x)[: self._depth - 1]
|
# create dummy output for the first block
B, C, H, W = x.shape
dummy = torch.empty([B, 0, H // 2, W // 2], dtype=x.dtype, device=x.device)
return [x, dummy] + self.forward_features(x)[: self._depth - 1]
| 34 | 259 | 99 | 358 | # ---------------------------------------------------------------
# Copyright (c) 2021, NVIDIA Corporation. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# ---------------------------------------------------------------
import math
import torch
import torch.nn as nn
from functools ... | # ---------------------------------------------------------------
# Copyright (c) 2021, NVIDIA Corporation. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# ---------------------------------------------------------------
import math
import torch
import torch.nn as nn
from functools ... |
23,445 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/mix_transformer.py | 42,43 | 14,52 | forward | Mlp | 43,52 | 43,52 | class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_feature... | class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_feature... | x = self.fc1(x)
x = self.dwconv(x, H, W)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
| x = self.fc1(x)
x = self.dwconv(x, H, W)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
| 22 | 437 | 83 | 520 | # ---------------------------------------------------------------
# Copyright (c) 2021, NVIDIA Corporation. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# ---------------------------------------------------------------
import math
import torch
import torch.nn as nn
from functools ... | # ---------------------------------------------------------------
# Copyright (c) 2021, NVIDIA Corporation. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# ---------------------------------------------------------------
import math
import torch
import torch.nn as nn
from functools ... |
23,446 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/mix_transformer.py | 193,194 | 170,217 | _init_weights | OverlapPatchEmbed | 194,208 | 194,208 | class OverlapPatchEmbed(nn.Module):
"""Image to Patch Embedding"""
def __init__(self, img_size=224, patch_size=7, stride=4, in_chans=3, embed_dim=768):
super().__init__()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.pat... | class OverlapPatchEmbed(nn.Module):
"""Image to Patch Embedding"""
def __init__(self, img_size=224, patch_size=7, stride=4, in_chans=3, embed_dim=768):
super().__init__()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = img_size
self.pat... | if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
... | if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
... | 45 | 379 | 236 | 615 | # ---------------------------------------------------------------
# Copyright (c) 2021, NVIDIA Corporation. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# ---------------------------------------------------------------
import math
import torch
import torch.nn as nn
from functools ... | # ---------------------------------------------------------------
# Copyright (c) 2021, NVIDIA Corporation. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# ---------------------------------------------------------------
import math
import torch
import torch.nn as nn
from functools ... |
23,447 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/mobilenet.py | 60,61 | 32,66 | load_state_dict | MobileNetV2Encoder | 61,66 | 61,66 | class MobileNetV2Encoder(torchvision.models.MobileNetV2, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.classifier
def get_stages(self):
... | class MobileNetV2Encoder(torchvision.models.MobileNetV2, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.classifier
def get_stages(self):
... | state_dict.pop("classifier.1.bias", None)
state_dict.pop("classifier.1.weight", None)
super().load_state_dict(state_dict, **kwargs)
| state_dict.pop("classifier.1.bias", None)
state_dict.pop("classifier.1.weight", None)
super().load_state_dict(state_dict, **kwargs)
| 6 | 258 | 59 | 317 | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... |
23,449 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/mobileone.py | 395,396 | 280,420 | forward | MobileOne | 397,404 | 396,404 | class MobileOne(nn.Module, EncoderMixin):
"""MobileOne Model
Pytorch implementation of `An Improved One millisecond Mobile Backbone` -
https://arxiv.org/pdf/2206.04040.pdf
"""
def __init__(
self,
out_channels,
num_blocks_per_stage: List[int] = [2, 8, 10, 1],
width_m... | class MobileOne(nn.Module, EncoderMixin):
"""MobileOne Model
Pytorch implementation of `An Improved One millisecond Mobile Backbone` -
https://arxiv.org/pdf/2206.04040.pdf
"""
def __init__(
self,
out_channels,
num_blocks_per_stage: List[int] = [2, 8, 10, 1],
width_m... | stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
| """Apply forward pass."""
stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
| 18 | 1,607 | 59 | 1,666 | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
import copy
from typing import List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import _utils as utils
from ._base import EncoderMixin
__all__ = ["MobileOne", "repara... | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
import copy
from typing import List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import _utils as utils
from ._base import EncoderMixin
__all__ = ["MobileOne", "repara... |
23,451 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/mobileone.py | 39,40 | 18,51 | forward | SEBlock | 41,51 | 40,51 | class SEBlock(nn.Module):
"""Squeeze and Excite module.
Pytorch implementation of `Squeeze-and-Excitation Networks` -
https://arxiv.org/pdf/1709.01507.pdf
"""
def __init__(self, in_channels: int, rd_ratio: float = 0.0625) -> None:
"""Construct a Squeeze and Excite Module.
:param i... | class SEBlock(nn.Module):
"""Squeeze and Excite module.
Pytorch implementation of `Squeeze-and-Excitation Networks` -
https://arxiv.org/pdf/1709.01507.pdf
"""
def __init__(self, in_channels: int, rd_ratio: float = 0.0625) -> None:
"""Construct a Squeeze and Excite Module.
:param i... | b, c, h, w = inputs.size()
x = F.avg_pool2d(inputs, kernel_size=[h, w])
x = self.reduce(x)
x = F.relu(x)
x = self.expand(x)
x = torch.sigmoid(x)
x = x.view(-1, c, 1, 1)
return inputs * x
| """Apply forward pass."""
b, c, h, w = inputs.size()
x = F.avg_pool2d(inputs, kernel_size=[h, w])
x = self.reduce(x)
x = F.relu(x)
x = self.expand(x)
x = torch.sigmoid(x)
x = x.view(-1, c, 1, 1)
return inputs * x
| 33 | 325 | 120 | 445 | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
import copy
from typing import List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import _utils as utils
from ._base import EncoderMixin
__all__ = ["MobileOne", "repara... | #
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
import copy
from typing import List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import _utils as utils
from ._base import EncoderMixin
__all__ = ["MobileOne", "repara... |
23,452 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/resnet.py | 57,58 | 37,73 | forward | ResNetEncoder | 58,67 | 58,67 | class ResNetEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.fc
del self.avgpool
def get_stages(self):
retu... | class ResNetEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.fc
del self.avgpool
def get_stages(self):
retu... | stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
| stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
| 18 | 265 | 63 | 328 | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... |
23,453 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/senet.py | 49,50 | 38,75 | get_stages | SENetEncoder | 50,59 | 50,59 | class SENetEncoder(SENet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
del self.last_linear
del self.avg_pool
def get_stages(self):
FIL... | class SENetEncoder(SENet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
del self.last_linear
del self.avg_pool
def get_stages(self):
FIL... | return [
nn.Identity(),
self.layer0[:-1],
nn.Sequential(self.layer0[-1], self.layer1),
self.layer2,
self.layer3,
self.layer4,
]
| return [
nn.Identity(),
self.layer0[:-1],
nn.Sequential(self.layer0[-1], self.layer1),
self.layer2,
self.layer3,
self.layer4,
]
| 10 | 250 | 76 | 326 | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... |
23,455 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/timm_efficientnet.py | 125,126 | 94,131 | load_state_dict | EfficientNetBaseEncoder | 126,131 | 126,131 | class EfficientNetBaseEncoder(EfficientNet, EncoderMixin):
def __init__(self, stage_idxs, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._stage_idxs = stage_idxs
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
del self.... | class EfficientNetBaseEncoder(EfficientNet, EncoderMixin):
def __init__(self, stage_idxs, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._stage_idxs = stage_idxs
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
del self.... | state_dict.pop("classifier.bias", None)
state_dict.pop("classifier.weight", None)
super().load_state_dict(state_dict, **kwargs)
| state_dict.pop("classifier.bias", None)
state_dict.pop("classifier.weight", None)
super().load_state_dict(state_dict, **kwargs)
| 6 | 328 | 55 | 383 | from functools import partial
import torch
import torch.nn as nn
from timm.models.efficientnet import EfficientNet
from timm.models.efficientnet import decode_arch_def, round_channels, default_cfgs
from timm.layers.activations import Swish
from ._base import EncoderMixin
def get_efficientnet_kwargs(channel_multipl... | from functools import partial
import torch
import torch.nn as nn
from timm.models.efficientnet import EfficientNet
from timm.models.efficientnet import decode_arch_def, round_channels, default_cfgs
from timm.layers.activations import Swish
from ._base import EncoderMixin
def get_efficientnet_kwargs(channel_multipl... |
23,456 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/timm_gernet.py | 16,17 | 7,42 | get_stages | GERNetEncoder | 17,26 | 17,26 | class GERNetEncoder(ByobNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.head
def get_stages(self):
FILL_FUNC_BODY def forward(self... | class GERNetEncoder(ByobNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.head
def get_stages(self):
FILL_FUNC_BODY def forward(self... | return [
nn.Identity(),
self.stem,
self.stages[0],
self.stages[1],
self.stages[2],
nn.Sequential(self.stages[3], self.stages[4], self.final_conv),
]
| return [
nn.Identity(),
self.stem,
self.stages[0],
self.stages[1],
self.stages[2],
nn.Sequential(self.stages[3], self.stages[4], self.final_conv),
]
| 11 | 238 | 87 | 325 | from timm.models import ByoModelCfg, ByoBlockCfg, ByobNet
from ._base import EncoderMixin
import torch.nn as nn
class GERNetEncoder(ByobNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels... | from timm.models import ByoModelCfg, ByoBlockCfg, ByobNet
from ._base import EncoderMixin
import torch.nn as nn
class GERNetEncoder(ByobNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels... |
23,458 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/timm_mobilenetv3.py | 41,42 | 12,90 | get_stages | MobileNetV3Encoder | 42,72 | 42,72 | class MobileNetV3Encoder(nn.Module, EncoderMixin):
def __init__(self, model_name, width_mult, depth=5, **kwargs):
super().__init__()
if "large" not in model_name and "small" not in model_name:
raise ValueError("MobileNetV3 wrong model name {}".format(model_name))
self._mode = "s... | class MobileNetV3Encoder(nn.Module, EncoderMixin):
def __init__(self, model_name, width_mult, depth=5, **kwargs):
super().__init__()
if "large" not in model_name and "small" not in model_name:
raise ValueError("MobileNetV3 wrong model name {}".format(model_name))
self._mode = "s... | if self._mode == "small":
return [
nn.Identity(),
nn.Sequential(
self.model.conv_stem,
self.model.bn1,
self.model.act1,
),
self.model.blocks[0],
self.model.bloc... | if self._mode == "small":
return [
nn.Identity(),
nn.Sequential(
self.model.conv_stem,
self.model.bn1,
self.model.act1,
),
self.model.blocks[0],
self.model.bloc... | 45 | 536 | 286 | 822 | import timm
import numpy as np
import torch.nn as nn
from ._base import EncoderMixin
def _make_divisible(x, divisible_by=8):
return int(np.ceil(x * 1.0 / divisible_by) * divisible_by)
class MobileNetV3Encoder(nn.Module, EncoderMixin):
def __init__(self, model_name, width_mult, depth=5, **kwargs):
s... | import timm
import numpy as np
import torch.nn as nn
from ._base import EncoderMixin
def _make_divisible(x, divisible_by=8):
return int(np.ceil(x * 1.0 / divisible_by) * divisible_by)
class MobileNetV3Encoder(nn.Module, EncoderMixin):
def __init__(self, model_name, width_mult, depth=5, **kwargs):
s... |
23,460 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/timm_regnet.py | 26,27 | 6,42 | forward | RegNetEncoder | 27,36 | 27,36 | class RegNetEncoder(RegNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
kwargs["cfg"] = RegNetCfg(**kwargs["cfg"])
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.head
def ge... | class RegNetEncoder(RegNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
kwargs["cfg"] = RegNetCfg(**kwargs["cfg"])
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.head
def ge... | stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
| stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
| 18 | 252 | 63 | 315 | from ._base import EncoderMixin
from timm.models.regnet import RegNet, RegNetCfg
import torch.nn as nn
class RegNetEncoder(RegNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
kwargs["cfg"] = RegNetCfg(**kwargs["cfg"])
super().__init__(**kwargs)
self._depth = depth
... | from ._base import EncoderMixin
from timm.models.regnet import RegNet, RegNetCfg
import torch.nn as nn
class RegNetEncoder(RegNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
kwargs["cfg"] = RegNetCfg(**kwargs["cfg"])
super().__init__(**kwargs)
self._depth = depth
... |
23,461 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/timm_res2net.py | 30,31 | 7,46 | forward | Res2NetEncoder | 31,40 | 31,40 | class Res2NetEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.fc
del self.global_pool
def get_stages(self):
... | class Res2NetEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.fc
del self.global_pool
def get_stages(self):
... | stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
| stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
| 18 | 303 | 63 | 366 | from ._base import EncoderMixin
from timm.models.resnet import ResNet
from timm.models.res2net import Bottle2neck
import torch.nn as nn
class Res2NetEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_... | from ._base import EncoderMixin
from timm.models.resnet import ResNet
from timm.models.res2net import Bottle2neck
import torch.nn as nn
class Res2NetEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_... |
23,462 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/timm_resnest.py | 40,41 | 7,46 | load_state_dict | ResNestEncoder | 41,46 | 41,46 | class ResNestEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.fc
del self.global_pool
def get_stages(self):
... | class ResNestEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.fc
del self.global_pool
def get_stages(self):
... | state_dict.pop("fc.bias", None)
state_dict.pop("fc.weight", None)
super().load_state_dict(state_dict, **kwargs)
| state_dict.pop("fc.bias", None)
state_dict.pop("fc.weight", None)
super().load_state_dict(state_dict, **kwargs)
| 6 | 309 | 53 | 362 | from ._base import EncoderMixin
from timm.models.resnet import ResNet
from timm.models.resnest import ResNestBottleneck
import torch.nn as nn
class ResNestEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self... | from ._base import EncoderMixin
from timm.models.resnet import ResNet
from timm.models.resnest import ResNestBottleneck
import torch.nn as nn
class ResNestEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.