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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12,450 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/datastructures.py | 500,501 | 486,506 | close | FormData | 501,506 | 501,506 | class FormData(ImmutableMultiDict[str, typing.Union[UploadFile, str]]):
"""
An immutable multidict, containing both file uploads and text input.
"""
def __init__(
self,
*args: FormData
| typing.Mapping[str, str | UploadFile]
| list[tuple[str, str | UploadFile]],
... | class FormData(ImmutableMultiDict[str, typing.Union[UploadFile, str]]):
"""
An immutable multidict, containing both file uploads and text input.
"""
def __init__(
self,
*args: FormData
| typing.Mapping[str, str | UploadFile]
| list[tuple[str, str | UploadFile]],
... | for key, value in self.multi_items():
if isinstance(value, UploadFile):
await value.close()
| for key, value in self.multi_items():
if isinstance(value, UploadFile):
await value.close()
| 10 | 150 | 39 | 189 | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... |
12,451 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/datastructures.py | 549,550 | 506,593 | getlist | Headers | 550,557 | 550,557 | class Headers(typing.Mapping[str, str]):
"""
An immutable, case-insensitive multidict.
"""
def __init__(
self,
headers: typing.Mapping[str, str] | None = None,
raw: list[tuple[bytes, bytes]] | None = None,
scope: typing.MutableMapping[str, typing.Any] | None = None,
... | class Headers(typing.Mapping[str, str]):
"""
An immutable, case-insensitive multidict.
"""
def __init__(
self,
headers: typing.Mapping[str, str] | None = None,
raw: list[tuple[bytes, bytes]] | None = None,
scope: typing.MutableMapping[str, typing.Any] | None = None,
... | get_header_key = key.lower().encode("latin-1")
return [
item_value.decode("latin-1")
for item_key, item_value in self._list
if item_key == get_header_key
]
| get_header_key = key.lower().encode("latin-1")
return [
item_value.decode("latin-1")
for item_key, item_value in self._list
if item_key == get_header_key
]
| 16 | 905 | 73 | 978 | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... |
12,452 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/datastructures.py | 301,302 | 253,327 | multi_items | ImmutableMultiDict | 302,304 | 302,304 | class ImmutableMultiDict(typing.Mapping[_KeyType, _CovariantValueType]):
_dict: dict[_KeyType, _CovariantValueType]
def __init__(
self,
*args: ImmutableMultiDict[_KeyType, _CovariantValueType]
| typing.Mapping[_KeyType, _CovariantValueType]
| typing.Iterable[tuple[_KeyType, _Cov... | class ImmutableMultiDict(typing.Mapping[_KeyType, _CovariantValueType]):
_dict: dict[_KeyType, _CovariantValueType]
def __init__(
self,
*args: ImmutableMultiDict[_KeyType, _CovariantValueType]
| typing.Mapping[_KeyType, _CovariantValueType]
| typing.Iterable[tuple[_KeyType, _Cov... | return list(self._list)
| return list(self._list)
| 2 | 811 | 12 | 823 | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... |
12,453 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/datastructures.py | 335,336 | 327,385 | pop | MultiDict | 336,339 | 336,339 | class MultiDict(ImmutableMultiDict[typing.Any, typing.Any]):
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
self.setlist(key, [value])
def __delitem__(self, key: typing.Any) -> None:
self._list = [(k, v) for k, v in self._list if k != key]
del self._dict[key]
de... | class MultiDict(ImmutableMultiDict[typing.Any, typing.Any]):
def __setitem__(self, key: typing.Any, value: typing.Any) -> None:
self.setlist(key, [value])
def __delitem__(self, key: typing.Any) -> None:
self._list = [(k, v) for k, v in self._list if k != key]
del self._dict[key]
de... | self._list = [(k, v) for k, v in self._list if k != key]
return self._dict.pop(key, default)
| self._list = [(k, v) for k, v in self._list if k != key]
return self._dict.pop(key, default)
| 16 | 662 | 43 | 705 | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... |
12,454 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/datastructures.py | 661,662 | 593,680 | update | MutableHeaders | 662,665 | 662,665 | class MutableHeaders(Headers):
def __setitem__(self, key: str, value: str) -> None:
"""
Set the header `key` to `value`, removing any duplicate entries.
Retains insertion order.
"""
set_key = key.lower().encode("latin-1")
set_value = value.encode("latin-1")
f... | class MutableHeaders(Headers):
def __setitem__(self, key: str, value: str) -> None:
"""
Set the header `key` to `value`, removing any duplicate entries.
Retains insertion order.
"""
set_key = key.lower().encode("latin-1")
set_value = value.encode("latin-1")
f... | for key, val in other.items():
self[key] = val
| for key, val in other.items():
self[key] = val
| 8 | 886 | 23 | 909 | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... |
12,455 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/datastructures.py | 110,111 | 23,175 | replace | URL | 111,143 | 111,143 | class URL:
def __init__(
self,
url: str = "",
scope: Scope | None = None,
**components: typing.Any,
) -> None:
if scope is not None:
assert not url, 'Cannot set both "url" and "scope".'
assert not components, 'Cannot set both "scope" and "**compone... | class URL:
def __init__(
self,
url: str = "",
scope: Scope | None = None,
**components: typing.Any,
) -> None:
if scope is not None:
assert not url, 'Cannot set both "url" and "scope".'
assert not components, 'Cannot set both "scope" and "**compone... | if (
"username" in kwargs
or "password" in kwargs
or "hostname" in kwargs
or "port" in kwargs
):
hostname = kwargs.pop("hostname", None)
port = kwargs.pop("port", self.port)
username = kwargs.pop("username", self.usernam... | if (
"username" in kwargs
or "password" in kwargs
or "hostname" in kwargs
or "port" in kwargs
):
hostname = kwargs.pop("hostname", None)
port = kwargs.pop("port", self.port)
username = kwargs.pop("username", self.usernam... | 92 | 1,121 | 322 | 1,443 | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... |
12,456 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/datastructures.py | 189,190 | 175,205 | make_absolute_url | URLPath | 190,205 | 190,205 | class URLPath(str):
"""
A URL path string that may also hold an associated protocol and/or host.
Used by the routing to return `url_path_for` matches.
"""
def __new__(cls, path: str, protocol: str = "", host: str = "") -> URLPath:
assert protocol in ("http", "websocket", "")
return ... | class URLPath(str):
"""
A URL path string that may also hold an associated protocol and/or host.
Used by the routing to return `url_path_for` matches.
"""
def __new__(cls, path: str, protocol: str = "", host: str = "") -> URLPath:
assert protocol in ("http", "websocket", "")
return ... | if isinstance(base_url, str):
base_url = URL(base_url)
if self.protocol:
scheme = {
"http": {True: "https", False: "http"},
"websocket": {True: "wss", False: "ws"},
}[self.protocol][base_url.is_secure]
else:
scheme =... | if isinstance(base_url, str):
base_url = URL(base_url)
if self.protocol:
scheme = {
"http": {True: "https", False: "http"},
"websocket": {True: "wss", False: "ws"},
}[self.protocol][base_url.is_secure]
else:
scheme =... | 40 | 180 | 171 | 351 | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... |
12,457 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/datastructures.py | 465,466 | 423,486 | seek | UploadFile | 466,471 | 466,471 | class UploadFile:
"""
An uploaded file included as part of the request data.
"""
def __init__(
self,
file: typing.BinaryIO,
*,
size: int | None = None,
filename: str | None = None,
headers: Headers | None = None,
) -> None:
self.filename = fil... | class UploadFile:
"""
An uploaded file included as part of the request data.
"""
def __init__(
self,
file: typing.BinaryIO,
*,
size: int | None = None,
filename: str | None = None,
headers: Headers | None = None,
) -> None:
self.filename = fil... | if self._in_memory:
self.file.seek(offset)
else:
await run_in_threadpool(self.file.seek, offset)
| if self._in_memory:
self.file.seek(offset)
else:
await run_in_threadpool(self.file.seek, offset)
| 7 | 508 | 47 | 555 | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... | from __future__ import annotations
import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from starlette.concurrency import run_in_threadpool
from starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVa... |
12,458 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/endpoints.py | 49,50 | 16,59 | method_not_allowed | HTTPEndpoint | 50,59 | 50,59 | class HTTPEndpoint:
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "http"
self.scope = scope
self.receive = receive
self.send = send
self._allowed_methods = [
method
for method in ("GET", "HEAD", "POST",... | class HTTPEndpoint:
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "http"
self.scope = scope
self.receive = receive
self.send = send
self._allowed_methods = [
method
for method in ("GET", "HEAD", "POST",... | # If we're running inside a starlette application then raise an
# exception, so that the configurable exception handler can deal with
# returning the response. For plain ASGI apps, just return the response.
headers = {"Allow": ", ".join(self._allowed_methods)}
if "app" in self.sc... | # If we're running inside a starlette application then raise an
# exception, so that the configurable exception handler can deal with
# returning the response. For plain ASGI apps, just return the response.
headers = {"Allow": ", ".join(self._allowed_methods)}
if "app" in self.sc... | 52 | 377 | 132 | 509 | from __future__ import annotations
import json
import typing
from starlette import status
from starlette._utils import is_async_callable
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import PlainTextRe... | from __future__ import annotations
import json
import typing
from starlette import status
from starlette._utils import is_async_callable
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import PlainTextRe... |
12,459 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/endpoints.py | 94,95 | 59,133 | decode | WebSocketEndpoint | 95,124 | 95,124 | class WebSocketEndpoint:
encoding: str | None = None # May be "text", "bytes", or "json".
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "websocket"
self.scope = scope
self.receive = receive
self.send = send
def __await__(se... | class WebSocketEndpoint:
encoding: str | None = None # May be "text", "bytes", or "json".
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "websocket"
self.scope = scope
self.receive = receive
self.send = send
def __await__(se... | if self.encoding == "text":
if "text" not in message:
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
raise RuntimeError("Expected text websocket messages, but got bytes")
return message["text"]
elif self.encoding == "bytes":
... | if self.encoding == "text":
if "text" not in message:
await websocket.close(code=status.WS_1003_UNSUPPORTED_DATA)
raise RuntimeError("Expected text websocket messages, but got bytes")
return message["text"]
elif self.encoding == "bytes":
... | 86 | 534 | 332 | 866 | from __future__ import annotations
import json
import typing
from starlette import status
from starlette._utils import is_async_callable
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import PlainTextRe... | from __future__ import annotations
import json
import typing
from starlette import status
from starlette._utils import is_async_callable
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import PlainTextRe... |
12,461 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/formparsers.py | 79,80 | 48,120 | parse | FormParser | 80,120 | 80,120 | class FormParser:
def __init__(
self, headers: Headers, stream: typing.AsyncGenerator[bytes, None]
) -> None:
assert (
multipart is not None
), "The `python-multipart` library must be installed to use form parsing."
self.headers = headers
self.stream = stream
... | class FormParser:
def __init__(
self, headers: Headers, stream: typing.AsyncGenerator[bytes, None]
) -> None:
assert (
multipart is not None
), "The `python-multipart` library must be installed to use form parsing."
self.headers = headers
self.stream = stream
... | # Callbacks dictionary.
callbacks = {
"on_field_start": self.on_field_start,
"on_field_name": self.on_field_name,
"on_field_data": self.on_field_data,
"on_field_end": self.on_field_end,
"on_end": self.on_end,
}
# Create the par... | # Callbacks dictionary.
callbacks = {
"on_field_start": self.on_field_start,
"on_field_name": self.on_field_name,
"on_field_data": self.on_field_data,
"on_field_end": self.on_field_end,
"on_end": self.on_end,
}
# Create the par... | 103 | 357 | 427 | 784 | from __future__ import annotations
import typing
from dataclasses import dataclass, field
from enum import Enum
from tempfile import SpooledTemporaryFile
from urllib.parse import unquote_plus
from starlette.datastructures import FormData, Headers, UploadFile
try:
import multipart
from multipart.multipart imp... | from __future__ import annotations
import typing
from dataclasses import dataclass, field
from enum import Enum
from tempfile import SpooledTemporaryFile
from urllib.parse import unquote_plus
from starlette.datastructures import FormData, Headers, UploadFile
try:
import multipart
from multipart.multipart imp... |
12,462 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/formparsers.py | 228,229 | 120,279 | parse | MultiPartParser | 229,279 | 229,279 | class MultiPartParser:
max_file_size = 1024 * 1024
def __init__(
self,
headers: Headers,
stream: typing.AsyncGenerator[bytes, None],
*,
max_files: int | float = 1000,
max_fields: int | float = 1000,
) -> None:
assert (
multipart is not Non... | class MultiPartParser:
max_file_size = 1024 * 1024
def __init__(
self,
headers: Headers,
stream: typing.AsyncGenerator[bytes, None],
*,
max_files: int | float = 1000,
max_fields: int | float = 1000,
) -> None:
assert (
multipart is not Non... | # Parse the Content-Type header to get the multipart boundary.
_, params = parse_options_header(self.headers["Content-Type"])
charset = params.get(b"charset", "utf-8")
if isinstance(charset, bytes):
charset = charset.decode("latin-1")
self._charset = charset
t... | # Parse the Content-Type header to get the multipart boundary.
_, params = parse_options_header(self.headers["Content-Type"])
charset = params.get(b"charset", "utf-8")
if isinstance(charset, bytes):
charset = charset.decode("latin-1")
self._charset = charset
t... | 186 | 1,277 | 628 | 1,905 | from __future__ import annotations
import typing
from dataclasses import dataclass, field
from enum import Enum
from tempfile import SpooledTemporaryFile
from urllib.parse import unquote_plus
from starlette.datastructures import FormData, Headers, UploadFile
try:
import multipart
from multipart.multipart imp... | from __future__ import annotations
import typing
from dataclasses import dataclass, field
from enum import Enum
from tempfile import SpooledTemporaryFile
from urllib.parse import unquote_plus
from starlette.datastructures import FormData, Headers, UploadFile
try:
import multipart
from multipart.multipart imp... |
12,463 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/middleware/authentication.py | 51,53 | 16,54 | default_on_error | AuthenticationMiddleware | 53,54 | 53,54 | class AuthenticationMiddleware:
def __init__(
self,
app: ASGIApp,
backend: AuthenticationBackend,
on_error: typing.Callable[[HTTPConnection, AuthenticationError], Response]
| None = None,
) -> None:
self.app = app
self.backend = backend
self.on_err... | class AuthenticationMiddleware:
def __init__(
self,
app: ASGIApp,
backend: AuthenticationBackend,
on_error: typing.Callable[[HTTPConnection, AuthenticationError], Response]
| None = None,
) -> None:
self.app = app
self.backend = backend
self.on_err... | return PlainTextResponse(str(exc), status_code=400)
| return PlainTextResponse(str(exc), status_code=400)
| 3 | 393 | 21 | 414 | from __future__ import annotations
import typing
from starlette.authentication import (
AuthCredentials,
AuthenticationBackend,
AuthenticationError,
UnauthenticatedUser,
)
from starlette.requests import HTTPConnection
from starlette.responses import PlainTextResponse, Response
from starlette.types imp... | from __future__ import annotations
import typing
from starlette.authentication import (
AuthCredentials,
AuthenticationBackend,
AuthenticationError,
UnauthenticatedUser,
)
from starlette.requests import HTTPConnection
from starlette.responses import PlainTextResponse, Response
from starlette.types imp... |
12,464 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/middleware/base.py | 110,111 | 96,201 | call_next | BaseHTTPMiddleware | 111,189 | 111,189 | class BaseHTTPMiddleware:
def __init__(self, app: ASGIApp, dispatch: DispatchFunction | None = None) -> None:
self.app = app
self.dispatch_func = self.dispatch if dispatch is None else dispatch
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"... | class BaseHTTPMiddleware:
def __init__(self, app: ASGIApp, dispatch: DispatchFunction | None = None) -> None:
self.app = app
self.dispatch_func = self.dispatch if dispatch is None else dispatch
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"... | app_exc: Exception | None = None
send_stream: ObjectSendStream[typing.MutableMapping[str, typing.Any]]
recv_stream: ObjectReceiveStream[typing.MutableMapping[str, typing.Any]]
send_stream, recv_stream = anyio.create_memory_object_stream()
async def receive_or... | app_exc: Exception | None = None
send_stream: ObjectSendStream[typing.MutableMapping[str, typing.Any]]
recv_stream: ObjectReceiveStream[typing.MutableMapping[str, typing.Any]]
send_stream, recv_stream = anyio.create_memory_object_stream()
async def receive_or... | 201 | 295 | 820 | 1,115 | from __future__ import annotations
import typing
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette._utils import collapse_excgroups
from starlette.background import BackgroundTask
from starlette.requests import ClientDisconnect, Request
from starlette.responses import ContentStr... | from __future__ import annotations
import typing
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette._utils import collapse_excgroups
from starlette.background import BackgroundTask
from starlette.requests import ClientDisconnect, Request
from starlette.responses import ContentStr... |
12,465 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/middleware/base.py | 35,36 | 21,96 | wrapped_receive | _CachedRequest | 36,96 | 36,96 | class _CachedRequest(Request):
"""
If the user calls Request.body() from their dispatch function
we cache the entire request body in memory and pass that to downstream middlewares,
but if they call Request.stream() then all we do is send an
empty body so that downstream things don't hang forever.
... | class _CachedRequest(Request):
"""
If the user calls Request.body() from their dispatch function
we cache the entire request body in memory and pass that to downstream middlewares,
but if they call Request.stream() then all we do is send an
empty body so that downstream things don't hang forever.
... | # wrapped_rcv state 1: disconnected
if self._wrapped_rcv_disconnected:
# we've already sent a disconnect to the downstream app
# we don't need to wait to get another one
# (although most ASGI servers will just keep sending it)
return {"type": "http.disconn... | # wrapped_rcv state 1: disconnected
if self._wrapped_rcv_disconnected:
# we've already sent a disconnect to the downstream app
# we don't need to wait to get another one
# (although most ASGI servers will just keep sending it)
return {"type": "http.disconn... | 278 | 180 | 700 | 880 | from __future__ import annotations
import typing
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette._utils import collapse_excgroups
from starlette.background import BackgroundTask
from starlette.requests import ClientDisconnect, Request
from starlette.responses import ContentStr... | from __future__ import annotations
import typing
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette._utils import collapse_excgroups
from starlette.background import BackgroundTask
from starlette.requests import ClientDisconnect, Request
from starlette.responses import ContentStr... |
12,466 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/middleware/base.py | 214,215 | 201,218 | stream_response | _StreamingResponse | 215,218 | 215,218 | class _StreamingResponse(StreamingResponse):
def __init__(
self,
content: ContentStream,
status_code: int = 200,
headers: typing.Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
info: typing.Mapping[str,... | class _StreamingResponse(StreamingResponse):
def __init__(
self,
content: ContentStream,
status_code: int = 200,
headers: typing.Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
info: typing.Mapping[str,... | if self._info:
await send({"type": "http.response.debug", "info": self._info})
return await super().stream_response(send)
| if self._info:
await send({"type": "http.response.debug", "info": self._info})
return await super().stream_response(send)
| 10 | 164 | 44 | 208 | from __future__ import annotations
import typing
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette._utils import collapse_excgroups
from starlette.background import BackgroundTask
from starlette.requests import ClientDisconnect, Request
from starlette.responses import ContentStr... | from __future__ import annotations
import typing
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette._utils import collapse_excgroups
from starlette.background import BackgroundTask
from starlette.requests import ClientDisconnect, Request
from starlette.responses import ContentStr... |
12,467 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/middleware/cors.py | 106,107 | 15,179 | preflight_response | CORSMiddleware | 107,144 | 107,144 | class CORSMiddleware:
def __init__(
self,
app: ASGIApp,
allow_origins: typing.Sequence[str] = (),
allow_methods: typing.Sequence[str] = ("GET",),
allow_headers: typing.Sequence[str] = (),
allow_credentials: bool = False,
allow_origin_regex: str | None = None,
... | class CORSMiddleware:
def __init__(
self,
app: ASGIApp,
allow_origins: typing.Sequence[str] = (),
allow_methods: typing.Sequence[str] = ("GET",),
allow_headers: typing.Sequence[str] = (),
allow_credentials: bool = False,
allow_origin_regex: str | None = None,
... | requested_origin = request_headers["origin"]
requested_method = request_headers["access-control-request-method"]
requested_headers = request_headers.get("access-control-request-headers")
headers = dict(self.preflight_headers)
failures = []
if self.is_allowed_origin(orig... | requested_origin = request_headers["origin"]
requested_method = request_headers["access-control-request-method"]
requested_headers = request_headers.get("access-control-request-headers")
headers = dict(self.preflight_headers)
failures = []
if self.is_allowed_origin(orig... | 144 | 1,417 | 460 | 1,877 | from __future__ import annotations
import functools
import re
import typing
from starlette.datastructures import Headers, MutableHeaders
from starlette.responses import PlainTextResponse, Response
from starlette.types import ASGIApp, Message, Receive, Scope, Send
ALL_METHODS = ("DELETE", "GET", "HEAD", "OPTIONS", "P... | from __future__ import annotations
import functools
import re
import typing
from starlette.datastructures import Headers, MutableHeaders
from starlette.responses import PlainTextResponse, Response
from starlette.types import ASGIApp, Message, Receive, Scope, Send
ALL_METHODS = ("DELETE", "GET", "HEAD", "OPTIONS", "P... |
12,468 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/middleware/errors.py | 248,249 | 127,262 | generate_plain_text | ServerErrorMiddleware | 249,251 | 249,251 | class ServerErrorMiddleware:
"""
Handles returning 500 responses when a server error occurs.
If 'debug' is set, then traceback responses will be returned,
otherwise the designated 'handler' will be called.
This middleware class should generally be used to wrap *everything*
else up, so that unh... | class ServerErrorMiddleware:
"""
Handles returning 500 responses when a server error occurs.
If 'debug' is set, then traceback responses will be returned,
otherwise the designated 'handler' will be called.
This middleware class should generally be used to wrap *everything*
else up, so that unh... | return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
| return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
| 4 | 1,376 | 29 | 1,405 | from __future__ import annotations
import html
import inspect
import traceback
import typing
from starlette._utils import is_async_callable
from starlette.concurrency import run_in_threadpool
from starlette.requests import Request
from starlette.responses import HTMLResponse, PlainTextResponse, Response
from starlett... | from __future__ import annotations
import html
import inspect
import traceback
import typing
from starlette._utils import is_async_callable
from starlette.concurrency import run_in_threadpool
from starlette.requests import Request
from starlette.responses import HTMLResponse, PlainTextResponse, Response
from starlett... |
12,469 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/middleware/exceptions.py | 38,43 | 17,78 | add_exception_handler | ExceptionMiddleware | 43,49 | 43,49 | class ExceptionMiddleware:
def __init__(
self,
app: ASGIApp,
handlers: typing.Mapping[
typing.Any, typing.Callable[[Request, Exception], Response]
]
| None = None,
debug: bool = False,
) -> None:
self.app = app
self.debug = debug # TOD... | class ExceptionMiddleware:
def __init__(
self,
app: ASGIApp,
handlers: typing.Mapping[
typing.Any, typing.Callable[[Request, Exception], Response]
]
| None = None,
debug: bool = False,
) -> None:
self.app = app
self.debug = debug # TOD... | if isinstance(exc_class_or_status_code, int):
self._status_handlers[exc_class_or_status_code] = handler
else:
assert issubclass(exc_class_or_status_code, Exception)
self._exception_handlers[exc_class_or_status_code] = handler
| if isinstance(exc_class_or_status_code, int):
self._status_handlers[exc_class_or_status_code] = handler
else:
assert issubclass(exc_class_or_status_code, Exception)
self._exception_handlers[exc_class_or_status_code] = handler
| 13 | 605 | 90 | 695 | from __future__ import annotations
import typing
from starlette._exception_handler import (
ExceptionHandlers,
StatusHandlers,
wrap_app_handling_exceptions,
)
from starlette.exceptions import HTTPException, WebSocketException
from starlette.requests import Request
from starlette.responses import PlainText... | from __future__ import annotations
import typing
from starlette._exception_handler import (
ExceptionHandlers,
StatusHandlers,
wrap_app_handling_exceptions,
)
from starlette.exceptions import HTTPException, WebSocketException
from starlette.requests import Request
from starlette.responses import PlainText... |
12,470 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/middleware/gzip.py | 112,113 | 1,114 | unattached_send | 113,114 | 113,114 | import gzip
import io
import typing
from starlette.datastructures import Headers, MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
class GZipMiddleware:
def __init__(
self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9
) -> None:
self.app = app... | import gzip
import io
import typing
from starlette.datastructures import Headers, MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
class GZipMiddleware:
def __init__(
self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9
) -> None:
self.app = app... | raise RuntimeError("send awaitable not set") # pragma: no cover
| raise RuntimeError("send awaitable not set") # pragma: no cover
| 9 | 1,246 | 20 | 1,266 | import gzip
import io
import typing
from starlette.datastructures import Headers, MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
class GZipMiddleware:
def __init__(
self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9
) -> None:
self.app = app... | import gzip
import io
import typing
from starlette.datastructures import Headers, MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
class GZipMiddleware:
def __init__(
self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9
) -> None:
self.app = app... | |
12,471 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/middleware/gzip.py | 46,47 | 29,112 | send_with_gzip | GZipResponder | 47,112 | 47,112 | class GZipResponder:
def __init__(self, app: ASGIApp, minimum_size: int, compresslevel: int = 9) -> None:
self.app = app
self.minimum_size = minimum_size
self.send: Send = unattached_send
self.initial_message: Message = {}
self.started = False
self.content_encoding_se... | class GZipResponder:
def __init__(self, app: ASGIApp, minimum_size: int, compresslevel: int = 9) -> None:
self.app = app
self.minimum_size = minimum_size
self.send: Send = unattached_send
self.initial_message: Message = {}
self.started = False
self.content_encoding_se... | message_type = message["type"]
if message_type == "http.response.start":
# Don't send the initial message until we've determined how to
# modify the outgoing headers correctly.
self.initial_message = message
headers = Headers(raw=self.initial_message["head... | message_type = message["type"]
if message_type == "http.response.start":
# Don't send the initial message until we've determined how to
# modify the outgoing headers correctly.
self.initial_message = message
headers = Headers(raw=self.initial_message["head... | 175 | 246 | 784 | 1,030 | import gzip
import io
import typing
from starlette.datastructures import Headers, MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
class GZipMiddleware:
def __init__(
self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9
) -> None:
self.app = app... | import gzip
import io
import typing
from starlette.datastructures import Headers, MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
class GZipMiddleware:
def __init__(
self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9
) -> None:
self.app = app... |
12,472 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/middleware/sessions.py | 57,58 | 15,86 | send_wrapper | SessionMiddleware | 58,85 | 58,85 | class SessionMiddleware:
def __init__(
self,
app: ASGIApp,
secret_key: str | Secret,
session_cookie: str = "session",
max_age: int | None = 14 * 24 * 60 * 60, # 14 days, in seconds
path: str = "/",
same_site: typing.Literal["lax", "strict", "none"] = "lax",
... | class SessionMiddleware:
def __init__(
self,
app: ASGIApp,
secret_key: str | Secret,
session_cookie: str = "session",
max_age: int | None = 14 * 24 * 60 * 60, # 14 days, in seconds
path: str = "/",
same_site: typing.Literal["lax", "strict", "none"] = "lax",
... | if message["type"] == "http.response.start":
if scope["session"]:
# We have session data to persist.
data = b64encode(json.dumps(scope["session"]).encode("utf-8"))
data = self.signer.sign(data)
headers = MutableH... | if message["type"] == "http.response.start":
if scope["session"]:
# We have session data to persist.
data = b64encode(json.dumps(scope["session"]).encode("utf-8"))
data = self.signer.sign(data)
headers = MutableH... | 79 | 530 | 422 | 952 | from __future__ import annotations
import json
import typing
from base64 import b64decode, b64encode
import itsdangerous
from itsdangerous.exc import BadSignature
from starlette.datastructures import MutableHeaders, Secret
from starlette.requests import HTTPConnection
from starlette.types import ASGIApp, Message, Re... | from __future__ import annotations
import json
import typing
from base64 import b64decode, b64encode
import itsdangerous
from itsdangerous.exc import BadSignature
from starlette.datastructures import MutableHeaders, Secret
from starlette.requests import HTTPConnection
from starlette.types import ASGIApp, Message, Re... |
12,473 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/middleware/wsgi.py | 21,22 | 1,157 | build_environ | 25,73 | 22,73 | from __future__ import annotations
import io
import math
import sys
import typing
import warnings
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette.types import Receive, Scope, Send
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future rele... | from __future__ import annotations
import io
import math
import sys
import typing
import warnings
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette.types import Receive, Scope, Send
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future rele... |
script_name = scope.get("root_path", "").encode("utf8").decode("latin1")
path_info = scope["path"].encode("utf8").decode("latin1")
if path_info.startswith(script_name):
path_info = path_info[len(script_name) :]
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": scrip... | """
Builds a scope and request body into a WSGI environ object.
"""
script_name = scope.get("root_path", "").encode("utf8").decode("latin1")
path_info = scope["path"].encode("utf8").decode("latin1")
if path_info.startswith(script_name):
path_info = path_info[len(script_name) :]
env... | 152 | 1,114 | 622 | 1,736 | from __future__ import annotations
import io
import math
import sys
import typing
import warnings
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette.types import Receive, Scope, Send
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future rele... | from __future__ import annotations
import io
import math
import sys
import typing
import warnings
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette.types import Receive, Scope, Send
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future rele... | |
12,474 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/middleware/wsgi.py | 119,125 | 83,157 | start_response | WSGIResponder | 125,143 | 125,143 | class WSGIResponder:
stream_send: ObjectSendStream[typing.MutableMapping[str, typing.Any]]
stream_receive: ObjectReceiveStream[typing.MutableMapping[str, typing.Any]]
def __init__(self, app: typing.Callable[..., typing.Any], scope: Scope) -> None:
self.app = app
self.scope = scope
s... | class WSGIResponder:
stream_send: ObjectSendStream[typing.MutableMapping[str, typing.Any]]
stream_receive: ObjectReceiveStream[typing.MutableMapping[str, typing.Any]]
def __init__(self, app: typing.Callable[..., typing.Any], scope: Scope) -> None:
self.app = app
self.scope = scope
s... | self.exc_info = exc_info
if not self.response_started:
self.response_started = True
status_code_string, _ = status.split(" ", 1)
status_code = int(status_code_string)
headers = [
(name.strip().encode("ascii").lower(), value.strip().encode("... | self.exc_info = exc_info
if not self.response_started:
self.response_started = True
status_code_string, _ = status.split(" ", 1)
status_code = int(status_code_string)
headers = [
(name.strip().encode("ascii").lower(), value.strip().encode("... | 40 | 654 | 184 | 838 | from __future__ import annotations
import io
import math
import sys
import typing
import warnings
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette.types import Receive, Scope, Send
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future rele... | from __future__ import annotations
import io
import math
import sys
import typing
import warnings
import anyio
from anyio.abc import ObjectReceiveStream, ObjectSendStream
from starlette.types import Receive, Scope, Send
warnings.warn(
"starlette.middleware.wsgi is deprecated and will be removed in a future rele... |
12,475 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/responses.py | 314,315 | 271,361 | set_stat_headers | FileResponse | 315,324 | 315,324 | class FileResponse(Response):
chunk_size = 64 * 1024
def __init__(
self,
path: str | os.PathLike[str],
status_code: int = 200,
headers: typing.Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
filena... | class FileResponse(Response):
chunk_size = 64 * 1024
def __init__(
self,
path: str | os.PathLike[str],
status_code: int = 200,
headers: typing.Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
filena... | content_length = str(stat_result.st_size)
last_modified = formatdate(stat_result.st_mtime, usegmt=True)
etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size)
etag = f'"{md5_hexdigest(etag_base.encode(), usedforsecurity=False)}"'
self.headers.setdefault("content-... | content_length = str(stat_result.st_size)
last_modified = formatdate(stat_result.st_mtime, usegmt=True)
etag_base = str(stat_result.st_mtime) + "-" + str(stat_result.st_size)
etag = f'"{md5_hexdigest(etag_base.encode(), usedforsecurity=False)}"'
self.headers.setdefault("content-... | 24 | 920 | 164 | 1,084 | from __future__ import annotations
import http.cookies
import json
import os
import stat
import typing
import warnings
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
import any... | from __future__ import annotations
import http.cookies
import json
import os
import stat
import typing
import warnings
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
import any... |
12,476 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/responses.py | 186,187 | 173,196 | render | JSONResponse | 187,196 | 187,196 | class JSONResponse(Response):
media_type = "application/json"
def __init__(
self,
content: typing.Any,
status_code: int = 200,
headers: typing.Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
) -> None:... | class JSONResponse(Response):
media_type = "application/json"
def __init__(
self,
content: typing.Any,
status_code: int = 200,
headers: typing.Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
) -> None:... | return json.dumps(
content,
ensure_ascii=False,
allow_nan=False,
indent=None,
separators=(",", ":"),
).encode("utf-8")
| return json.dumps(
content,
ensure_ascii=False,
allow_nan=False,
indent=None,
separators=(",", ":"),
).encode("utf-8")
| 9 | 146 | 68 | 214 | from __future__ import annotations
import http.cookies
import json
import os
import stat
import typing
import warnings
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
import any... | from __future__ import annotations
import http.cookies
import json
import os
import stat
import typing
import warnings
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
import any... |
12,477 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/responses.py | 51,52 | 25,165 | init_headers | Response | 52,85 | 52,85 | class Response:
media_type = None
charset = "utf-8"
def __init__(
self,
content: typing.Any = None,
status_code: int = 200,
headers: typing.Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
) -> None... | class Response:
media_type = None
charset = "utf-8"
def __init__(
self,
content: typing.Any = None,
status_code: int = 200,
headers: typing.Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
) -> None... | if headers is None:
raw_headers: list[tuple[bytes, bytes]] = []
populate_content_length = True
populate_content_type = True
else:
raw_headers = [
(k.lower().encode("latin-1"), v.encode("latin-1"))
for k, v in headers.items()... | if headers is None:
raw_headers: list[tuple[bytes, bytes]] = []
populate_content_length = True
populate_content_type = True
else:
raw_headers = [
(k.lower().encode("latin-1"), v.encode("latin-1"))
for k, v in headers.items()... | 105 | 1,050 | 404 | 1,454 | from __future__ import annotations
import http.cookies
import json
import os
import stat
import typing
import warnings
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
import any... | from __future__ import annotations
import http.cookies
import json
import os
import stat
import typing
import warnings
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
import any... |
12,478 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/responses.py | 242,243 | 216,271 | stream_response | StreamingResponse | 243,257 | 243,257 | class StreamingResponse(Response):
body_iterator: AsyncContentStream
def __init__(
self,
content: ContentStream,
status_code: int = 200,
headers: typing.Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
... | class StreamingResponse(Response):
body_iterator: AsyncContentStream
def __init__(
self,
content: ContentStream,
status_code: int = 200,
headers: typing.Mapping[str, str] | None = None,
media_type: str | None = None,
background: BackgroundTask | None = None,
... | await send(
{
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
async for chunk in self.body_iterator:
if not isinstance(chunk, (bytes, memoryview)):
chun... | await send(
{
"type": "http.response.start",
"status": self.status_code,
"headers": self.raw_headers,
}
)
async for chunk in self.body_iterator:
if not isinstance(chunk, (bytes, memoryview)):
chun... | 38 | 424 | 161 | 585 | from __future__ import annotations
import http.cookies
import json
import os
import stat
import typing
import warnings
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
import any... | from __future__ import annotations
import http.cookies
import json
import os
import stat
import typing
import warnings
from datetime import datetime
from email.utils import format_datetime, formatdate
from functools import partial
from mimetypes import guess_type
from urllib.parse import quote
import anyio
import any... |
12,479 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/schemas.py | 38,39 | 34,130 | get_endpoints | BaseSchemaGenerator | 49,89 | 39,89 | class BaseSchemaGenerator:
def get_schema(self, routes: list[BaseRoute]) -> dict[str, typing.Any]:
raise NotImplementedError() # pragma: no cover
def get_endpoints(self, routes: list[BaseRoute]) -> list[EndpointInfo]:
FILL_FUNC_BODY def _remove_converter(self, path: str) -> str:
"""
... | class BaseSchemaGenerator:
def get_schema(self, routes: list[BaseRoute]) -> dict[str, typing.Any]:
raise NotImplementedError() # pragma: no cover
def get_endpoints(self, routes: list[BaseRoute]) -> list[EndpointInfo]:
"""
Given the routes, yields the following information:
- p... | endpoints_info: list[EndpointInfo] = []
for route in routes:
if isinstance(route, (Mount, Host)):
routes = route.routes or []
if isinstance(route, Mount):
path = self._remove_converter(route.path)
else:
... | """
Given the routes, yields the following information:
- path
eg: /users/
- http_method
one of 'get', 'post', 'put', 'patch', 'delete', 'options'
- func
method ready to extract the docstring
"""
endpoints_info: list[EndpointIn... | 100 | 549 | 436 | 985 | from __future__ import annotations
import inspect
import re
import typing
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import BaseRoute, Host, Mount, Route
try:
import yaml
except ModuleNotFoundError: # pragma: nocover
yaml = None # type: ignore[ass... | from __future__ import annotations
import inspect
import re
import typing
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import BaseRoute, Host, Mount, Route
try:
import yaml
except ModuleNotFoundError: # pragma: nocover
yaml = None # type: ignore[ass... |
12,480 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/schemas.py | 20,21 | 17,28 | render | OpenAPIResponse | 21,28 | 21,28 | class OpenAPIResponse(Response):
media_type = "application/vnd.oai.openapi"
def render(self, content: typing.Any) -> bytes:
FILL_FUNC_BODY | class OpenAPIResponse(Response):
media_type = "application/vnd.oai.openapi"
def render(self, content: typing.Any) -> bytes:
FILL_FUNC_BODY | assert yaml is not None, "`pyyaml` must be installed to use OpenAPIResponse."
assert isinstance(
content, dict
), "The schema passed to OpenAPIResponse should be a dictionary."
return yaml.dump(content, default_flow_style=False).encode("utf-8")
| assert yaml is not None, "`pyyaml` must be installed to use OpenAPIResponse."
assert isinstance(
content, dict
), "The schema passed to OpenAPIResponse should be a dictionary."
return yaml.dump(content, default_flow_style=False).encode("utf-8")
| 29 | 54 | 84 | 138 | from __future__ import annotations
import inspect
import re
import typing
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import BaseRoute, Host, Mount, Route
try:
import yaml
except ModuleNotFoundError: # pragma: nocover
yaml = None # type: ignore[ass... | from __future__ import annotations
import inspect
import re
import typing
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import BaseRoute, Host, Mount, Route
try:
import yaml
except ModuleNotFoundError: # pragma: nocover
yaml = None # type: ignore[ass... |
12,481 | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette | /home/hieuvd/dung_repo/raw/stars_01/encode_starlette/starlette/starlette/schemas.py | 134,135 | 130,151 | get_schema | SchemaGenerator | 135,151 | 135,151 | class SchemaGenerator(BaseSchemaGenerator):
def __init__(self, base_schema: dict[str, typing.Any]) -> None:
self.base_schema = base_schema
def get_schema(self, routes: list[BaseRoute]) -> dict[str, typing.Any]:
FILL_FUNC_BODY | class SchemaGenerator(BaseSchemaGenerator):
def __init__(self, base_schema: dict[str, typing.Any]) -> None:
self.base_schema = base_schema
def get_schema(self, routes: list[BaseRoute]) -> dict[str, typing.Any]:
FILL_FUNC_BODY | schema = dict(self.base_schema)
schema.setdefault("paths", {})
endpoints_info = self.get_endpoints(routes)
for endpoint in endpoints_info:
parsed = self.parse_docstring(endpoint.func)
if not parsed:
continue
if endpoint.path not in s... | schema = dict(self.base_schema)
schema.setdefault("paths", {})
endpoints_info = self.get_endpoints(routes)
for endpoint in endpoints_info:
parsed = self.parse_docstring(endpoint.func)
if not parsed:
continue
if endpoint.path not in s... | 32 | 82 | 148 | 230 | from __future__ import annotations
import inspect
import re
import typing
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import BaseRoute, Host, Mount, Route
try:
import yaml
except ModuleNotFoundError: # pragma: nocover
yaml = None # type: ignore[ass... | from __future__ import annotations
import inspect
import re
import typing
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import BaseRoute, Host, Mount, Route
try:
import yaml
except ModuleNotFoundError: # pragma: nocover
yaml = None # type: ignore[ass... |
12,484 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/_subprocess.py | 21,26 | 1,80 | get_subprocess | 36,54 | 26,54 | """
Some light wrappers around Python's multiprocessing, to deal with cleanly
starting child processes.
"""
from __future__ import annotations
import multiprocessing
import os
import sys
from multiprocessing.context import SpawnProcess
from socket import socket
from typing import Callable
from uvicorn.config import ... | """
Some light wrappers around Python's multiprocessing, to deal with cleanly
starting child processes.
"""
from __future__ import annotations
import multiprocessing
import os
import sys
from multiprocessing.context import SpawnProcess
from socket import socket
from typing import Callable
from uvicorn.config import ... | # We pass across the stdin fileno, and reopen it in the child process.
# This is required for some debugging environments.
try:
stdin_fileno = sys.stdin.fileno()
# The `sys.stdin` can be `None`, see https://docs.python.org/3/library/sys.html#sys.__stdin__.
except (AttributeError, OSError):
... | """
Called in the parent process, to instantiate a new child process instance.
The child is not yet started at this point.
* config - The Uvicorn configuration instance.
* target - A callable that accepts a list of sockets. In practice this will
be the `Server.run()` method.
* so... | 55 | 567 | 203 | 770 | """
Some light wrappers around Python's multiprocessing, to deal with cleanly
starting child processes.
"""
from __future__ import annotations
import multiprocessing
import os
import sys
from multiprocessing.context import SpawnProcess
from socket import socket
from typing import Callable
from uvicorn.config import ... | """
Some light wrappers around Python's multiprocessing, to deal with cleanly
starting child processes.
"""
from __future__ import annotations
import multiprocessing
import os
import sys
from multiprocessing.context import SpawnProcess
from socket import socket
from typing import Callable
from uvicorn.config import ... | |
12,487 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/importer.py | 9,10 | 1,35 | import_from_string | 10,35 | 10,35 | import importlib
from typing import Any
class ImportFromStringError(Exception):
pass
def import_from_string(import_str: Any) -> Any:
FILL_FUNC_BODY | import importlib
from typing import Any
class ImportFromStringError(Exception):
pass
def import_from_string(import_str: Any) -> Any:
FILL_FUNC_BODY | if not isinstance(import_str, str):
return import_str
module_str, _, attrs_str = import_str.partition(":")
if not module_str or not attrs_str:
message = 'Import string "{import_str}" must be in format "<module>:<attribute>".'
raise ImportFromStringError(message.format(import_str=imp... | if not isinstance(import_str, str):
return import_str
module_str, _, attrs_str = import_str.partition(":")
if not module_str or not attrs_str:
message = 'Import string "{import_str}" must be in format "<module>:<attribute>".'
raise ImportFromStringError(message.format(import_str=imp... | 82 | 53 | 316 | 369 | import importlib
from typing import Any
class ImportFromStringError(Exception):
pass
def import_from_string(import_str: Any) -> Any:
FILL_FUNC_BODY | import importlib
from typing import Any
class ImportFromStringError(Exception):
pass
def import_from_string(import_str: Any) -> Any:
FILL_FUNC_BODY | |
12,488 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/lifespan/on.py | 47,48 | 31,138 | startup | LifespanOn | 48,64 | 48,64 | class LifespanOn:
def __init__(self, config: Config) -> None:
if not config.loaded:
config.load()
self.config = config
self.logger = logging.getLogger("uvicorn.error")
self.startup_event = asyncio.Event()
self.shutdown_event = asyncio.Event()
self.receive... | class LifespanOn:
def __init__(self, config: Config) -> None:
if not config.loaded:
config.load()
self.config = config
self.logger = logging.getLogger("uvicorn.error")
self.startup_event = asyncio.Event()
self.shutdown_event = asyncio.Event()
self.receive... | self.logger.info("Waiting for application startup.")
loop = asyncio.get_event_loop()
main_lifespan_task = loop.create_task(self.main()) # noqa: F841
# Keep a hard reference to prevent garbage collection
# See https://github.com/encode/uvicorn/pull/972
startup_event: Lif... | self.logger.info("Waiting for application startup.")
loop = asyncio.get_event_loop()
main_lifespan_task = loop.create_task(self.main()) # noqa: F841
# Keep a hard reference to prevent garbage collection
# See https://github.com/encode/uvicorn/pull/972
startup_event: Lif... | 53 | 1,108 | 235 | 1,343 | from __future__ import annotations
import asyncio
import logging
from asyncio import Queue
from typing import Any, Union
from uvicorn import Config
from uvicorn._types import (
LifespanScope,
LifespanShutdownCompleteEvent,
LifespanShutdownEvent,
LifespanShutdownFailedEvent,
LifespanStartupComplete... | from __future__ import annotations
import asyncio
import logging
from asyncio import Queue
from typing import Any, Union
from uvicorn import Config
from uvicorn._types import (
LifespanScope,
LifespanShutdownCompleteEvent,
LifespanShutdownEvent,
LifespanShutdownFailedEvent,
LifespanStartupComplete... |
12,489 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/logging.py | 82,83 | 73,118 | get_status_code | AccessFormatter | 83,97 | 83,97 | class AccessFormatter(ColourizedFormatter):
status_code_colours = {
1: lambda code: click.style(str(code), fg="bright_white"),
2: lambda code: click.style(str(code), fg="green"),
3: lambda code: click.style(str(code), fg="yellow"),
4: lambda code: click.style(str(code), fg="red"),
... | class AccessFormatter(ColourizedFormatter):
status_code_colours = {
1: lambda code: click.style(str(code), fg="bright_white"),
2: lambda code: click.style(str(code), fg="green"),
3: lambda code: click.style(str(code), fg="yellow"),
4: lambda code: click.style(str(code), fg="red"),
... | try:
status_phrase = http.HTTPStatus(status_code).phrase
except ValueError:
status_phrase = ""
status_and_phrase = f"{status_code} {status_phrase}"
if self.use_colors:
def default(code: int) -> str:
return status_and_phrase # pragma: ... | try:
status_phrase = http.HTTPStatus(status_code).phrase
except ValueError:
status_phrase = ""
status_and_phrase = f"{status_code} {status_phrase}"
if self.use_colors:
def default(code: int) -> str:
return status_and_phrase # pragma: ... | 36 | 391 | 153 | 544 | from __future__ import annotations
import http
import logging
import sys
from copy import copy
from typing import Literal
import click
TRACE_LOG_LEVEL = 5
class ColourizedFormatter(logging.Formatter):
"""
A custom log formatter class that:
* Outputs the LOG_LEVEL with an appropriate color.
* If a ... | from __future__ import annotations
import http
import logging
import sys
from copy import copy
from typing import Literal
import click
TRACE_LOG_LEVEL = 5
class ColourizedFormatter(logging.Formatter):
"""
A custom log formatter class that:
* Outputs the LOG_LEVEL with an appropriate color.
* If a ... |
12,490 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/logging.py | 45,46 | 14,68 | color_level_name | ColourizedFormatter | 46,52 | 46,52 | class ColourizedFormatter(logging.Formatter):
"""
A custom log formatter class that:
* Outputs the LOG_LEVEL with an appropriate color.
* If a log call includes an `extras={"color_message": ...}` it will be used
for formatting the output, instead of the plain text message.
"""
level_name... | class ColourizedFormatter(logging.Formatter):
"""
A custom log formatter class that:
* Outputs the LOG_LEVEL with an appropriate color.
* If a log call includes an `extras={"color_message": ...}` it will be used
for formatting the output, instead of the plain text message.
"""
level_name... | def default(level_name: str) -> str:
return str(level_name) # pragma: no cover
func = self.level_name_colors.get(level_no, default)
return func(level_name)
| def default(level_name: str) -> str:
return str(level_name) # pragma: no cover
func = self.level_name_colors.get(level_no, default)
return func(level_name)
| 17 | 656 | 69 | 725 | from __future__ import annotations
import http
import logging
import sys
from copy import copy
from typing import Literal
import click
TRACE_LOG_LEVEL = 5
class ColourizedFormatter(logging.Formatter):
"""
A custom log formatter class that:
* Outputs the LOG_LEVEL with an appropriate color.
* If a ... | from __future__ import annotations
import http
import logging
import sys
from copy import copy
from typing import Literal
import click
TRACE_LOG_LEVEL = 5
class ColourizedFormatter(logging.Formatter):
"""
A custom log formatter class that:
* Outputs the LOG_LEVEL with an appropriate color.
* If a ... |
12,491 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/logging.py | 69,70 | 68,73 | should_use_colors | DefaultFormatter | 70,73 | 70,73 | class DefaultFormatter(ColourizedFormatter):
def should_use_colors(self) -> bool:
FILL_FUNC_BODY | class DefaultFormatter(ColourizedFormatter):
def should_use_colors(self) -> bool:
FILL_FUNC_BODY | return sys.stderr.isatty() # pragma: no cover
| return sys.stderr.isatty() # pragma: no cover
| 6 | 39 | 24 | 63 | from __future__ import annotations
import http
import logging
import sys
from copy import copy
from typing import Literal
import click
TRACE_LOG_LEVEL = 5
class ColourizedFormatter(logging.Formatter):
"""
A custom log formatter class that:
* Outputs the LOG_LEVEL with an appropriate color.
* If a ... | from __future__ import annotations
import http
import logging
import sys
from copy import copy
from typing import Literal
import click
TRACE_LOG_LEVEL = 5
class ColourizedFormatter(logging.Formatter):
"""
A custom log formatter class that:
* Outputs the LOG_LEVEL with an appropriate color.
* If a ... |
12,492 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/loops/asyncio.py | 8,9 | 1,11 | asyncio_setup | 9,11 | 9,11 | import asyncio
import logging
import sys
logger = logging.getLogger("uvicorn.error")
def asyncio_setup(use_subprocess: bool = False) -> None:
FILL_FUNC_BODY | import asyncio
import logging
import sys
logger = logging.getLogger("uvicorn.error")
def asyncio_setup(use_subprocess: bool = False) -> None:
FILL_FUNC_BODY | if sys.platform == "win32" and use_subprocess:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
| if sys.platform == "win32" and use_subprocess:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
| 7 | 57 | 42 | 99 | import asyncio
import logging
import sys
logger = logging.getLogger("uvicorn.error")
def asyncio_setup(use_subprocess: bool = False) -> None:
FILL_FUNC_BODY | import asyncio
import logging
import sys
logger = logging.getLogger("uvicorn.error")
def asyncio_setup(use_subprocess: bool = False) -> None:
FILL_FUNC_BODY | |
12,493 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/loops/auto.py | 1,2 | 1,12 | auto_loop_setup | 2,12 | 2,12 | def auto_loop_setup(use_subprocess: bool = False) -> None:
FILL_FUNC_BODY | def auto_loop_setup(use_subprocess: bool = False) -> None:
FILL_FUNC_BODY | try:
import uvloop # noqa
except ImportError: # pragma: no cover
from uvicorn.loops.asyncio import asyncio_setup as loop_setup
loop_setup(use_subprocess=use_subprocess)
else: # pragma: no cover
from uvicorn.loops.uvloop import uvloop_setup
uvloop_setup(use_subpro... | try:
import uvloop # noqa
except ImportError: # pragma: no cover
from uvicorn.loops.asyncio import asyncio_setup as loop_setup
loop_setup(use_subprocess=use_subprocess)
else: # pragma: no cover
from uvicorn.loops.uvloop import uvloop_setup
uvloop_setup(use_subpro... | 28 | 31 | 126 | 157 | def auto_loop_setup(use_subprocess: bool = False) -> None:
FILL_FUNC_BODY | def auto_loop_setup(use_subprocess: bool = False) -> None:
FILL_FUNC_BODY | |
12,494 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/loops/uvloop.py | 6,7 | 1,8 | uvloop_setup | 7,8 | 7,8 | import asyncio
import uvloop
def uvloop_setup(use_subprocess: bool = False) -> None:
FILL_FUNC_BODY | import asyncio
import uvloop
def uvloop_setup(use_subprocess: bool = False) -> None:
FILL_FUNC_BODY | asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
| asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
| 1 | 43 | 21 | 64 | import asyncio
import uvloop
def uvloop_setup(use_subprocess: bool = False) -> None:
FILL_FUNC_BODY | import asyncio
import uvloop
def uvloop_setup(use_subprocess: bool = False) -> None:
FILL_FUNC_BODY | |
12,495 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/middleware/message_logger.py | 22,23 | 1,88 | message_with_placeholders | 27,36 | 23,36 | import logging
from typing import Any
from uvicorn._types import (
ASGI3Application,
ASGIReceiveCallable,
ASGIReceiveEvent,
ASGISendCallable,
ASGISendEvent,
WWWScope,
)
from uvicorn.logging import TRACE_LOG_LEVEL
PLACEHOLDER_FORMAT = {
"body": "<{length} bytes>",
"bytes": "<{length} by... | import logging
from typing import Any
from uvicorn._types import (
ASGI3Application,
ASGIReceiveCallable,
ASGIReceiveEvent,
ASGISendCallable,
ASGISendEvent,
WWWScope,
)
from uvicorn.logging import TRACE_LOG_LEVEL
PLACEHOLDER_FORMAT = {
"body": "<{length} bytes>",
"bytes": "<{length} by... | new_message = message.copy()
for attr in PLACEHOLDER_FORMAT.keys():
if message.get(attr) is not None:
content = message[attr]
placeholder = PLACEHOLDER_FORMAT[attr].format(length=len(content))
new_message[attr] = placeholder
return new_message
| """
Return an ASGI message, with any body-type content omitted and replaced
with a placeholder.
"""
new_message = message.copy()
for attr in PLACEHOLDER_FORMAT.keys():
if message.get(attr) is not None:
content = message[attr]
placeholder = PLACEHOLDER_FORMAT[attr]... | 23 | 809 | 95 | 904 | import logging
from typing import Any
from uvicorn._types import (
ASGI3Application,
ASGIReceiveCallable,
ASGIReceiveEvent,
ASGISendCallable,
ASGISendEvent,
WWWScope,
)
from uvicorn.logging import TRACE_LOG_LEVEL
PLACEHOLDER_FORMAT = {
"body": "<{length} bytes>",
"bytes": "<{length} by... | import logging
from typing import Any
from uvicorn._types import (
ASGI3Application,
ASGIReceiveCallable,
ASGIReceiveEvent,
ASGISendCallable,
ASGISendEvent,
WWWScope,
)
from uvicorn.logging import TRACE_LOG_LEVEL
PLACEHOLDER_FORMAT = {
"body": "<{length} bytes>",
"bytes": "<{length} by... | |
12,496 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/middleware/message_logger.py | 68,69 | 36,88 | inner_send | MessageLoggerMiddleware | 69,76 | 69,76 | class MessageLoggerMiddleware:
def __init__(self, app: "ASGI3Application"):
self.task_counter = 0
self.app = app
self.logger = logging.getLogger("uvicorn.asgi")
def trace(message: Any, *args: Any, **kwargs: Any) -> None:
self.logger.log(TRACE_LOG_LEVEL, message, *args, *... | class MessageLoggerMiddleware:
def __init__(self, app: "ASGI3Application"):
self.task_counter = 0
self.app = app
self.logger = logging.getLogger("uvicorn.asgi")
def trace(message: Any, *args: Any, **kwargs: Any) -> None:
self.logger.log(TRACE_LOG_LEVEL, message, *args, *... | logged_message = message_with_placeholders(message)
log_text = "%s [%d] Send %s"
self.logger.trace( # type: ignore
log_text, prefix, task_counter, logged_message
)
await send(message)
| logged_message = message_with_placeholders(message)
log_text = "%s [%d] Send %s"
self.logger.trace( # type: ignore
log_text, prefix, task_counter, logged_message
)
await send(message)
| 20 | 541 | 77 | 618 | import logging
from typing import Any
from uvicorn._types import (
ASGI3Application,
ASGIReceiveCallable,
ASGIReceiveEvent,
ASGISendCallable,
ASGISendEvent,
WWWScope,
)
from uvicorn.logging import TRACE_LOG_LEVEL
PLACEHOLDER_FORMAT = {
"body": "<{length} bytes>",
"bytes": "<{length} by... | import logging
from typing import Any
from uvicorn._types import (
ASGI3Application,
ASGIReceiveCallable,
ASGIReceiveEvent,
ASGISendCallable,
ASGISendEvent,
WWWScope,
)
from uvicorn.logging import TRACE_LOG_LEVEL
PLACEHOLDER_FORMAT = {
"body": "<{length} bytes>",
"bytes": "<{length} by... |
12,497 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/middleware/proxy_headers.py | 32,33 | 19,71 | get_trusted_client_host | ProxyHeadersMiddleware | 33,42 | 33,42 | class ProxyHeadersMiddleware:
def __init__(
self,
app: ASGI3Application,
trusted_hosts: list[str] | str = "127.0.0.1",
) -> None:
self.app = app
if isinstance(trusted_hosts, str):
self.trusted_hosts = {item.strip() for item in trusted_hosts.split(",")}
... | class ProxyHeadersMiddleware:
def __init__(
self,
app: ASGI3Application,
trusted_hosts: list[str] | str = "127.0.0.1",
) -> None:
self.app = app
if isinstance(trusted_hosts, str):
self.trusted_hosts = {item.strip() for item in trusted_hosts.split(",")}
... | if self.always_trust:
return x_forwarded_for_hosts[0]
for host in reversed(x_forwarded_for_hosts):
if host not in self.trusted_hosts:
return host
return None
| if self.always_trust:
return x_forwarded_for_hosts[0]
for host in reversed(x_forwarded_for_hosts):
if host not in self.trusted_hosts:
return host
return None
| 17 | 653 | 76 | 729 | """
This middleware can be used when a known proxy is fronting the application,
and is trusted to be properly setting the `X-Forwarded-Proto` and
`X-Forwarded-For` headers with the connecting client information.
Modifies the `client` and `scheme` information so that they reference
the connecting client, rather that th... | """
This middleware can be used when a known proxy is fronting the application,
and is trusted to be properly setting the `X-Forwarded-Proto` and
`X-Forwarded-For` headers with the connecting client information.
Modifies the `client` and `scheme` information so that they reference
the connecting client, rather that th... |
12,498 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/protocols/http/flow_control.py | 42,43 | 1,55 | service_unavailable | 43,55 | 43,55 | import asyncio
from uvicorn._types import ASGIReceiveCallable, ASGISendCallable, Scope
CLOSE_HEADER = (b"connection", b"close")
HIGH_WATER_LIMIT = 65536
class FlowControl:
def __init__(self, transport: asyncio.Transport) -> None:
self._transport = transport
self.read_paused = False
self... | import asyncio
from uvicorn._types import ASGIReceiveCallable, ASGISendCallable, Scope
CLOSE_HEADER = (b"connection", b"close")
HIGH_WATER_LIMIT = 65536
class FlowControl:
def __init__(self, transport: asyncio.Transport) -> None:
self._transport = transport
self.read_paused = False
self... | await send(
{
"type": "http.response.start",
"status": 503,
"headers": [
(b"content-type", b"text/plain; charset=utf-8"),
(b"content-length", b"19"),
(b"connection", b"close"),
],
}
)
await send({... | await send(
{
"type": "http.response.start",
"status": 503,
"headers": [
(b"content-type", b"text/plain; charset=utf-8"),
(b"content-length", b"19"),
(b"connection", b"close"),
],
}
)
await send({... | 27 | 407 | 134 | 541 | import asyncio
from uvicorn._types import ASGIReceiveCallable, ASGISendCallable, Scope
CLOSE_HEADER = (b"connection", b"close")
HIGH_WATER_LIMIT = 65536
class FlowControl:
def __init__(self, transport: asyncio.Transport) -> None:
self._transport = transport
self.read_paused = False
self... | import asyncio
from uvicorn._types import ASGIReceiveCallable, ASGISendCallable, Scope
CLOSE_HEADER = (b"connection", b"close")
HIGH_WATER_LIMIT = 65536
class FlowControl:
def __init__(self, transport: asyncio.Transport) -> None:
self._transport = transport
self.read_paused = False
self... | |
12,499 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/protocols/http/flow_control.py | 18,19 | 10,42 | drain | FlowControl | 19,21 | 19,21 | class FlowControl:
def __init__(self, transport: asyncio.Transport) -> None:
self._transport = transport
self.read_paused = False
self.write_paused = False
self._is_writable_event = asyncio.Event()
self._is_writable_event.set()
async def drain(self) -> None:
FILL_FUNC_BO... | class FlowControl:
def __init__(self, transport: asyncio.Transport) -> None:
self._transport = transport
self.read_paused = False
self.write_paused = False
self._is_writable_event = asyncio.Event()
self._is_writable_event.set()
async def drain(self) -> None:
FILL_FUNC_BO... | await self._is_writable_event.wait()
| await self._is_writable_event.wait()
| 2 | 290 | 17 | 307 | import asyncio
from uvicorn._types import ASGIReceiveCallable, ASGISendCallable, Scope
CLOSE_HEADER = (b"connection", b"close")
HIGH_WATER_LIMIT = 65536
class FlowControl:
def __init__(self, transport: asyncio.Transport) -> None:
self._transport = transport
self.read_paused = False
self... | import asyncio
from uvicorn._types import ASGIReceiveCallable, ASGISendCallable, Scope
CLOSE_HEADER = (b"connection", b"close")
HIGH_WATER_LIMIT = 65536
class FlowControl:
def __init__(self, transport: asyncio.Transport) -> None:
self._transport = transport
self.read_paused = False
self... |
12,502 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/protocols/http/h11_impl.py | 525,526 | 366,548 | receive | RequestResponseCycle | 526,548 | 526,548 | class RequestResponseCycle:
def __init__(
self,
scope: HTTPScope,
conn: h11.Connection,
transport: asyncio.Transport,
flow: FlowControl,
logger: logging.Logger,
access_logger: logging.Logger,
access_log: bool,
default_headers: list[tuple[bytes,... | class RequestResponseCycle:
def __init__(
self,
scope: HTTPScope,
conn: h11.Connection,
transport: asyncio.Transport,
flow: FlowControl,
logger: logging.Logger,
access_logger: logging.Logger,
access_log: bool,
default_headers: list[tuple[bytes,... | if self.waiting_for_100_continue and not self.transport.is_closing():
headers: list[tuple[str, str]] = []
event = h11.InformationalResponse(status_code=100, headers=headers, reason="Continue")
output = self.conn.send(event=event)
self.transport.write(output)
... | if self.waiting_for_100_continue and not self.transport.is_closing():
headers: list[tuple[str, str]] = []
event = h11.InformationalResponse(status_code=100, headers=headers, reason="Continue")
output = self.conn.send(event=event)
self.transport.write(output)
... | 55 | 1,613 | 266 | 1,879 | from __future__ import annotations
import asyncio
import http
import logging
from typing import Any, Callable, Literal, cast
from urllib.parse import unquote
import h11
from h11._connection import DEFAULT_MAX_INCOMPLETE_EVENT_SIZE
from uvicorn._types import (
ASGI3Application,
ASGIReceiveEvent,
ASGISendE... | from __future__ import annotations
import asyncio
import http
import logging
from typing import Any, Callable, Literal, cast
from urllib.parse import unquote
import h11
from h11._connection import DEFAULT_MAX_INCOMPLETE_EVENT_SIZE
from uvicorn._types import (
ASGI3Application,
ASGIReceiveEvent,
ASGISendE... |
12,503 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/protocols/utils.py | 12,13 | 1,57 | get_remote_addr | 13,29 | 13,29 | from __future__ import annotations
import asyncio
import urllib.parse
from uvicorn._types import WWWScope
class ClientDisconnected(IOError): ...
def get_remote_addr(transport: asyncio.Transport) -> tuple[str, int] | None:
FILL_FUNC_BODYdef get_local_addr(transport: asyncio.Transport) -> tuple[str, int] | None:
... | from __future__ import annotations
import asyncio
import urllib.parse
from uvicorn._types import WWWScope
class ClientDisconnected(IOError): ...
def get_remote_addr(transport: asyncio.Transport) -> tuple[str, int] | None:
FILL_FUNC_BODYdef get_local_addr(transport: asyncio.Transport) -> tuple[str, int] | None:
... | socket_info = transport.get_extra_info("socket")
if socket_info is not None:
try:
info = socket_info.getpeername()
return (str(info[0]), int(info[1])) if isinstance(info, tuple) else None
except OSError: # pragma: no cover
# This case appears to inconsistentl... | socket_info = transport.get_extra_info("socket")
if socket_info is not None:
try:
info = socket_info.getpeername()
return (str(info[0]), int(info[1])) if isinstance(info, tuple) else None
except OSError: # pragma: no cover
# This case appears to inconsistentl... | 65 | 431 | 194 | 625 | from __future__ import annotations
import asyncio
import urllib.parse
from uvicorn._types import WWWScope
class ClientDisconnected(IOError): ...
def get_remote_addr(transport: asyncio.Transport) -> tuple[str, int] | None:
FILL_FUNC_BODYdef get_local_addr(transport: asyncio.Transport) -> tuple[str, int] | None:
... | from __future__ import annotations
import asyncio
import urllib.parse
from uvicorn._types import WWWScope
class ClientDisconnected(IOError): ...
def get_remote_addr(transport: asyncio.Transport) -> tuple[str, int] | None:
FILL_FUNC_BODYdef get_local_addr(transport: asyncio.Transport) -> tuple[str, int] | None:
... | |
12,506 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/supervisors/basereload.py | 117,118 | 1,122 | _display_path | 118,122 | 118,122 | from __future__ import annotations
import logging
import os
import signal
import sys
import threading
from pathlib import Path
from socket import socket
from types import FrameType
from typing import Callable, Iterator
import click
from uvicorn._subprocess import get_subprocess
from uvicorn.config import Config
HAN... | from __future__ import annotations
import logging
import os
import signal
import sys
import threading
from pathlib import Path
from socket import socket
from types import FrameType
from typing import Callable, Iterator
import click
from uvicorn._subprocess import get_subprocess
from uvicorn.config import Config
HAN... | try:
return f"'{path.relative_to(Path.cwd())}'"
except ValueError:
return f"'{path}'"
| try:
return f"'{path.relative_to(Path.cwd())}'"
except ValueError:
return f"'{path}'"
| 7 | 1,172 | 42 | 1,214 | from __future__ import annotations
import logging
import os
import signal
import sys
import threading
from pathlib import Path
from socket import socket
from types import FrameType
from typing import Callable, Iterator
import click
from uvicorn._subprocess import get_subprocess
from uvicorn.config import Config
HAN... | from __future__ import annotations
import logging
import os
import signal
import sys
import threading
from pathlib import Path
from socket import socket
from types import FrameType
from typing import Callable, Iterator
import click
from uvicorn._subprocess import get_subprocess
from uvicorn.config import Config
HAN... | |
12,507 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/supervisors/basereload.py | 99,100 | 26,117 | shutdown | BaseReload | 100,113 | 100,113 | class BaseReload:
def __init__(
self,
config: Config,
target: Callable[[list[socket] | None], None],
sockets: list[socket],
) -> None:
self.config = config
self.target = target
self.sockets = sockets
self.should_exit = threading.Event()
sel... | class BaseReload:
def __init__(
self,
config: Config,
target: Callable[[list[socket] | None], None],
sockets: list[socket],
) -> None:
self.config = config
self.target = target
self.sockets = sockets
self.should_exit = threading.Event()
sel... | if sys.platform == "win32":
self.should_exit.set() # pragma: py-not-win32
else:
self.process.terminate() # pragma: py-win32
self.process.join()
for sock in self.sockets:
sock.close()
message = f"Stopping reloader process [{str(self.pid)}]"
... | if sys.platform == "win32":
self.should_exit.set() # pragma: py-not-win32
else:
self.process.terminate() # pragma: py-win32
self.process.join()
for sock in self.sockets:
sock.close()
message = f"Stopping reloader process [{str(self.pid)}]"
... | 36 | 834 | 177 | 1,011 | from __future__ import annotations
import logging
import os
import signal
import sys
import threading
from pathlib import Path
from socket import socket
from types import FrameType
from typing import Callable, Iterator
import click
from uvicorn._subprocess import get_subprocess
from uvicorn.config import Config
HAN... | from __future__ import annotations
import logging
import os
import signal
import sys
import threading
from pathlib import Path
from socket import socket
from types import FrameType
from typing import Callable, Iterator
import click
from uvicorn._subprocess import get_subprocess
from uvicorn.config import Config
HAN... |
12,508 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/supervisors/multiprocess.py | 63,64 | 25,71 | shutdown | Multiprocess | 64,71 | 64,71 | class Multiprocess:
def __init__(
self,
config: Config,
target: Callable[[list[socket] | None], None],
sockets: list[socket],
) -> None:
self.config = config
self.target = target
self.sockets = sockets
self.processes: list[SpawnProcess] = []
... | class Multiprocess:
def __init__(
self,
config: Config,
target: Callable[[list[socket] | None], None],
sockets: list[socket],
) -> None:
self.config = config
self.target = target
self.sockets = sockets
self.processes: list[SpawnProcess] = []
... | for process in self.processes:
process.terminate()
process.join()
message = f"Stopping parent process [{str(self.pid)}]"
color_message = "Stopping parent process [{}]".format(click.style(str(self.pid), fg="cyan", bold=True))
logger.info(message, extra={"color_mes... | for process in self.processes:
process.terminate()
process.join()
message = f"Stopping parent process [{str(self.pid)}]"
color_message = "Stopping parent process [{}]".format(click.style(str(self.pid), fg="cyan", bold=True))
logger.info(message, extra={"color_mes... | 23 | 409 | 107 | 516 | from __future__ import annotations
import logging
import os
import signal
import threading
from multiprocessing.context import SpawnProcess
from socket import socket
from types import FrameType
from typing import Callable
import click
from uvicorn._subprocess import get_subprocess
from uvicorn.config import Config
... | from __future__ import annotations
import logging
import os
import signal
import threading
from multiprocessing.context import SpawnProcess
from socket import socket
from types import FrameType
from typing import Callable
import click
from uvicorn._subprocess import get_subprocess
from uvicorn.config import Config
... |
12,509 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/supervisors/statreload.py | 49,50 | 14,53 | iter_py_files | StatReload | 50,53 | 50,53 | class StatReload(BaseReload):
def __init__(
self,
config: Config,
target: Callable[[list[socket] | None], None],
sockets: list[socket],
) -> None:
super().__init__(config, target, sockets)
self.reloader_name = "StatReload"
self.mtimes: dict[Path, float] = ... | class StatReload(BaseReload):
def __init__(
self,
config: Config,
target: Callable[[list[socket] | None], None],
sockets: list[socket],
) -> None:
super().__init__(config, target, sockets)
self.reloader_name = "StatReload"
self.mtimes: dict[Path, float] = ... | for reload_dir in self.config.reload_dirs:
for path in list(reload_dir.rglob("*.py")):
yield path.resolve()
| for reload_dir in self.config.reload_dirs:
for path in list(reload_dir.rglob("*.py")):
yield path.resolve()
| 10 | 342 | 47 | 389 | from __future__ import annotations
import logging
from pathlib import Path
from socket import socket
from typing import Callable, Iterator
from uvicorn.config import Config
from uvicorn.supervisors.basereload import BaseReload
logger = logging.getLogger("uvicorn.error")
class StatReload(BaseReload):
def __init... | from __future__ import annotations
import logging
from pathlib import Path
from socket import socket
from typing import Callable, Iterator
from uvicorn.config import Config
from uvicorn.supervisors.basereload import BaseReload
logger = logging.getLogger("uvicorn.error")
class StatReload(BaseReload):
def __init... |
12,510 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/supervisors/watchfilesreload.py | 81,82 | 55,89 | should_restart | WatchFilesReload | 82,89 | 82,89 | class WatchFilesReload(BaseReload):
def __init__(
self,
config: Config,
target: Callable[[list[socket] | None], None],
sockets: list[socket],
) -> None:
super().__init__(config, target, sockets)
self.reloader_name = "WatchFiles"
self.reload_dirs = []
... | class WatchFilesReload(BaseReload):
def __init__(
self,
config: Config,
target: Callable[[list[socket] | None], None],
sockets: list[socket],
) -> None:
super().__init__(config, target, sockets)
self.reloader_name = "WatchFiles"
self.reload_dirs = []
... | self.pause()
changes = next(self.watcher)
if changes:
unique_paths = {Path(c[1]) for c in changes}
return [p for p in unique_paths if self.watch_filter(p)]
return None
| self.pause()
changes = next(self.watcher)
if changes:
unique_paths = {Path(c[1]) for c in changes}
return [p for p in unique_paths if self.watch_filter(p)]
return None
| 23 | 303 | 73 | 376 | from __future__ import annotations
from pathlib import Path
from socket import socket
from typing import Callable
from watchfiles import watch
from uvicorn.config import Config
from uvicorn.supervisors.basereload import BaseReload
class FileFilter:
def __init__(self, config: Config):
default_includes =... | from __future__ import annotations
from pathlib import Path
from socket import socket
from typing import Callable
from watchfiles import watch
from uvicorn.config import Config
from uvicorn.supervisors.basereload import BaseReload
class FileFilter:
def __init__(self, config: Config):
default_includes =... |
12,511 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/supervisors/watchgodreload.py | 66,67 | 22,121 | should_watch_dir | CustomWatcher | 67,121 | 67,121 | class CustomWatcher(DefaultWatcher):
def __init__(self, root_path: Path, config: Config):
default_includes = ["*.py"]
self.includes = [default for default in default_includes if default not in config.reload_excludes]
self.includes.extend(config.reload_includes)
self.includes = list(s... | class CustomWatcher(DefaultWatcher):
def __init__(self, root_path: Path, config: Config):
default_includes = ["*.py"]
self.includes = [default for default in default_includes if default not in config.reload_excludes]
self.includes.extend(config.reload_includes)
self.includes = list(s... | cached_result = self.watched_dirs.get(entry.path)
if cached_result is not None:
return cached_result
entry_path = Path(entry)
if entry_path in self.dirs_excludes:
self.watched_dirs[entry.path] = False
return False
for exclude_pattern in self... | cached_result = self.watched_dirs.get(entry.path)
if cached_result is not None:
return cached_result
entry_path = Path(entry)
if entry_path in self.dirs_excludes:
self.watched_dirs[entry.path] = False
return False
for exclude_pattern in self... | 132 | 594 | 560 | 1,154 | from __future__ import annotations
import logging
import warnings
from pathlib import Path
from socket import socket
from typing import TYPE_CHECKING, Callable
from watchgod import DefaultWatcher
from uvicorn.config import Config
from uvicorn.supervisors.basereload import BaseReload
if TYPE_CHECKING:
import os
... | from __future__ import annotations
import logging
import warnings
from pathlib import Path
from socket import socket
from typing import TYPE_CHECKING, Callable
from watchgod import DefaultWatcher
from uvicorn.config import Config
from uvicorn.supervisors.basereload import BaseReload
if TYPE_CHECKING:
import os
... |
12,512 | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn | /home/hieuvd/dung_repo/raw/stars_01/encode_uvicorn/uvicorn/uvicorn/supervisors/watchgodreload.py | 144,145 | 121,153 | should_restart | WatchGodReload | 145,153 | 145,153 | class WatchGodReload(BaseReload):
def __init__(
self,
config: Config,
target: Callable[[list[socket] | None], None],
sockets: list[socket],
) -> None:
warnings.warn(
'"watchgod" is deprecated, you should switch ' "to watchfiles (`pip install watchfiles`).",
... | class WatchGodReload(BaseReload):
def __init__(
self,
config: Config,
target: Callable[[list[socket] | None], None],
sockets: list[socket],
) -> None:
warnings.warn(
'"watchgod" is deprecated, you should switch ' "to watchfiles (`pip install watchfiles`).",
... | self.pause()
for watcher in self.watchers:
change = watcher.check()
if change != set():
return list({Path(c[1]) for c in change})
return None
| self.pause()
for watcher in self.watchers:
change = watcher.check()
if change != set():
return list({Path(c[1]) for c in change})
return None
| 20 | 280 | 65 | 345 | from __future__ import annotations
import logging
import warnings
from pathlib import Path
from socket import socket
from typing import TYPE_CHECKING, Callable
from watchgod import DefaultWatcher
from uvicorn.config import Config
from uvicorn.supervisors.basereload import BaseReload
if TYPE_CHECKING:
import os
... | from __future__ import annotations
import logging
import warnings
from pathlib import Path
from socket import socket
from typing import TYPE_CHECKING, Callable
from watchgod import DefaultWatcher
from uvicorn.config import Config
from uvicorn.supervisors.basereload import BaseReload
if TYPE_CHECKING:
import os
... |
12,774 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/datasets/coco_to_cityscapes_id.py | 53,54 | 1,96 | cityscapes_to_coco_with_rider | 54,68 | 54,68 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | lookup = {
0: 0, # ... background
1: 2, # bicycle
2: 3, # car
3: 1, # person
4: 7, # train
5: 8, # truck
6: 4, # motorcycle
7: 6, # bus
8: 1, # rider ("person", *rider has human right!*)
}
return lookup[cityscapes_id]
| lookup = {
0: 0, # ... background
1: 2, # bicycle
2: 3, # car
3: 1, # person
4: 7, # train
5: 8, # truck
6: 4, # motorcycle
7: 6, # bus
8: 1, # rider ("person", *rider has human right!*)
}
return lookup[cityscapes_id]
| 48 | 1,061 | 140 | 1,201 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,776 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/datasets/dummy_datasets.py | 28,29 | 1,48 | get_coco_dataset | 30,48 | 29,48 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | ds = AttrDict()
classes = [
'__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant',
'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse',
'sheep', 'cow', 'elephant', 'bear', 'zebra',... | """A dummy COCO dataset that includes only the 'classes' field."""
ds = AttrDict()
classes = [
'__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant',
'stop sign', 'parking meter', 'bench', 'bird', 'cat... | 114 | 312 | 420 | 732 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,781 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/modeling/VGG16.py | 26,27 | 1,76 | add_VGG16_conv5_body | 27,61 | 27,61 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | model.Conv('data', 'conv1_1', 3, 64, 3, pad=1, stride=1)
model.Relu('conv1_1', 'conv1_1')
model.Conv('conv1_1', 'conv1_2', 64, 64, 3, pad=1, stride=1)
model.Relu('conv1_2', 'conv1_2')
model.MaxPool('conv1_2', 'pool1', kernel=2, pad=0, stride=2)
model.Conv('pool1', 'conv2_1', 64, 128, 3, pad=1, s... | model.Conv('data', 'conv1_1', 3, 64, 3, pad=1, stride=1)
model.Relu('conv1_1', 'conv1_1')
model.Conv('conv1_1', 'conv1_2', 64, 64, 3, pad=1, stride=1)
model.Relu('conv1_2', 'conv1_2')
model.MaxPool('conv1_2', 'pool1', kernel=2, pad=0, stride=2)
model.Conv('pool1', 'conv2_1', 64, 128, 3, pad=1, s... | 147 | 506 | 930 | 1,436 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,782 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/modeling/VGG_CNN_M_1024.py | 26,27 | 1,62 | add_VGG_CNN_M_1024_conv5_body | 27,47 | 27,47 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | model.Conv('data', 'conv1', 3, 96, 7, pad=0, stride=2)
model.Relu('conv1', 'conv1')
model.LRN('conv1', 'norm1', size=5, alpha=0.0005, beta=0.75, bias=2.)
model.MaxPool('norm1', 'pool1', kernel=3, pad=0, stride=2)
model.StopGradient('pool1', 'pool1')
# No updates at conv1 and below (norm1 and poo... | model.Conv('data', 'conv1', 3, 96, 7, pad=0, stride=2)
model.Relu('conv1', 'conv1')
model.LRN('conv1', 'norm1', size=5, alpha=0.0005, beta=0.75, bias=2.)
model.MaxPool('norm1', 'pool1', kernel=3, pad=0, stride=2)
model.StopGradient('pool1', 'pool1')
# No updates at conv1 and below (norm1 and poo... | 99 | 530 | 472 | 1,002 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,784 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/modeling/generate_anchors.py | 106,107 | 1,124 | _ratio_enum | 108,117 | 107,117 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | w, h, x_ctr, y_ctr = _whctrs(anchor)
size = w * h
size_ratios = size / ratios
ws = np.round(np.sqrt(size_ratios))
hs = np.round(ws * ratios)
anchors = _mkanchors(ws, hs, x_ctr, y_ctr)
return anchors
| """Enumerate a set of anchors for each aspect ratio wrt an anchor."""
w, h, x_ctr, y_ctr = _whctrs(anchor)
size = w * h
size_ratios = size / ratios
ws = np.round(np.sqrt(size_ratios))
hs = np.round(ws * ratios)
anchors = _mkanchors(ws, hs, x_ctr, y_ctr)
return anchors
| 32 | 1,474 | 108 | 1,582 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,787 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/modeling/name_compat.py | 59,60 | 1,63 | get_new_name | 60,63 | 60,63 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | if func_name in _RENAME:
func_name = _RENAME[func_name]
return func_name
| if func_name in _RENAME:
func_name = _RENAME[func_name]
return func_name
| 9 | 837 | 34 | 871 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,789 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/modeling/rfcn_heads.py | 30,31 | 1,100 | add_rfcn_outputs | 31,100 | 31,100 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | if dim_reduce is not None:
# Optional dim reduction
blob_in = model.Conv(
blob_in,
'conv_dim_reduce',
dim_in,
dim_reduce,
kernel=1,
pad=0,
stride=1,
weight_init=gauss_fill(0.01),
bias_init=con... | if dim_reduce is not None:
# Optional dim reduction
blob_in = model.Conv(
blob_in,
'conv_dim_reduce',
dim_in,
dim_reduce,
kernel=1,
pad=0,
stride=1,
weight_init=gauss_fill(0.01),
bias_init=con... | 127 | 305 | 855 | 1,160 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,790 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/modeling/rpn_heads.py | 55,56 | 1,155 | add_single_scale_rpn_outputs | 57,125 | 56,125 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | anchors = generate_anchors(
stride=1. / spatial_scale,
sizes=cfg.RPN.SIZES,
aspect_ratios=cfg.RPN.ASPECT_RATIOS
)
num_anchors = anchors.shape[0]
dim_out = dim_in
# RPN hidden representation
model.Conv(
blob_in,
'conv_rpn',
dim_in,
dim_out,
... | """Add RPN outputs to a single scale model (i.e., no FPN)."""
anchors = generate_anchors(
stride=1. / spatial_scale,
sizes=cfg.RPN.SIZES,
aspect_ratios=cfg.RPN.ASPECT_RATIOS
)
num_anchors = anchors.shape[0]
dim_out = dim_in
# RPN hidden representation
model.Conv(
... | 145 | 1,116 | 761 | 1,877 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,791 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/ops/collect_and_distribute_fpn_rpn_proposals.py | 91,92 | 1,114 | distribute | 95,114 | 92,114 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | lvl_min = cfg.FPN.ROI_MIN_LEVEL
lvl_max = cfg.FPN.ROI_MAX_LEVEL
lvls = fpn.map_rois_to_fpn_levels(rois[:, 1:5], lvl_min, lvl_max)
outputs[0].reshape(rois.shape)
outputs[0].data[...] = rois
# Create new roi blobs for each FPN level
# (See: modeling.FPN.add_multilevel_roi_blobs which is simi... | """To understand the output blob order see return value of
detectron.roi_data.fast_rcnn.get_fast_rcnn_blob_names(is_training=False)
"""
lvl_min = cfg.FPN.ROI_MIN_LEVEL
lvl_max = cfg.FPN.ROI_MAX_LEVEL
lvls = fpn.map_rois_to_fpn_levels(rois[:, 1:5], lvl_min, lvl_max)
outputs[0].reshape(rois.s... | 79 | 1,264 | 399 | 1,663 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,792 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/ops/collect_and_distribute_fpn_rpn_proposals.py | 35,36 | 31,71 | forward | CollectAndDistributeFpnRpnProposalsOp | 39,71 | 36,71 | class CollectAndDistributeFpnRpnProposalsOp:
def __init__(self, train):
self._train = train
def forward(self, inputs, outputs):
FILL_FUNC_BODY | class CollectAndDistributeFpnRpnProposalsOp:
def __init__(self, train):
self._train = train
def forward(self, inputs, outputs):
"""See modeling.detector.CollectAndDistributeFpnRpnProposals for
inputs/outputs documentation.
"""
FILL_FUNC_BODY | # inputs is
# [rpn_rois_fpn2, ..., rpn_rois_fpn6,
# rpn_roi_probs_fpn2, ..., rpn_roi_probs_fpn6]
# If training with Faster R-CNN, then inputs will additionally include
# + [roidb, im_info]
rois = collect(inputs, self._train)
if self._train:
# During ... | """See modeling.detector.CollectAndDistributeFpnRpnProposals for
inputs/outputs documentation.
"""
# inputs is
# [rpn_rois_fpn2, ..., rpn_rois_fpn6,
# rpn_roi_probs_fpn2, ..., rpn_roi_probs_fpn6]
# If training with Faster R-CNN, then inputs will additionally incl... | 167 | 86 | 541 | 627 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
12,793 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/ops/generate_proposal_labels.py | 33,34 | 31,55 | forward | GenerateProposalLabelsOp | 37,55 | 34,55 | class GenerateProposalLabelsOp:
def forward(self, inputs, outputs):
FILL_FUNC_BODY | class GenerateProposalLabelsOp:
def forward(self, inputs, outputs):
"""See modeling.detector.GenerateProposalLabels for inputs/outputs
documentation.
"""
FILL_FUNC_BODY | # During training we reuse the data loader code. We populate roidb
# entries on the fly using the rois generated by RPN.
# im_info: [[im_height, im_width, im_scale], ...]
rois = inputs[0].data
roidb = blob_utils.deserialize(inputs[1].data)
im_info = inputs[2].data
... | """See modeling.detector.GenerateProposalLabels for inputs/outputs
documentation.
"""
# During training we reuse the data loader code. We populate roidb
# entries on the fly using the rois generated by RPN.
# im_info: [[im_height, im_width, im_scale], ...]
rois = ... | 100 | 61 | 355 | 416 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
12,796 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/roi_data/data_utils.py | 50,53 | 1,126 | get_field_of_anchors | 53,104 | 53,104 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | global _threadlocal_foa
if not hasattr(_threadlocal_foa, 'cache'):
_threadlocal_foa.cache = {}
cache_key = str(stride) + str(anchor_sizes) + str(anchor_aspect_ratios)
if cache_key in _threadlocal_foa.cache:
return _threadlocal_foa.cache[cache_key]
# Anchors at a single feature cell... | global _threadlocal_foa
if not hasattr(_threadlocal_foa, 'cache'):
_threadlocal_foa.cache = {}
cache_key = str(stride) + str(anchor_sizes) + str(anchor_aspect_ratios)
if cache_key in _threadlocal_foa.cache:
return _threadlocal_foa.cache[cache_key]
# Anchors at a single feature cell... | 192 | 751 | 752 | 1,503 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,798 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/roi_data/keypoint_rcnn.py | 37,40 | 1,130 | add_keypoint_rcnn_blobs | 41,94 | 40,94 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Note: gt_inds must match how they're computed in
# datasets.json_dataset._merge_proposal_boxes_into_roidb
gt_inds = np.where(roidb['gt_classes'] > 0)[0]
max_overlaps = roidb['max_overlaps']
gt_keypoints = roidb['gt_keypoints']
ind_kp = gt_inds[roidb['box_to_gt_ind_map']]
within_box = _wit... | """Add Mask R-CNN keypoint specific blobs to the given blobs dictionary."""
# Note: gt_inds must match how they're computed in
# datasets.json_dataset._merge_proposal_boxes_into_roidb
gt_inds = np.where(roidb['gt_classes'] > 0)[0]
max_overlaps = roidb['max_overlaps']
gt_keypoints = roidb['gt_key... | 153 | 961 | 946 | 1,907 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,799 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/roi_data/mask_rcnn.py | 37,38 | 1,127 | add_mask_rcnn_blobs | 39,105 | 38,105 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Prepare the mask targets by associating one gt mask to each training roi
# that has a fg (non-bg) class label.
M = cfg.MRCNN.RESOLUTION
polys_gt_inds = np.where(
(roidb['gt_classes'] > 0) & (roidb['is_crowd'] == 0)
)[0]
polys_gt = [roidb['segms'][i] for i in polys_gt_inds]
boxes_fr... | """Add Mask R-CNN specific blobs to the input blob dictionary."""
# Prepare the mask targets by associating one gt mask to each training roi
# that has a fg (non-bg) class label.
M = cfg.MRCNN.RESOLUTION
polys_gt_inds = np.where(
(roidb['gt_classes'] > 0) & (roidb['is_crowd'] == 0)
)[0]
... | 341 | 694 | 1,196 | 1,890 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,801 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/utils/collections.py | 52,53 | 24,67 | immutable | AttrDict | 56,65 | 53,65 | class AttrDict(dict):
IMMUTABLE = '__immutable__'
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__[AttrDict.IMMUTABLE] = False
def __getattr__(self, name):
if name in self.__dict__:
return self.__dict__[name]
el... | class AttrDict(dict):
IMMUTABLE = '__immutable__'
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__[AttrDict.IMMUTABLE] = False
def __getattr__(self, name):
if name in self.__dict__:
return self.__dict__[name]
el... | self.__dict__[AttrDict.IMMUTABLE] = is_immutable
# Recursively set immutable state
for v in self.__dict__.values():
if isinstance(v, AttrDict):
v.immutable(is_immutable)
for v in self.values():
if isinstance(v, AttrDict):
v.immutabl... | """Set immutability to is_immutable and recursively apply the setting
to all nested AttrDicts.
"""
self.__dict__[AttrDict.IMMUTABLE] = is_immutable
# Recursively set immutable state
for v in self.__dict__.values():
if isinstance(v, AttrDict):
v... | 24 | 328 | 112 | 440 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
12,803 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/utils/coordinator.py | 57,58 | 1,74 | coordinated_get | 58,66 | 58,66 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | while not coordinator.should_stop():
try:
return queue.get(block=True, timeout=1.0)
except Queue.Empty:
continue
raise Exception('Coordinator stopped during get()')
| while not coordinator.should_stop():
try:
return queue.get(block=True, timeout=1.0)
except Queue.Empty:
continue
raise Exception('Coordinator stopped during get()')
| 15 | 517 | 66 | 583 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,804 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/utils/coordinator.py | 47,49 | 32,57 | stop_on_exception | Coordinator | 49,57 | 49,57 | class Coordinator:
def __init__(self):
self._event = threading.Event()
def request_stop(self):
log.debug('Coordinator stopping')
self._event.set()
def should_stop(self):
return self._event.is_set()
def wait_for_stop(self):
return self._event.wait()
@conte... | class Coordinator:
def __init__(self):
self._event = threading.Event()
def request_stop(self):
log.debug('Coordinator stopping')
self._event.set()
def should_stop(self):
return self._event.is_set()
def wait_for_stop(self):
return self._event.wait()
@conte... | try:
yield
except Exception:
if not self.should_stop():
traceback.print_exc()
self.request_stop()
| try:
yield
except Exception:
if not self.should_stop():
traceback.print_exc()
self.request_stop()
| 9 | 127 | 49 | 176 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
12,805 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/utils/env.py | 62,63 | 1,92 | get_detectron_ops_lib | 64,78 | 63,78 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Candidate prefixes for detectron ops lib path
prefixes = [_CMAKE_INSTALL_PREFIX, sys.prefix, sys.exec_prefix] + sys.path
# Candidate subdirs for detectron ops lib
subdirs = ['lib', 'torch/lib']
# Try to find detectron ops lib
for prefix in prefixes:
for subdir in subdirs:
o... | """Retrieve Detectron ops library."""
# Candidate prefixes for detectron ops lib path
prefixes = [_CMAKE_INSTALL_PREFIX, sys.prefix, sys.exec_prefix] + sys.path
# Candidate subdirs for detectron ops lib
subdirs = ['lib', 'torch/lib']
# Try to find detectron ops lib
for prefix in prefixes:
... | 61 | 703 | 202 | 905 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,806 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/utils/image.py | 35,36 | 1,46 | aspect_ratio_abs | 37,46 | 36,46 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | im_h, im_w = im.shape[:2]
im_area = im_h * im_w
im_ar_w = np.sqrt(im_area * aspect_ratio)
im_ar_h = np.sqrt(im_area / aspect_ratio)
assert np.isclose(im_ar_w / im_ar_h, aspect_ratio)
im_ar = cv2.resize(im, dsize=(int(im_ar_w), int(im_ar_h)))
return im_ar
| """Performs absolute aspect ratio transformation."""
im_h, im_w = im.shape[:2]
im_area = im_h * im_w
im_ar_w = np.sqrt(im_area * aspect_ratio)
im_ar_h = np.sqrt(im_area / aspect_ratio)
assert np.isclose(im_ar_w / im_ar_h, aspect_ratio)
im_ar = cv2.resize(im, dsize=(int(im_ar_w), int(im_ar_... | 31 | 358 | 144 | 502 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,809 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/utils/logging.py | 76,77 | 1,84 | setup_logging | 77,84 | 77,84 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | FORMAT = '%(levelname)s %(filename)s:%(lineno)4d: %(message)s'
# Manually clear root loggers to prevent any module that may have called
# logging.basicConfig() from blocking our logging setup
logging.root.handlers = []
logging.basicConfig(level=logging.INFO, format=FORMAT, stream=sys.stdout)
log... | FORMAT = '%(levelname)s %(filename)s:%(lineno)4d: %(message)s'
# Manually clear root loggers to prevent any module that may have called
# logging.basicConfig() from blocking our logging setup
logging.root.handlers = []
logging.basicConfig(level=logging.INFO, format=FORMAT, stream=sys.stdout)
log... | 36 | 663 | 118 | 781 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,810 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/utils/logging.py | 52,53 | 41,68 | AddValue | SmoothedValue | 53,58 | 53,58 | class SmoothedValue:
"""Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __init__(self, window_size):
self.deque = deque(maxlen=window_size)
self.series = []
self.total = 0.0
self.count = 0
def AddVal... | class SmoothedValue:
"""Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __init__(self, window_size):
self.deque = deque(maxlen=window_size)
self.series = []
self.total = 0.0
self.count = 0
def AddVal... | self.deque.append(value)
self.series.append(value)
self.count += 1
self.total += value
| self.deque.append(value)
self.series.append(value)
self.count += 1
self.total += value
| 8 | 181 | 41 | 222 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
12,811 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/utils/lr_policy.py | 28,29 | 1,132 | get_lr_at_iter | 32,50 | 29,50 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | lr = get_lr_func()(it)
if it < cfg.SOLVER.WARM_UP_ITERS:
method = cfg.SOLVER.WARM_UP_METHOD
if method == 'constant':
warmup_factor = cfg.SOLVER.WARM_UP_FACTOR
elif method == 'linear':
alpha = it / cfg.SOLVER.WARM_UP_ITERS
warmup_factor = cfg.SOLVER.WAR... | """Get the learning rate at iteration it according to the cfg.SOLVER
settings.
"""
lr = get_lr_func()(it)
if it < cfg.SOLVER.WARM_UP_ITERS:
method = cfg.SOLVER.WARM_UP_METHOD
if method == 'constant':
warmup_factor = cfg.SOLVER.WARM_UP_FACTOR
elif method == 'linear... | 56 | 1,367 | 233 | 1,600 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,812 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/utils/subprocess.py | 39,42 | 1,134 | process_in_parallel | 46,106 | 42,106 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Snapshot the current cfg state in order to pass to the inference
# subprocesses
cfg_file = os.path.join(output_dir, '{}_range_config.yaml'.format(tag))
with open(cfg_file, 'w') as f:
envu.yaml_dump(cfg, stream=f)
subprocess_env = os.environ.copy()
processes = []
subinds = np.array_... | """Run the specified binary cfg.NUM_GPUS times in parallel, each time as a
subprocess that uses one GPU. The binary must accept the command line
arguments `--range {start} {end}` that specify a data processing range.
"""
# Snapshot the current cfg state in order to pass to the inference
# subpro... | 214 | 821 | 855 | 1,676 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | |
12,813 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/detectron/utils/timer.py | 45,46 | 34,61 | toc | Timer | 46,55 | 46,55 | class Timer:
"""A simple timer."""
def __init__(self):
self.reset()
def tic(self):
# using time.time instead of time.clock because time time.clock
# does not normalize for multithreading
self.start_time = time.time()
def toc(self, average=True):
FILL_FUNC_BODY def r... | class Timer:
"""A simple timer."""
def __init__(self):
self.reset()
def tic(self):
# using time.time instead of time.clock because time time.clock
# does not normalize for multithreading
self.start_time = time.time()
def toc(self, average=True):
FILL_FUNC_BODY def r... | self.diff = time.time() - self.start_time
self.total_time += self.diff
self.calls += 1
self.average_time = self.total_time / self.calls
if average:
return self.average_time
else:
return self.diff
| self.diff = time.time() - self.start_time
self.total_time += self.diff
self.calls += 1
self.average_time = self.total_time / self.calls
if average:
return self.average_time
else:
return self.diff
| 23 | 153 | 88 | 241 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
12,814 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_Detectron/Detectron/tools/reval.py | 85,86 | 1,112 | do_reval | 86,105 | 86,105 | #!/usr/bin/env python
# Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | #!/usr/bin/env python
# Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | dataset = JsonDataset(dataset_name)
dets = load_object(os.path.join(output_dir, 'detections.pkl'))
# Override config with the one saved in the detections file
if args.cfg_file is not None:
core_config.merge_cfg_from_cfg(core_config.load_cfg(dets['cfg']))
else:
core_config._merge_a_i... | dataset = JsonDataset(dataset_name)
dets = load_object(os.path.join(output_dir, 'detections.pkl'))
# Override config with the one saved in the detections file
if args.cfg_file is not None:
core_config.merge_cfg_from_cfg(core_config.load_cfg(dets['cfg']))
else:
core_config._merge_a_i... | 38 | 801 | 239 | 1,040 | #!/usr/bin/env python
# Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | #!/usr/bin/env python
# Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | |
13,661 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/adversarial/discriminators/base.py | 25,27 | 19,35 | forward | MultiDiscriminator | 27,29 | 27,29 | class MultiDiscriminator(ABC, nn.Module):
"""Base implementation for discriminators composed of sub-discriminators acting at different scales.
"""
def __init__(self):
super().__init__()
@abstractmethod
def forward(self, x: torch.Tensor) -> MultiDiscriminatorOutputType:
FILL_FUNC_BODY @pr... | class MultiDiscriminator(ABC, nn.Module):
"""Base implementation for discriminators composed of sub-discriminators acting at different scales.
"""
def __init__(self):
super().__init__()
@abstractmethod
def forward(self, x: torch.Tensor) -> MultiDiscriminatorOutputType:
FILL_FUNC_BODY @pr... | ...
| ...
| 1 | 140 | 6 | 146 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from abc import ABC, abstractmethod
import typing as tp
import torch
import torch.nn as nn
FeatureMapType = tp.List[to... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from abc import ABC, abstractmethod
import typing as tp
import torch
import torch.nn as nn
FeatureMapType = tp.List[to... |
13,662 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/adversarial/discriminators/mpd.py | 17,18 | 1,107 | get_padding | 18,21 | 18,21 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import torch
import torch.nn as nn
import torch.nn.functional as F
from ...modules import NormConv2... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import torch
import torch.nn as nn
import torch.nn.functional as F
from ...modules import NormConv2... | return int((kernel_size * dilation - dilation) / 2)
| return int((kernel_size * dilation - dilation) / 2)
| 8 | 1,339 | 24 | 1,363 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import torch
import torch.nn as nn
import torch.nn.functional as F
from ...modules import NormConv2... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import torch
import torch.nn as nn
import torch.nn.functional as F
from ...modules import NormConv2... | |
13,663 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/adversarial/discriminators/mpd.py | 99,100 | 79,107 | forward | MultiPeriodDiscriminator | 100,107 | 100,107 | class MultiPeriodDiscriminator(MultiDiscriminator):
"""Multi-Period (MPD) Discriminator.
Args:
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
periods (Sequence[int]): Periods between samples of audio for the sub-discriminators.
**kwar... | class MultiPeriodDiscriminator(MultiDiscriminator):
"""Multi-Period (MPD) Discriminator.
Args:
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
periods (Sequence[int]): Periods between samples of audio for the sub-discriminators.
**kwar... | logits = []
fmaps = []
for disc in self.discriminators:
logit, fmap = disc(x)
logits.append(logit)
fmaps.append(fmap)
return logits, fmaps
| logits = []
fmaps = []
for disc in self.discriminators:
logit, fmap = disc(x)
logits.append(logit)
fmaps.append(fmap)
return logits, fmaps
| 19 | 282 | 71 | 353 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import torch
import torch.nn as nn
import torch.nn.functional as F
from ...modules import NormConv2... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import torch
import torch.nn as nn
import torch.nn.functional as F
from ...modules import NormConv2... |
13,664 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/adversarial/discriminators/mpd.py | 58,59 | 21,79 | forward | PeriodDiscriminator | 59,79 | 59,79 | class PeriodDiscriminator(nn.Module):
"""Period sub-discriminator.
Args:
period (int): Period between samples of audio.
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
n_layers (int): Number of convolutional layers.
kernel_size... | class PeriodDiscriminator(nn.Module):
"""Period sub-discriminator.
Args:
period (int): Period between samples of audio.
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
n_layers (int): Number of convolutional layers.
kernel_size... | fmap = []
# 1d to 2d
b, c, t = x.shape
if t % self.period != 0: # pad first
n_pad = self.period - (t % self.period)
x = F.pad(x, (0, n_pad), 'reflect')
t = t + n_pad
x = x.view(b, c, t // self.period, self.period)
for conv in self.con... | fmap = []
# 1d to 2d
b, c, t = x.shape
if t % self.period != 0: # pad first
n_pad = self.period - (t % self.period)
x = F.pad(x, (0, n_pad), 'reflect')
t = t + n_pad
x = x.view(b, c, t // self.period, self.period)
for conv in self.con... | 71 | 664 | 220 | 884 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import torch
import torch.nn as nn
import torch.nn.functional as F
from ...modules import NormConv2... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import torch
import torch.nn as nn
import torch.nn.functional as F
from ...modules import NormConv2... |
13,665 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/adversarial/discriminators/msd.py | 117,118 | 95,127 | forward | MultiScaleDiscriminator | 118,127 | 118,127 | class MultiScaleDiscriminator(MultiDiscriminator):
"""Multi-Scale (MSD) Discriminator,
Args:
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
downsample_factor (int): Downsampling factor between the different scales.
scale_norms (Sequen... | class MultiScaleDiscriminator(MultiDiscriminator):
"""Multi-Scale (MSD) Discriminator,
Args:
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
downsample_factor (int): Downsampling factor between the different scales.
scale_norms (Sequen... | logits = []
fmaps = []
for i, disc in enumerate(self.discriminators):
if i != 0:
self.downsample(x)
logit, fmap = disc(x)
logits.append(logit)
fmaps.append(fmap)
return logits, fmaps
| logits = []
fmaps = []
for i, disc in enumerate(self.discriminators):
if i != 0:
self.downsample(x)
logit, fmap = disc(x)
logits.append(logit)
fmaps.append(fmap)
return logits, fmaps
| 25 | 352 | 95 | 447 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import numpy as np
import torch
import torch.nn as nn
from ...modules import NormConv1d
from .base ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import numpy as np
import torch
import torch.nn as nn
from ...modules import NormConv1d
from .base ... |
13,666 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/adversarial/discriminators/msd.py | 83,84 | 17,95 | forward | ScaleDiscriminator | 84,95 | 84,95 | class ScaleDiscriminator(nn.Module):
"""Waveform sub-discriminator.
Args:
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
kernel_sizes (Sequence[int]): Kernel sizes for first and last convolutions.
filters (int): Number of initial filt... | class ScaleDiscriminator(nn.Module):
"""Waveform sub-discriminator.
Args:
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
kernel_sizes (Sequence[int]): Kernel sizes for first and last convolutions.
filters (int): Number of initial filt... | fmap = []
for layer in self.convs:
x = layer(x)
x = self.activation(x)
fmap.append(x)
x = self.conv_post(x)
fmap.append(x)
# x = torch.flatten(x, 1, -1)
return x, fmap
| fmap = []
for layer in self.convs:
x = layer(x)
x = self.activation(x)
fmap.append(x)
x = self.conv_post(x)
fmap.append(x)
# x = torch.flatten(x, 1, -1)
return x, fmap
| 27 | 1,219 | 104 | 1,323 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import numpy as np
import torch
import torch.nn as nn
from ...modules import NormConv1d
from .base ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import numpy as np
import torch
import torch.nn as nn
from ...modules import NormConv1d
from .base ... |
13,668 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/adversarial/discriminators/msstftd.py | 81,82 | 22,94 | forward | DiscriminatorSTFT | 82,94 | 82,94 | class DiscriminatorSTFT(nn.Module):
"""STFT sub-discriminator.
Args:
filters (int): Number of filters in convolutions.
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
n_fft (int): Size of FFT for each scale.
hop_length (int): L... | class DiscriminatorSTFT(nn.Module):
"""STFT sub-discriminator.
Args:
filters (int): Number of filters in convolutions.
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
n_fft (int): Size of FFT for each scale.
hop_length (int): L... | fmap = []
z = self.spec_transform(x) # [B, 2, Freq, Frames, 2]
z = torch.cat([z.real, z.imag], dim=1)
z = rearrange(z, 'b c w t -> b c t w')
for i, layer in enumerate(self.convs):
z = layer(z)
z = self.activation(z)
fmap.append(z)
z = ... | fmap = []
z = self.spec_transform(x) # [B, 2, Freq, Frames, 2]
z = torch.cat([z.real, z.imag], dim=1)
z = rearrange(z, 'b c w t -> b c t w')
for i, layer in enumerate(self.convs):
z = layer(z)
z = self.activation(z)
fmap.append(z)
z = ... | 47 | 1,111 | 154 | 1,265 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import torchaudio
import torch
from torch import nn
from einops import rearrange
from ...modules im... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import torchaudio
import torch
from torch import nn
from einops import rearrange
from ...modules im... |
13,669 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/adversarial/discriminators/msstftd.py | 127,128 | 94,135 | forward | MultiScaleSTFTDiscriminator | 128,135 | 128,135 | class MultiScaleSTFTDiscriminator(MultiDiscriminator):
"""Multi-Scale STFT (MS-STFT) discriminator.
Args:
filters (int): Number of filters in convolutions.
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
sep_channels (bool): Separate c... | class MultiScaleSTFTDiscriminator(MultiDiscriminator):
"""Multi-Scale STFT (MS-STFT) discriminator.
Args:
filters (int): Number of filters in convolutions.
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
sep_channels (bool): Separate c... | logits = []
fmaps = []
for disc in self.discriminators:
logit, fmap = disc(x)
logits.append(logit)
fmaps.append(fmap)
return logits, fmaps
| logits = []
fmaps = []
for disc in self.discriminators:
logit, fmap = disc(x)
logits.append(logit)
fmaps.append(fmap)
return logits, fmaps
| 19 | 590 | 71 | 661 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import torchaudio
import torch
from torch import nn
from einops import rearrange
from ...modules im... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
import torchaudio
import torch
from torch import nn
from einops import rearrange
from ...modules im... |
13,671 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/adversarial/losses.py | 67,68 | 26,138 | _save_to_state_dict | AdversarialLoss | 68,73 | 68,73 | class AdversarialLoss(nn.Module):
"""Adversary training wrapper.
Args:
adversary (nn.Module): The adversary module will be used to estimate the logits given the fake and real samples.
We assume here the adversary output is ``Tuple[List[torch.Tensor], List[List[torch.Tensor]]]``
... | class AdversarialLoss(nn.Module):
"""Adversary training wrapper.
Args:
adversary (nn.Module): The adversary module will be used to estimate the logits given the fake and real samples.
We assume here the adversary output is ``Tuple[List[torch.Tensor], List[List[torch.Tensor]]]``
... | # Add the optimizer state dict inside our own.
super()._save_to_state_dict(destination, prefix, keep_vars)
destination[prefix + 'optimizer'] = self.optimizer.state_dict()
return destination
| # Add the optimizer state dict inside our own.
super()._save_to_state_dict(destination, prefix, keep_vars)
destination[prefix + 'optimizer'] = self.optimizer.state_dict()
return destination
| 19 | 1,627 | 65 | 1,692 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""
Utility module to handle adversarial losses without requiring to mess up the main training loop.
"""
import typing a... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""
Utility module to handle adversarial losses without requiring to mess up the main training loop.
"""
import typing a... |
13,672 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/adversarial/losses.py | 214,215 | 201,229 | forward | FeatureMatchingLoss | 215,229 | 215,229 | class FeatureMatchingLoss(nn.Module):
"""Feature matching loss for adversarial training.
Args:
loss (nn.Module): Loss to use for feature matching (default=torch.nn.L1).
normalize (bool): Whether to normalize the loss.
by number of feature maps.
"""
def __init__(self, loss: n... | class FeatureMatchingLoss(nn.Module):
"""Feature matching loss for adversarial training.
Args:
loss (nn.Module): Loss to use for feature matching (default=torch.nn.L1).
normalize (bool): Whether to normalize the loss.
by number of feature maps.
"""
def __init__(self, loss: n... | assert len(fmap_fake) == len(fmap_real) and len(fmap_fake) > 0
feat_loss = torch.tensor(0., device=fmap_fake[0].device)
feat_scale = torch.tensor(0., device=fmap_fake[0].device)
n_fmaps = 0
for (feat_fake, feat_real) in zip(fmap_fake, fmap_real):
assert feat_fake.shap... | assert len(fmap_fake) == len(fmap_real) and len(fmap_fake) > 0
feat_loss = torch.tensor(0., device=fmap_fake[0].device)
feat_scale = torch.tensor(0., device=fmap_fake[0].device)
n_fmaps = 0
for (feat_fake, feat_real) in zip(fmap_fake, fmap_real):
assert feat_fake.shap... | 46 | 194 | 213 | 407 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""
Utility module to handle adversarial losses without requiring to mess up the main training loop.
"""
import typing a... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""
Utility module to handle adversarial losses without requiring to mess up the main training loop.
"""
import typing a... |
13,676 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/data/audio_dataset.py | 70,72 | 60,84 | from_dict | AudioMeta | 72,77 | 72,77 | @dataclass(order=True)
class AudioMeta(BaseInfo):
path: str
duration: float
sample_rate: int
amplitude: tp.Optional[float] = None
weight: tp.Optional[float] = None
# info_path is used to load additional information about the audio file that is stored in zip files.
info_path: tp.Optional[Path... | @dataclass(order=True)
class AudioMeta(BaseInfo):
path: str
duration: float
sample_rate: int
amplitude: tp.Optional[float] = None
weight: tp.Optional[float] = None
# info_path is used to load additional information about the audio file that is stored in zip files.
info_path: tp.Optional[Path... | base = cls._dict2fields(dictionary)
if 'info_path' in base and base['info_path'] is not None:
base['info_path'] = PathInZip(base['info_path'])
return cls(**base)
| base = cls._dict2fields(dictionary)
if 'info_path' in base and base['info_path'] is not None:
base['info_path'] = PathInZip(base['info_path'])
return cls(**base)
| 17 | 186 | 70 | 256 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""AudioDataset support. In order to handle a larger number of files
without having to scan again the folders, we precompu... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""AudioDataset support. In order to handle a larger number of files
without having to scan again the folders, we precompu... |
13,677 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/data/audio_dataset.py | 41,43 | 38,60 | _dict2fields | BaseInfo | 43,48 | 43,48 | @dataclass(order=True)
class BaseInfo:
@classmethod
def _dict2fields(cls, dictionary: dict):
FILL_FUNC_BODY @classmethod
def from_dict(cls, dictionary: dict):
_dictionary = cls._dict2fields(dictionary)
return cls(**_dictionary)
def to_dict(self):
return {
field.n... | @dataclass(order=True)
class BaseInfo:
@classmethod
def _dict2fields(cls, dictionary: dict):
FILL_FUNC_BODY @classmethod
def from_dict(cls, dictionary: dict):
_dictionary = cls._dict2fields(dictionary)
return cls(**_dictionary)
def to_dict(self):
return {
field.n... | return {
field.name: dictionary[field.name]
for field in fields(cls) if field.name in dictionary
}
| return {
field.name: dictionary[field.name]
for field in fields(cls) if field.name in dictionary
}
| 13 | 133 | 40 | 173 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""AudioDataset support. In order to handle a larger number of files
without having to scan again the folders, we precompu... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""AudioDataset support. In order to handle a larger number of files
without having to scan again the folders, we precompu... |
13,679 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/data/info_audio_dataset.py | 95,96 | 1,111 | get_keyword_list | 97,111 | 96,111 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Base classes for the datasets that also provide non-audio metadata,
e.g. description, text transcription etc.
"""
from ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Base classes for the datasets that also provide non-audio metadata,
e.g. description, text transcription etc.
"""
from ... | if isinstance(values, str):
values = [v.strip() for v in re.split(r'[,\s]', values)]
elif isinstance(values, float) and math.isnan(values):
values = []
if not isinstance(values, list):
logger.debug(f"Unexpected keyword list {values}")
values = [str(values)]
kws = [get_ke... | """Preprocess a list of keywords."""
if isinstance(values, str):
values = [v.strip() for v in re.split(r'[,\s]', values)]
elif isinstance(values, float) and math.isnan(values):
values = []
if not isinstance(values, list):
logger.debug(f"Unexpected keyword list {values}")
... | 58 | 1,018 | 174 | 1,192 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Base classes for the datasets that also provide non-audio metadata,
e.g. description, text transcription etc.
"""
from ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Base classes for the datasets that also provide non-audio metadata,
e.g. description, text transcription etc.
"""
from ... | |
13,680 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/data/info_audio_dataset.py | 50,51 | 38,54 | to_condition_attributes | AudioInfo | 51,54 | 51,54 | @dataclass
class AudioInfo(SegmentWithAttributes):
"""Dummy SegmentInfo with empty attributes.
The InfoAudioDataset is expected to return metadata that inherits
from SegmentWithAttributes class and can return conditioning attributes.
This basically guarantees all datasets will be compatible with curre... | @dataclass
class AudioInfo(SegmentWithAttributes):
"""Dummy SegmentInfo with empty attributes.
The InfoAudioDataset is expected to return metadata that inherits
from SegmentWithAttributes class and can return conditioning attributes.
This basically guarantees all datasets will be compatible with curre... | return ConditioningAttributes()
| return ConditioningAttributes()
| 2 | 145 | 12 | 157 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Base classes for the datasets that also provide non-audio metadata,
e.g. description, text transcription etc.
"""
from ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Base classes for the datasets that also provide non-audio metadata,
e.g. description, text transcription etc.
"""
from ... |
13,682 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/data/music_dataset.py | 75,77 | 36,115 | attribute_getter | MusicInfo | 77,91 | 77,91 | @dataclass
class MusicInfo(AudioInfo):
"""Segment info augmented with music metadata.
"""
# music-specific metadata
title: tp.Optional[str] = None
artist: tp.Optional[str] = None # anonymized artist id, used to ensure no overlap between splits
key: tp.Optional[str] = None
bpm: tp.Optional[f... | @dataclass
class MusicInfo(AudioInfo):
"""Segment info augmented with music metadata.
"""
# music-specific metadata
title: tp.Optional[str] = None
artist: tp.Optional[str] = None # anonymized artist id, used to ensure no overlap between splits
key: tp.Optional[str] = None
bpm: tp.Optional[f... | if attribute == 'bpm':
preprocess_func = get_bpm
elif attribute == 'key':
preprocess_func = get_musical_key
elif attribute in ['moods', 'keywords']:
preprocess_func = get_keyword_list
elif attribute in ['genre', 'name', 'instrument']:
prepr... | if attribute == 'bpm':
preprocess_func = get_bpm
elif attribute == 'key':
preprocess_func = get_musical_key
elif attribute in ['moods', 'keywords']:
preprocess_func = get_keyword_list
elif attribute in ['genre', 'name', 'instrument']:
prepr... | 46 | 739 | 155 | 894 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Dataset of music tracks with rich metadata.
"""
from dataclasses import dataclass, field, fields, replace
import gzip
i... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Dataset of music tracks with rich metadata.
"""
from dataclasses import dataclass, field, fields, replace
import gzip
i... |
13,683 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/data/music_dataset.py | 175,176 | 167,187 | sample_paraphrase | Paraphraser | 176,187 | 176,187 | class Paraphraser:
def __init__(self, paraphrase_source: tp.Union[str, Path], paraphrase_p: float = 0.):
self.paraphrase_p = paraphrase_p
open_fn = gzip.open if str(paraphrase_source).lower().endswith('.gz') else open
with open_fn(paraphrase_source, 'rb') as f: # type: ignore
se... | class Paraphraser:
def __init__(self, paraphrase_source: tp.Union[str, Path], paraphrase_p: float = 0.):
self.paraphrase_p = paraphrase_p
open_fn = gzip.open if str(paraphrase_source).lower().endswith('.gz') else open
with open_fn(paraphrase_source, 'rb') as f: # type: ignore
se... | if random.random() >= self.paraphrase_p:
return description
info_path = Path(audio_path).with_suffix('.json')
if info_path not in self.paraphrase_source:
warn_once(logger, f"{info_path} not in paraphrase source!")
return description
new_desc = random.c... | if random.random() >= self.paraphrase_p:
return description
info_path = Path(audio_path).with_suffix('.json')
if info_path not in self.paraphrase_source:
warn_once(logger, f"{info_path} not in paraphrase source!")
return description
new_desc = random.c... | 30 | 185 | 142 | 327 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Dataset of music tracks with rich metadata.
"""
from dataclasses import dataclass, field, fields, replace
import gzip
i... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Dataset of music tracks with rich metadata.
"""
from dataclasses import dataclass, field, fields, replace
import gzip
i... |
13,685 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/data/sound_dataset.py | 163,164 | 87,173 | collater | SoundDataset | 164,173 | 164,173 | class SoundDataset(InfoAudioDataset):
"""Sound audio dataset: Audio dataset with environmental sound-specific metadata.
Args:
info_fields_required (bool): Whether all the mandatory metadata fields should be in the loaded metadata.
external_metadata_source (tp.Optional[str]): Folder containing J... | class SoundDataset(InfoAudioDataset):
"""Sound audio dataset: Audio dataset with environmental sound-specific metadata.
Args:
info_fields_required (bool): Whether all the mandatory metadata fields should be in the loaded metadata.
external_metadata_source (tp.Optional[str]): Folder containing J... | # when training, audio mixing is performed in the collate function
wav, sound_info = super().collater(samples) # SoundDataset always returns infos
if self.aug_p > 0:
wav, sound_info = mix_samples(wav, sound_info, self.aug_p, self.mix_p,
snr_... | # when training, audio mixing is performed in the collate function
wav, sound_info = super().collater(samples) # SoundDataset always returns infos
if self.aug_p > 0:
wav, sound_info = mix_samples(wav, sound_info, self.aug_p, self.mix_p,
snr_... | 37 | 1,104 | 151 | 1,255 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Dataset of audio with a simple description.
"""
from dataclasses import dataclass, fields, replace
import json
from pa... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Dataset of audio with a simple description.
"""
from dataclasses import dataclass, fields, replace
import json
from pa... |
13,686 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/data/sound_dataset.py | 45,46 | 34,87 | to_condition_attributes | SoundInfo | 46,56 | 46,56 | @dataclass
class SoundInfo(SegmentWithAttributes):
"""Segment info augmented with Sound metadata.
"""
description: tp.Optional[str] = None
self_wav: tp.Optional[torch.Tensor] = None
@property
def has_sound_meta(self) -> bool:
return self.description is not None
def to_condition_att... | @dataclass
class SoundInfo(SegmentWithAttributes):
"""Segment info augmented with Sound metadata.
"""
description: tp.Optional[str] = None
self_wav: tp.Optional[torch.Tensor] = None
@property
def has_sound_meta(self) -> bool:
return self.description is not None
def to_condition_att... | out = ConditioningAttributes()
for _field in fields(self):
key, value = _field.name, getattr(self, _field.name)
if key == 'self_wav':
out.wav[key] = value
else:
out.text[key] = value
return out
| out = ConditioningAttributes()
for _field in fields(self):
key, value = _field.name, getattr(self, _field.name)
if key == 'self_wav':
out.wav[key] = value
else:
out.text[key] = value
return out
| 26 | 421 | 91 | 512 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Dataset of audio with a simple description.
"""
from dataclasses import dataclass, fields, replace
import json
from pa... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Dataset of audio with a simple description.
"""
from dataclasses import dataclass, fields, replace
import json
from pa... |
13,687 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/data/zip.py | 49,50 | 1,77 | _open_zip | 50,53 | 50,53 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Utility for reading some info from inside a zip file.
"""
import typing
import zipfile
from dataclasses import datacl... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Utility for reading some info from inside a zip file.
"""
import typing
import zipfile
from dataclasses import datacl... | return zipfile.ZipFile(path, mode)
| return zipfile.ZipFile(path, mode)
| 3 | 760 | 19 | 779 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Utility for reading some info from inside a zip file.
"""
import typing
import zipfile
from dataclasses import datacl... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Utility for reading some info from inside a zip file.
"""
import typing
import zipfile
from dataclasses import datacl... | |
13,688 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/data/zip.py | 41,43 | 21,49 | from_paths | PathInZip | 43,45 | 43,45 | @dataclass(order=True)
class PathInZip:
"""Hold a path of file within a zip file.
Args:
path (str): The convention is <path_to_zip>:<relative_path_inside_zip>.
Let's assume there is a zip file /some/location/foo.zip
and inside of it is a json file located at /data/file1.json,
... | @dataclass(order=True)
class PathInZip:
"""Hold a path of file within a zip file.
Args:
path (str): The convention is <path_to_zip>:<relative_path_inside_zip>.
Let's assume there is a zip file /some/location/foo.zip
and inside of it is a json file located at /data/file1.json,
... | return cls(zip_path + cls.INFO_PATH_SEP + file_path)
| return cls(zip_path + cls.INFO_PATH_SEP + file_path)
| 6 | 295 | 27 | 322 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Utility for reading some info from inside a zip file.
"""
import typing
import zipfile
from dataclasses import datacl... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Utility for reading some info from inside a zip file.
"""
import typing
import zipfile
from dataclasses import datacl... |
13,689 | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft | /home/hieuvd/dung_repo/raw/stars_01/facebookresearch_audiocraft/audiocraft/audiocraft/environment.py | 127,129 | 25,177 | get_slurm_partitions | AudioCraftEnvironment | 135,145 | 129,145 | class AudioCraftEnvironment:
"""Environment configuration for teams and clusters.
AudioCraftEnvironment picks compute cluster settings (slurm, dora) from the current running environment
or declared variable and the loaded team configuration. Additionally, the AudioCraftEnvironment
provides pointers to ... | class AudioCraftEnvironment:
"""Environment configuration for teams and clusters.
AudioCraftEnvironment picks compute cluster settings (slurm, dora) from the current running environment
or declared variable and the loaded team configuration. Additionally, the AudioCraftEnvironment
provides pointers to ... | if not partition_types:
partition_types = ["global"]
cluster_config = cls.instance()._get_cluster_config()
partitions = [
cluster_config["partitions"][partition_type]
for partition_type in partition_types
]
return ",".join(partitions)
| """Gets the requested partitions for the current team and cluster as a comma-separated string.
Args:
partition_types (list[str], optional): partition types to retrieve. Values must be
from ['global', 'team']. If not provided, the global partition is returned.
"""
... | 20 | 1,659 | 90 | 1,749 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""
Provides cluster and tools configuration across clusters (slurm, dora, utilities).
"""
import logging
import os
from... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""
Provides cluster and tools configuration across clusters (slurm, dora, utilities).
"""
import logging
import os
from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.