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
39,544
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/fastapi.py
37,38
28,55
make_session_info
WebSocketConnection
38,45
38,45
class WebSocketConnection(ws_adaptor.WebSocketConnection): def __init__(self, websocket: WebSocket, ioloop): self.ws = websocket self.ioloop = ioloop def get_query_argument(self, name) -> typing.Optional[str]: return self.ws.query_params.get(name, None) def make_session_info(self)...
class WebSocketConnection(ws_adaptor.WebSocketConnection): def __init__(self, websocket: WebSocket, ioloop): self.ws = websocket self.ioloop = ioloop def get_query_argument(self, name) -> typing.Optional[str]: return self.ws.query_params.get(name, None) def make_session_info(self)...
session_info = get_session_info_from_headers(self.ws.headers) session_info['user_ip'] = self.ws.client.host or '' session_info['request'] = self.ws session_info['backend'] = 'starlette' session_info['protocol'] = 'websocket' return session_info
session_info = get_session_info_from_headers(self.ws.headers) session_info['user_ip'] = self.ws.client.host or '' session_info['request'] = self.ws session_info['backend'] = 'starlette' session_info['protocol'] = 'websocket' return session_info
19
213
96
309
import asyncio import logging import os import typing from functools import partial import uvicorn from starlette.applications import Starlette from starlette.requests import Request from starlette.responses import HTMLResponse from starlette.routing import Route, WebSocketRoute, Mount from starlette.websockets import...
import asyncio import logging import os import typing from functools import partial import uvicorn from starlette.applications import Starlette from starlette.requests import Request from starlette.responses import HTMLResponse from starlette.routing import Route, WebSocketRoute, Mount from starlette.websockets import...
39,545
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/flask.py
134,142
1,182
start_server
156,182
142,182
""" Flask backend """ import json import logging import os import threading import werkzeug from flask import Flask, request, send_from_directory, Response from . import page from .adaptor.http import HttpContext, HttpHandler, run_event_loop from .page import make_applications from .remote_access import start_remote_...
""" Flask backend """ import json import logging import os import threading import werkzeug from flask import Flask, request, send_from_directory, Response from . import page from .adaptor.http import HttpContext, HttpHandler, run_event_loop from .page import make_applications from .remote_access import start_remote_...
if not host: host = '0.0.0.0' if port == 0: port = get_free_port() app = wsgi_app(applications, cdn=cdn, static_dir=static_dir, allowed_origins=allowed_origins, check_origin=check_origin, session_expire_seconds=session_expire_seconds, session_cleanup_i...
"""Start a Flask server to provide the PyWebIO application as a web service. :param int session_expire_seconds: Session expiration time, in seconds(default 600s). If no client message is received within ``session_expire_seconds``, the session will be considered expired. :param int session_cleanup_in...
66
1,654
391
2,045
""" Flask backend """ import json import logging import os import threading import werkzeug from flask import Flask, request, send_from_directory, Response from . import page from .adaptor.http import HttpContext, HttpHandler, run_event_loop from .page import make_applications from .remote_access import start_remote_...
""" Flask backend """ import json import logging import os import threading import werkzeug from flask import Flask, request, send_from_directory, Response from . import page from .adaptor.http import HttpContext, HttpHandler, run_event_loop from .page import make_applications from .remote_access import start_remote_...
39,546
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/flask.py
58,59
24,80
set_content
FlaskHttpContext
64,71
59,71
class FlaskHttpContext(HttpContext): backend_name = 'flask' def __init__(self): self.response = Response() self.request_data = request.data def request_obj(self): """返回当前请求对象""" return request._get_current_object() def request_method(self): """返回当前请求的方法,大写""" ...
class FlaskHttpContext(HttpContext): backend_name = 'flask' def __init__(self): self.response = Response() self.request_data = request.data def request_obj(self): """返回当前请求对象""" return request._get_current_object() def request_method(self): """返回当前请求的方法,大写""" ...
# self.response.data accept str and bytes if json_type: self.set_header('content-type', 'application/json') self.response.data = json.dumps(content) else: self.response.data = content
"""设置相应的内容 :param content: :param bool json_type: content是否要序列化成json格式,并将 content-type 设置为application/json """ # self.response.data accept str and bytes if json_type: self.set_header('content-type', 'application/json') self.response.data = json.du...
17
409
72
481
""" Flask backend """ import json import logging import os import threading import werkzeug from flask import Flask, request, send_from_directory, Response from . import page from .adaptor.http import HttpContext, HttpHandler, run_event_loop from .page import make_applications from .remote_access import start_remote_...
""" Flask backend """ import json import logging import os import threading import werkzeug from flask import Flask, request, send_from_directory, Response from . import page from .adaptor.http import HttpContext, HttpHandler, run_event_loop from .page import make_applications from .remote_access import start_remote_...
39,549
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/path_deploy.py
337,338
336,343
get_cdn
HttpPathDeployHandler
338,343
338,343
class HttpPathDeployHandler(HttpHandler): def get_cdn(self, context): FILL_FUNC_BODY
class HttpPathDeployHandler(HttpHandler): def get_cdn(self, context): FILL_FUNC_BODY
_cdn = super().get_cdn(context) if not _cdn: return LOCAL_STATIC_URL return _cdn
_cdn = super().get_cdn(context) if not _cdn: return LOCAL_STATIC_URL return _cdn
10
33
41
74
import ast import os.path from contextlib import contextmanager from functools import partial import tornado.template import tornado.web import tornado.ioloop from . import page from .adaptor.http import HttpHandler from .page import make_applications from .tornado import webio_handler, set_ioloop from .tornado_http ...
import ast import os.path from contextlib import contextmanager from functools import partial import tornado.template import tornado.web import tornado.ioloop from . import page from .adaptor.http import HttpHandler from .page import make_applications from .tornado import webio_handler, set_ioloop from .tornado_http ...
39,550
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/path_deploy.py
356,357
349,360
get
ReqHandler
357,360
357,360
class ReqHandler(tornado.web.RequestHandler): def options(self): return self.get() def post(self): return self.get() def get(self): FILL_FUNC_BODY
class ReqHandler(tornado.web.RequestHandler): def options(self): return self.get() def post(self): return self.get() def get(self): FILL_FUNC_BODY
context = TornadoHttpContext(self) self.write(handler.handle_request(context))
context = TornadoHttpContext(self) self.write(handler.handle_request(context))
4
63
30
93
import ast import os.path from contextlib import contextmanager from functools import partial import tornado.template import tornado.web import tornado.ioloop from . import page from .adaptor.http import HttpHandler from .page import make_applications from .tornado import webio_handler, set_ioloop from .tornado_http ...
import ast import os.path from contextlib import contextmanager from functools import partial import tornado.template import tornado.web import tornado.ioloop from . import page from .adaptor.http import HttpHandler from .page import make_applications from .tornado import webio_handler, set_ioloop from .tornado_http ...
39,551
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/path_deploy.py
276,277
268,289
get_app
WSHandler
277,289
277,289
class WSHandler(Handler): def get_cdn(self): _cdn = super().get_cdn() if not _cdn: return LOCAL_STATIC_URL return _cdn def get_app(self): FILL_FUNC_BODY
class WSHandler(Handler): def get_cdn(self): _cdn = super().get_cdn() if not _cdn: return LOCAL_STATIC_URL return _cdn def get_app(self): FILL_FUNC_BODY
reload = self.get_query_argument('reload', None) is not None type, res = get_app_from_path(self.request.path, abs_base, index=index_func, reload=reload) if type == 'error': raise tornado.web.HTTPError(status_code=res) elif type == 'html': r...
reload = self.get_query_argument('reload', None) is not None type, res = get_app_from_path(self.request.path, abs_base, index=index_func, reload=reload) if type == 'error': raise tornado.web.HTTPError(status_code=res) elif type == 'html': r...
37
72
158
230
import ast import os.path from contextlib import contextmanager from functools import partial import tornado.template import tornado.web import tornado.ioloop from . import page from .adaptor.http import HttpHandler from .page import make_applications from .tornado import webio_handler, set_ioloop from .tornado_http ...
import ast import os.path from contextlib import contextmanager from functools import partial import tornado.template import tornado.web import tornado.ioloop from . import page from .adaptor.http import HttpHandler from .page import make_applications from .tornado import webio_handler, set_ioloop from .tornado_http ...
39,552
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/remote_access.py
39,40
1,143
remote_access_service
49,100
40,100
""" * Implementation of remote access Use https://github.com/wang0618/localshare service by running a ssh subprocess in PyWebIO application. The stdout of ssh process is the connection info. """ import json import logging import os import threading import time import shlex from subprocess import Popen, PIPE import sh...
""" * Implementation of remote access Use https://github.com/wang0618/localshare service by running a ssh subprocess in PyWebIO application. The stdout of ssh process is the connection info. """ import json import logging import os import threading import time import shlex from subprocess import Popen, PIPE import sh...
global _ssh_process cmd = "ssh -oStrictHostKeyChecking=no -R 80:127.0.0.1:%s -p %s %s -- --output json" % ( local_port, server_port, server) args = shlex.split(cmd) logger.debug('remote access service command: %s', cmd) _ssh_process = Popen(args, stdout=PIPE, stderr=PIPE) logger.debug...
""" Wait at most one minute to get the ssh output, if it gets a normal out, the connection is successfully established. Otherwise report error and kill ssh process. :param local_port: ssh local listen port :param server: ssh server domain :param server_port: ssh server port :param setup_tim...
172
896
646
1,542
""" * Implementation of remote access Use https://github.com/wang0618/localshare service by running a ssh subprocess in PyWebIO application. The stdout of ssh process is the connection info. """ import json import logging import os import threading import time import shlex from subprocess import Popen, PIPE import sh...
""" * Implementation of remote access Use https://github.com/wang0618/localshare service by running a ssh subprocess in PyWebIO application. The stdout of ssh process is the connection info. """ import json import logging import os import threading import time import shlex from subprocess import Popen, PIPE import sh...
39,554
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/tornado.py
122,123
110,157
get
Handler
124,136
123,136
class Handler(tornado.websocket.WebSocketHandler): def get_app(self): app_name = self.get_query_argument('app', 'index') app = applications.get(app_name) or applications['index'] return app def get_cdn(self): if cdn is True and self.get_query_argumen...
class Handler(tornado.websocket.WebSocketHandler): def get_app(self): app_name = self.get_query_argument('app', 'index') app = applications.get(app_name) or applications['index'] return app def get_cdn(self): if cdn is True and self.get_query_argumen...
if self.request.headers.get("Upgrade", "").lower() != "websocket": # Backward compatible # Frontend detect whether the backend is http server if self.get_query_argument('test', ''): return self.write('') app = self.get_app(...
"""http GET request""" if self.request.headers.get("Upgrade", "").lower() != "websocket": # Backward compatible # Frontend detect whether the backend is http server if self.get_query_argument('test', ''): return self.write('') ...
35
335
134
469
import asyncio import fnmatch import json import logging import os import threading import typing import webbrowser from functools import partial from typing import Callable, Dict, List, Optional, Union from urllib.parse import urlparse import tornado import tornado.httpserver import tornado.ioloop import tornado.web ...
import asyncio import fnmatch import json import logging import os import threading import typing import webbrowser from functools import partial from typing import Callable, Dict, List, Optional, Union from urllib.parse import urlparse import tornado import tornado.httpserver import tornado.ioloop import tornado.web ...
39,555
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/tornado.py
354,355
315,360
on_close
SingleSessionWSHandler
355,360
355,360
class SingleSessionWSHandler(_webio_handler(cdn=False)): session: ScriptModeSession = None instance: typing.ClassVar = None closed = False def send_msg_to_client(self, session): for msg in session.get_task_commands(): try: self.write_m...
class SingleSessionWSHandler(_webio_handler(cdn=False)): session: ScriptModeSession = None instance: typing.ClassVar = None closed = False def send_msg_to_client(self, session): for msg in session.get_task_commands(): try: self.write_m...
if self.session is not None: self.session.close() self.closed = True logger.debug('ScriptModeSession closed')
if self.session is not None: self.session.close() self.closed = True logger.debug('ScriptModeSession closed')
11
440
42
482
import asyncio import fnmatch import json import logging import os import threading import typing import webbrowser from functools import partial from typing import Callable, Dict, List, Optional, Union from urllib.parse import urlparse import tornado import tornado.httpserver import tornado.ioloop import tornado.web ...
import asyncio import fnmatch import json import logging import os import threading import typing import webbrowser from functools import partial from typing import Callable, Dict, List, Optional, Union from urllib.parse import urlparse import tornado import tornado.httpserver import tornado.ioloop import tornado.web ...
39,556
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/tornado.py
90,91
68,94
close
WebSocketConnection
91,94
91,94
class WebSocketConnection(ws_adaptor.WebSocketConnection): def __init__(self, context: tornado.websocket.WebSocketHandler): self.context = context def get_query_argument(self, name) -> typing.Optional[str]: return self.context.get_query_argument(name, None) def make_session_info(self) -> ...
class WebSocketConnection(ws_adaptor.WebSocketConnection): def __init__(self, context: tornado.websocket.WebSocketHandler): self.context = context def get_query_argument(self, name) -> typing.Optional[str]: return self.context.get_query_argument(name, None) def make_session_info(self) -> ...
self.context.close()
self.context.close()
1
267
13
280
import asyncio import fnmatch import json import logging import os import threading import typing import webbrowser from functools import partial from typing import Callable, Dict, List, Optional, Union from urllib.parse import urlparse import tornado import tornado.httpserver import tornado.ioloop import tornado.web ...
import asyncio import fnmatch import json import logging import os import threading import typing import webbrowser from functools import partial from typing import Callable, Dict, List, Optional, Union from urllib.parse import urlparse import tornado import tornado.httpserver import tornado.ioloop import tornado.web ...
39,557
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/tornado_http.py
111,119
1,165
start_server
133,165
119,165
import os import json import logging import tornado.ioloop import tornado.web from . import page from ..session import Session from .adaptor.http import HttpContext, HttpHandler from .tornado import set_ioloop, _setup_server, open_webbrowser_on_server_started from .utils import cdn_validation, print_listen_address fr...
import os import json import logging import tornado.ioloop import tornado.web from . import page from ..session import Session from .adaptor.http import HttpContext, HttpHandler from .tornado import set_ioloop, _setup_server, open_webbrowser_on_server_started from .utils import cdn_validation, print_listen_address fr...
if not host: host = '0.0.0.0' cdn = cdn_validation(cdn, 'warn') set_ioloop(tornado.ioloop.IOLoop.current()) # to enable bokeh app cdn = cdn_validation(cdn, 'warn') # if CDN is not available, warn user and disable CDN page.MAX_PAYLOAD_SIZE = max_payload_size = parse_file_size(max_paylo...
"""Start a Tornado server to provide the PyWebIO application as a web service. The Tornado server communicates with the browser by HTTP protocol. :param int session_expire_seconds: Session expiration time, in seconds(default 60s). If no client message is received within ``session_expire_seconds``, ...
78
1,309
498
1,807
import os import json import logging import tornado.ioloop import tornado.web from . import page from ..session import Session from .adaptor.http import HttpContext, HttpHandler from .tornado import set_ioloop, _setup_server, open_webbrowser_on_server_started from .utils import cdn_validation, print_listen_address fr...
import os import json import logging import tornado.ioloop import tornado.web from . import page from ..session import Session from .adaptor.http import HttpContext, HttpHandler from .tornado import set_ioloop, _setup_server, open_webbrowser_on_server_started from .utils import cdn_validation, print_listen_address fr...
39,558
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/tornado_http.py
100,101
96,108
post
MainHandler
101,103
101,103
class MainHandler(tornado.web.RequestHandler): def options(self): return self.get() def post(self): FILL_FUNC_BODY async def get(self): context = TornadoHttpContext(self) response = await handler.handle_request_async(context) self.write(respons...
class MainHandler(tornado.web.RequestHandler): def options(self): return self.get() def post(self): FILL_FUNC_BODY async def get(self): context = TornadoHttpContext(self) response = await handler.handle_request_async(context) self.write(respons...
return self.get()
return self.get()
2
91
10
101
import os import json import logging import tornado.ioloop import tornado.web from . import page from ..session import Session from .adaptor.http import HttpContext, HttpHandler from .tornado import set_ioloop, _setup_server, open_webbrowser_on_server_started from .utils import cdn_validation, print_listen_address fr...
import os import json import logging import tornado.ioloop import tornado.web from . import page from ..session import Session from .adaptor.http import HttpContext, HttpHandler from .tornado import set_ioloop, _setup_server, open_webbrowser_on_server_started from .utils import cdn_validation, print_listen_address fr...
39,559
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/platform/tornado_http.py
52,53
18,78
set_content
TornadoHttpContext
58,65
53,65
class TornadoHttpContext(HttpContext): backend_name = 'tornado' def __init__(self, handler: tornado.web.RequestHandler): self.handler = handler self.response = b'' def request_obj(self): """返回当前请求对象""" return self.handler.request def request_method(self): """返回...
class TornadoHttpContext(HttpContext): backend_name = 'tornado' def __init__(self, handler: tornado.web.RequestHandler): self.handler = handler self.response = b'' def request_obj(self): """返回当前请求对象""" return self.handler.request def request_method(self): """返回...
# self.response.content accept str and byte if json_type: self.set_header('content-type', 'application/json') self.response = json.dumps(content) else: self.response = content
"""设置相应的内容 :param content: :param bool json_type: content是否要序列化成json格式,并将 content-type 设置为application/json """ # self.response.content accept str and byte if json_type: self.set_header('content-type', 'application/json') self.response = json.dumps...
17
472
68
540
import os import json import logging import tornado.ioloop import tornado.web from . import page from ..session import Session from .adaptor.http import HttpContext, HttpHandler from .tornado import set_ioloop, _setup_server, open_webbrowser_on_server_started from .utils import cdn_validation, print_listen_address fr...
import os import json import logging import tornado.ioloop import tornado.web from . import page from ..session import Session from .adaptor.http import HttpContext, HttpHandler from .tornado import set_ioloop, _setup_server, open_webbrowser_on_server_started from .utils import cdn_validation, print_listen_address fr...
39,561
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/session/base.py
109,110
12,174
close
Session
114,129
110,129
class Session: """ 会话对象,由Backend创建 属性: info 表示会话信息的对象 save 会话的数据对象,提供用户在对象上保存一些会话相关数据 由Task在当前Session上下文中调用: get_current_session get_current_task_id get_scope_name pop_scope push_scope send_task_command next_client_event ...
class Session: """ 会话对象,由Backend创建 属性: info 表示会话信息的对象 save 会话的数据对象,提供用户在对象上保存一些会话相关数据 由Task在当前Session上下文中调用: get_current_session get_current_task_id get_scope_name pop_scope push_scope send_task_command next_client_event ...
if self._closed: return self._closed = True self.deferred_functions.reverse() while self.deferred_functions: func = self.deferred_functions.pop() try: func() except Exception as e: msg = "Error occurred when...
"""Close current session :param bool nonblock: Don't block thread. Used in closing from backend. """ if self._closed: return self._closed = True self.deferred_functions.reverse() while self.deferred_functions: func = self.deferred_functio...
45
1,507
139
1,646
import logging import sys import traceback from collections import defaultdict import user_agents from ..exceptions import SessionException logger = logging.getLogger(__name__) class Session: """ 会话对象,由Backend创建 属性: info 表示会话信息的对象 save 会话的数据对象,提供用户在对象上保存一些会话相关数据 由Task在当前Session上下文中...
import logging import sys import traceback from collections import defaultdict import user_agents from ..exceptions import SessionException logger = logging.getLogger(__name__) class Session: """ 会话对象,由Backend创建 属性: info 表示会话信息的对象 save 会话的数据对象,提供用户在对象上保存一些会话相关数据 由Task在当前Session上下文中...
39,563
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/session/coroutinebased.py
286,288
268,379
gen_coro_id
Task
289,295
288,295
class Task: @contextmanager def session_context(self): """ >>> with session_context(): ... res = self.coros[-1].send(data) """ # todo issue: with 语句可能发生嵌套,导致内层with退出时,将属性置空 _context.current_session = self.session _context.current_task_id = self.coro_...
class Task: @contextmanager def session_context(self): """ >>> with session_context(): ... res = self.coros[-1].send(data) """ # todo issue: with 语句可能发生嵌套,导致内层with退出时,将属性置空 _context.current_session = self.session _context.current_task_id = self.coro_...
name = 'coro' if hasattr(coro, '__name__'): name = coro.__name__ return '%s-%s' % (name, random_str(10))
"""生成协程id""" name = 'coro' if hasattr(coro, '__name__'): name = coro.__name__ return '%s-%s' % (name, random_str(10))
14
1,056
60
1,116
import asyncio import logging import threading from contextlib import contextmanager from functools import partial from .base import Session from ..exceptions import SessionNotFoundException, SessionClosedException, SessionException from ..utils import random_str, isgeneratorfunction, iscoroutinefunction logger = log...
import asyncio import logging import threading from contextlib import contextmanager from functools import partial from .base import Session from ..exceptions import SessionNotFoundException, SessionClosedException, SessionException from ..utils import random_str, isgeneratorfunction, iscoroutinefunction logger = log...
39,564
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/session/coroutinebased.py
259,260
249,268
close
TaskHandler
261,263
260,263
class TaskHandler: """The handler of coroutine task See also: `run_async() <pywebio.session.run_async>` """ def __init__(self, close, closed): self._close = close self._closed = closed def close(self): FILL_FUNC_BODY def closed(self) -> bool: """Returns a bool stating w...
class TaskHandler: """The handler of coroutine task See also: `run_async() <pywebio.session.run_async>` """ def __init__(self, close, closed): self._close = close self._closed = closed def close(self): """Close the coroutine task.""" FILL_FUNC_BODY def closed(self) -> b...
return self._close()
"""Close the coroutine task.""" return self._close()
2
132
10
142
import asyncio import logging import threading from contextlib import contextmanager from functools import partial from .base import Session from ..exceptions import SessionNotFoundException, SessionClosedException, SessionException from ..utils import random_str, isgeneratorfunction, iscoroutinefunction logger = log...
import asyncio import logging import threading from contextlib import contextmanager from functools import partial from .base import Session from ..exceptions import SessionNotFoundException, SessionClosedException, SessionException from ..utils import random_str, isgeneratorfunction, iscoroutinefunction logger = log...
39,565
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/session/threadbased.py
311,313
308,346
get_current_session
ScriptModeSession
313,319
313,319
class ScriptModeSession(ThreadBasedSession): """Script mode的会话实现""" @classmethod def get_current_session(cls) -> "ScriptModeSession": FILL_FUNC_BODY @classmethod def get_current_task_id(cls): task_id = super().get_current_task_id() session = cls.get_current_session() if task_...
class ScriptModeSession(ThreadBasedSession): """Script mode的会话实现""" @classmethod def get_current_session(cls) -> "ScriptModeSession": FILL_FUNC_BODY @classmethod def get_current_task_id(cls): task_id = super().get_current_task_id() session = cls.get_current_session() if task_...
if cls.instance is None: raise SessionNotFoundException("Can't find current session. It might be a bug.") if cls.instance.closed(): raise SessionClosedException() return cls.instance
if cls.instance is None: raise SessionNotFoundException("Can't find current session. It might be a bug.") if cls.instance.closed(): raise SessionClosedException() return cls.instance
20
439
62
501
import logging import queue import threading from functools import wraps from .base import Session from ..exceptions import SessionNotFoundException, SessionClosedException, SessionException from ..utils import random_str, LimitedSizeQueue, isgeneratorfunction, iscoroutinefunction, \ get_function_name logger = lo...
import logging import queue import threading from functools import wraps from .base import Session from ..exceptions import SessionNotFoundException, SessionClosedException, SessionException from ..utils import random_str, LimitedSizeQueue, isgeneratorfunction, iscoroutinefunction, \ get_function_name logger = lo...
39,568
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/utils.py
233,234
198,243
_put
LimitedSizeQueue
234,237
234,237
class LimitedSizeQueue(queue.Queue): """ 有限大小的队列 `get()` 返回全部数据 队列满时,再 `put()` 会阻塞 """ def get(self): """获取队列全部数据""" try: return super().get(block=False) except queue.Empty: return [] def wait_empty(self, timeout=None): """等待队列内的数据被取...
class LimitedSizeQueue(queue.Queue): """ 有限大小的队列 `get()` 返回全部数据 队列满时,再 `put()` 会阻塞 """ def get(self): """获取队列全部数据""" try: return super().get(block=False) except queue.Empty: return [] def wait_empty(self, timeout=None): """等待队列内的数据被取...
self.queue.append(item) # Get an item from the queue
self.queue.append(item) # Get an item from the queue
8
304
23
327
import asyncio import functools import inspect import os import queue import random import socket import string import time from collections import OrderedDict from contextlib import closing from os.path import abspath, dirname, join, normpath project_dir = dirname(abspath(__file__)) STATIC_PATH = join(project_dir, '...
import asyncio import functools import inspect import os import queue import random import socket import string import time from collections import OrderedDict from contextlib import closing from os.path import abspath, dirname, join, normpath project_dir = dirname(abspath(__file__)) STATIC_PATH = join(project_dir, '...
39,569
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO
/home/hieuvd/dung_repo/raw/stars_02/pywebio_PyWebIO/PyWebIO/pywebio/utils.py
79,81
46,126
_dict
ObjectDictProxy
81,83
81,83
class ObjectDictProxy: """ 通过属性访问的字典。实例不维护底层字典,而是每次在访问时使用回调函数获取 在对象属性上保存的数据会被保存到底层字典中 访问数据对象不存在的属性时会返回None而不是抛出异常。 不能保存下划线开始的属性 用 ``obj._dict`` 获取对象的字典表示 Example:: d = {} data = LazyObjectDict(lambda: d) data.name = "Wang" data.age = 22 assert data...
class ObjectDictProxy: """ 通过属性访问的字典。实例不维护底层字典,而是每次在访问时使用回调函数获取 在对象属性上保存的数据会被保存到底层字典中 访问数据对象不存在的属性时会返回None而不是抛出异常。 不能保存下划线开始的属性 用 ``obj._dict`` 获取对象的字典表示 Example:: d = {} data = LazyObjectDict(lambda: d) data.name = "Wang" data.age = 22 assert data...
return self._dict_getter()
return self._dict_getter()
2
644
13
657
import asyncio import functools import inspect import os import queue import random import socket import string import time from collections import OrderedDict from contextlib import closing from os.path import abspath, dirname, join, normpath project_dir = dirname(abspath(__file__)) STATIC_PATH = join(project_dir, '...
import asyncio import functools import inspect import os import queue import random import socket import string import time from collections import OrderedDict from contextlib import closing from os.path import abspath, dirname, join, normpath project_dir = dirname(abspath(__file__)) STATIC_PATH = join(project_dir, '...
39,591
/home/hieuvd/dung_repo/raw/stars_02/qubvel_segmentation_models/segmentation_models
/home/hieuvd/dung_repo/raw/stars_02/qubvel_segmentation_models/segmentation_models/segmentation_models/backbones/backbones_factory.py
109,110
9,113
get_preprocessing
BackbonesFactory
110,113
110,113
class BackbonesFactory(ModelsFactory): _default_feature_layers = { # List of layers to take features from backbone in the following order: # (x16, x8, x4, x2, x1) - `x4` mean that features has 4 times less spatial # resolution (Height x Width) than input image. # VGG 'vgg16...
class BackbonesFactory(ModelsFactory): _default_feature_layers = { # List of layers to take features from backbone in the following order: # (x16, x8, x4, x2, x1) - `x4` mean that features has 4 times less spatial # resolution (Height x Width) than input image. # VGG 'vgg16...
return self.get(name)[1]
return self.get(name)[1]
2
1,947
16
1,963
import copy import efficientnet.model as eff from classification_models.models_factory import ModelsFactory from . import inception_resnet_v2 as irv2 from . import inception_v3 as iv3 class BackbonesFactory(ModelsFactory): _default_feature_layers = { # List of layers to take features from backbone in th...
import copy import efficientnet.model as eff from classification_models.models_factory import ModelsFactory from . import inception_resnet_v2 as irv2 from . import inception_v3 as iv3 class BackbonesFactory(ModelsFactory): _default_feature_layers = { # List of layers to take features from backbone in th...
39,595
/home/hieuvd/dung_repo/raw/stars_02/qubvel_segmentation_models/segmentation_models
/home/hieuvd/dung_repo/raw/stars_02/qubvel_segmentation_models/segmentation_models/segmentation_models/base/objects.py
30,32
1,63
set_submodules
KerasObject
32,37
32,37
class KerasObject: _backend = None _models = None _layers = None _utils = None def __init__(self, name=None): if (self.backend is None or self.utils is None or self.models is None or self.layers is None): raise RuntimeError('You ca...
class KerasObject: _backend = None _models = None _layers = None _utils = None def __init__(self, name=None): if (self.backend is None or self.utils is None or self.models is None or self.layers is None): raise RuntimeError('You ca...
cls._backend = backend cls._layers = layers cls._models = models cls._utils = utils
cls._backend = backend cls._layers = layers cls._models = models cls._utils = utils
12
356
40
396
class KerasObject: _backend = None _models = None _layers = None _utils = None def __init__(self, name=None): if (self.backend is None or self.utils is None or self.models is None or self.layers is None): raise RuntimeError('You ca...
class KerasObject: _backend = None _models = None _layers = None _utils = None def __init__(self, name=None): if (self.backend is None or self.utils is None or self.models is None or self.layers is None): raise RuntimeError('You ca...
39,596
/home/hieuvd/dung_repo/raw/stars_02/qubvel_segmentation_models/segmentation_models
/home/hieuvd/dung_repo/raw/stars_02/qubvel_segmentation_models/segmentation_models/segmentation_models/models/_common_blocks.py
4,22
1,70
Conv2dBn
23,70
22,70
from keras_applications import get_submodules_from_kwargs def Conv2dBn( filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), activation=None, kernel_initializer='glorot_uniform', bias_initializer='zeros',...
from keras_applications import get_submodules_from_kwargs def Conv2dBn( filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), activation=None, kernel_initializer='glorot_uniform', bias_initializer='zeros',...
conv_name, act_name, bn_name = None, None, None block_name = kwargs.pop('name', None) backend, layers, models, keras_utils = get_submodules_from_kwargs(kwargs) if block_name is not None: conv_name = block_name + '_conv' if block_name is not None and activation is not None: act_str...
"""Extension of Conv2D layer with batchnorm""" conv_name, act_name, bn_name = None, None, None block_name = kwargs.pop('name', None) backend, layers, models, keras_utils = get_submodules_from_kwargs(kwargs) if block_name is not None: conv_name = block_name + '_conv' if block_name is n...
111
187
508
695
from keras_applications import get_submodules_from_kwargs def Conv2dBn( filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), activation=None, kernel_initializer='glorot_uniform', bias_initializer='zeros',...
from keras_applications import get_submodules_from_kwargs def Conv2dBn( filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), activation=None, kernel_initializer='glorot_uniform', bias_initializer='zeros',...
39,597
/home/hieuvd/dung_repo/raw/stars_02/qubvel_segmentation_models/segmentation_models
/home/hieuvd/dung_repo/raw/stars_02/qubvel_segmentation_models/segmentation_models/segmentation_models/models/_utils.py
13,14
1,17
filter_keras_submodules
15,17
14,17
from keras_applications import get_submodules_from_kwargs def freeze_model(model, **kwargs): """Set all layers non trainable, excluding BatchNormalization layers""" _, layers, _, _ = get_submodules_from_kwargs(kwargs) for layer in model.layers: if not isinstance(layer, layers.BatchNormalization): ...
from keras_applications import get_submodules_from_kwargs def freeze_model(model, **kwargs): """Set all layers non trainable, excluding BatchNormalization layers""" _, layers, _, _ = get_submodules_from_kwargs(kwargs) for layer in model.layers: if not isinstance(layer, layers.BatchNormalization): ...
submodule_keys = kwargs.keys() & {'backend', 'layers', 'models', 'utils'} return {key: kwargs[key] for key in submodule_keys}
"""Selects only arguments that define keras_application submodules. """ submodule_keys = kwargs.keys() & {'backend', 'layers', 'models', 'utils'} return {key: kwargs[key] for key in submodule_keys}
15
141
49
190
from keras_applications import get_submodules_from_kwargs def freeze_model(model, **kwargs): """Set all layers non trainable, excluding BatchNormalization layers""" _, layers, _, _ = get_submodules_from_kwargs(kwargs) for layer in model.layers: if not isinstance(layer, layers.BatchNormalization): ...
from keras_applications import get_submodules_from_kwargs def freeze_model(model, **kwargs): """Set all layers non trainable, excluding BatchNormalization layers""" _, layers, _, _ = get_submodules_from_kwargs(kwargs) for layer in model.layers: if not isinstance(layer, layers.BatchNormalization): ...
39,602
/home/hieuvd/dung_repo/raw/stars_02/qubvel_segmentation_models/segmentation_models
/home/hieuvd/dung_repo/raw/stars_02/qubvel_segmentation_models/segmentation_models/segmentation_models/utils.py
40,50
1,90
set_regularization
66,90
50,90
""" Utility functions for segmentation models """ from keras_applications import get_submodules_from_kwargs from . import inject_global_submodules def set_trainable(model, recompile=True, **kwargs): """Set all layers of model trainable and recompile it Note: Model is recompiled using same optimizer,...
""" Utility functions for segmentation models """ from keras_applications import get_submodules_from_kwargs from . import inject_global_submodules def set_trainable(model, recompile=True, **kwargs): """Set all layers of model trainable and recompile it Note: Model is recompiled using same optimizer,...
_, _, models, _ = get_submodules_from_kwargs(kwargs) for layer in model.layers: # set kernel_regularizer if kernel_regularizer is not None and hasattr(layer, 'kernel_regularizer'): layer.kernel_regularizer = kernel_regularizer # set bias_regularizer if bias_regulariz...
"""Set regularizers to all layers Note: Returned model's config is updated correctly Args: model (``keras.models.Model``): instance of keras model kernel_regularizer(``regularizer`): regularizer of kernels bias_regularizer(``regularizer``): regularizer of bias activi...
88
538
312
850
""" Utility functions for segmentation models """ from keras_applications import get_submodules_from_kwargs from . import inject_global_submodules def set_trainable(model, recompile=True, **kwargs): """Set all layers of model trainable and recompile it Note: Model is recompiled using same optimizer,...
""" Utility functions for segmentation models """ from keras_applications import get_submodules_from_kwargs from . import inject_global_submodules def set_trainable(model, recompile=True, **kwargs): """Set all layers of model trainable and recompile it Note: Model is recompiled using same optimizer,...
39,603
/home/hieuvd/dung_repo/raw/stars_02/qubvel_segmentation_models/segmentation_models
/home/hieuvd/dung_repo/raw/stars_02/qubvel_segmentation_models/segmentation_models/setup.py
76,77
59,97
run
UploadCommand
77,97
77,97
class UploadCommand(Command): """Support setup.py upload.""" description = 'Build and publish the package.' user_options = [] @staticmethod def status(s): """Prints things in bold.""" print(s) def initialize_options(self): pass def finalize_options(self): ...
class UploadCommand(Command): """Support setup.py upload.""" description = 'Build and publish the package.' user_options = [] @staticmethod def status(s): """Prints things in bold.""" print(s) def initialize_options(self): pass def finalize_options(self): ...
try: self.status('Removing previous builds...') rmtree(os.path.join(here, 'dist')) except OSError: pass self.status('Building Source and Wheel (universal) distribution...') os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))...
try: self.status('Removing previous builds...') rmtree(os.path.join(here, 'dist')) except OSError: pass self.status('Building Source and Wheel (universal) distribution...') os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))...
45
109
204
313
#!/usr/bin/env python # -*- coding: utf-8 -*- # Note: To use the 'upload' functionality of this file, you must: # $ pip install twine import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command # Package meta-data. NAME = 'segmentation_models' DESCRIPTION = 'Image...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Note: To use the 'upload' functionality of this file, you must: # $ pip install twine import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command # Package meta-data. NAME = 'segmentation_models' DESCRIPTION = 'Image...
39,738
/home/hieuvd/dung_repo/raw/stars_02/reddelexc_hackerone-reports/hackerone-reports
/home/hieuvd/dung_repo/raw/stars_02/reddelexc_hackerone-reports/hackerone-reports/fetcher.py
48,49
1,98
fetch
49,96
49,96
""" This script runs first. It will scroll through hacktivity until the appearance of URL of the first report in data.csv. Then script searches for all new reports' URLs and add them to data.csv. To use it without modifications you should put non-empty data.csv file in the same directory with this script (current dat...
""" This script runs first. It will scroll through hacktivity until the appearance of URL of the first report in data.csv. Then script searches for all new reports' URLs and add them to data.csv. To use it without modifications you should put non-empty data.csv file in the same directory with this script (current dat...
options = ChromeOptions() options.binary_location = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" options.add_argument('no-sandbox') options.add_argument('headless') driver = Chrome(options=options) reports = [] with open('data.csv', 'r', newline='', encoding='utf-8') as fi...
options = ChromeOptions() options.binary_location = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" options.add_argument('no-sandbox') options.add_argument('headless') driver = Chrome(options=options) reports = [] with open('data.csv', 'r', newline='', encoding='utf-8') as fi...
106
391
551
942
""" This script runs first. It will scroll through hacktivity until the appearance of URL of the first report in data.csv. Then script searches for all new reports' URLs and add them to data.csv. To use it without modifications you should put non-empty data.csv file in the same directory with this script (current dat...
""" This script runs first. It will scroll through hacktivity until the appearance of URL of the first report in data.csv. Then script searches for all new reports' URLs and add them to data.csv. To use it without modifications you should put non-empty data.csv file in the same directory with this script (current dat...
39,739
/home/hieuvd/dung_repo/raw/stars_02/reddelexc_hackerone-reports/hackerone-reports
/home/hieuvd/dung_repo/raw/stars_02/reddelexc_hackerone-reports/hackerone-reports/filler.py
15,16
1,48
fill
16,46
16,46
""" This script runs third. It will get every report in json and take necessary information. It takes a lot of time to fetch because there are so much reports. To use it without modifications you should put non-empty data.csv file in the same directory with this script (current data.csv is good). """ import csv impo...
""" This script runs third. It will get every report in json and take necessary information. It takes a lot of time to fetch because there are so much reports. To use it without modifications you should put non-empty data.csv file in the same directory with this script (current data.csv is good). """ import csv impo...
reports = [] with open('data.csv', 'r', newline='', encoding='utf-8') as file: reader = csv.DictReader(file) for row in reader: reports.append(dict(row)) count_of_reports = len(reports) for i in range(count_of_reports): time.sleep(0.1) print('Fetching report '...
reports = [] with open('data.csv', 'r', newline='', encoding='utf-8') as file: reader = csv.DictReader(file) for row in reader: reports.append(dict(row)) count_of_reports = len(reports) for i in range(count_of_reports): time.sleep(0.1) print('Fetching report '...
113
114
463
577
""" This script runs third. It will get every report in json and take necessary information. It takes a lot of time to fetch because there are so much reports. To use it without modifications you should put non-empty data.csv file in the same directory with this script (current data.csv is good). """ import csv impo...
""" This script runs third. It will get every report in json and take necessary information. It takes a lot of time to fetch because there are so much reports. To use it without modifications you should put non-empty data.csv file in the same directory with this script (current data.csv is good). """ import csv impo...
39,916
/home/hieuvd/dung_repo/raw/stars_02/ryanmcgrath_twython/twython
/home/hieuvd/dung_repo/raw/stars_02/ryanmcgrath_twython/twython/twython/exceptions.py
31,33
13,36
msg
TwythonError
33,36
33,36
class TwythonError(Exception): """Generic error class, catch-all for most Twython issues. Special cases are handled by TwythonAuthError & TwythonRateLimitError. from twython import TwythonError, TwythonRateLimitError, TwythonAuthError """ def __init__(self, msg, error_code=None, retry_after=None):...
class TwythonError(Exception): """Generic error class, catch-all for most Twython issues. Special cases are handled by TwythonAuthError & TwythonRateLimitError. from twython import TwythonError, TwythonRateLimitError, TwythonAuthError """ def __init__(self, msg, error_code=None, retry_after=None):...
return self.args[0]
return self.args[0]
2
223
14
237
# -*- coding: utf-8 -*- """ twython.exceptions ~~~~~~~~~~~~~~~~~~ This module contains Twython specific Exception classes. """ from .endpoints import TWITTER_HTTP_STATUS_CODE class TwythonError(Exception): """Generic error class, catch-all for most Twython issues. Special cases are handled by TwythonAuthEr...
# -*- coding: utf-8 -*- """ twython.exceptions ~~~~~~~~~~~~~~~~~~ This module contains Twython specific Exception classes. """ from .endpoints import TWITTER_HTTP_STATUS_CODE class TwythonError(Exception): """Generic error class, catch-all for most Twython issues. Special cases are handled by TwythonAuthEr...
39,917
/home/hieuvd/dung_repo/raw/stars_02/ryanmcgrath_twython/twython
/home/hieuvd/dung_repo/raw/stars_02/ryanmcgrath_twython/twython/twython/helpers.py
14,15
1,35
_transparent_params
15,35
15,35
# -*- coding: utf-8 -*- """ twython.helpers ~~~~~~~~~~~~~~~ This module contains functions that are repeatedly used throughout the Twython library. """ from .compat import basestring, numeric_types def _transparent_params(_params): FILL_FUNC_BODY
# -*- coding: utf-8 -*- """ twython.helpers ~~~~~~~~~~~~~~~ This module contains functions that are repeatedly used throughout the Twython library. """ from .compat import basestring, numeric_types def _transparent_params(_params): FILL_FUNC_BODY
params = {} files = {} for k, v in _params.items(): if hasattr(v, 'read') and callable(v.read): files[k] = v # pragma: no cover elif isinstance(v, bool): if v: params[k] = 'true' else: params[k] = 'false' elif isins...
params = {} files = {} for k, v in _params.items(): if hasattr(v, 'read') and callable(v.read): files[k] = v # pragma: no cover elif isinstance(v, bool): if v: params[k] = 'true' else: params[k] = 'false' elif isins...
66
81
218
299
# -*- coding: utf-8 -*- """ twython.helpers ~~~~~~~~~~~~~~~ This module contains functions that are repeatedly used throughout the Twython library. """ from .compat import basestring, numeric_types def _transparent_params(_params): FILL_FUNC_BODY
# -*- coding: utf-8 -*- """ twython.helpers ~~~~~~~~~~~~~~~ This module contains functions that are repeatedly used throughout the Twython library. """ from .compat import basestring, numeric_types def _transparent_params(_params): FILL_FUNC_BODY
39,918
/home/hieuvd/dung_repo/raw/stars_02/ryanmcgrath_twython/twython
/home/hieuvd/dung_repo/raw/stars_02/ryanmcgrath_twython/twython/twython/streaming/types.py
61,62
24,89
firehose
TwythonStreamerTypesStatuses
62,73
62,73
class TwythonStreamerTypesStatuses(object): """Class for different statuses endpoints Available so :meth:`TwythonStreamer.statuses.filter()` is available. Just a bit cleaner than :meth:`TwythonStreamer.statuses_filter()`, :meth:`statuses_sample()`, etc. all being single methods in :class:`TwythonS...
class TwythonStreamerTypesStatuses(object): """Class for different statuses endpoints Available so :meth:`TwythonStreamer.statuses.filter()` is available. Just a bit cleaner than :meth:`TwythonStreamer.statuses_filter()`, :meth:`statuses_sample()`, etc. all being single methods in :class:`TwythonS...
r"""Stream statuses/firehose :param \*\*params: Parameters to send with your stream request Accepted params found at: https://dev.twitter.com/docs/api/1.1/get/statuses/firehose """ url = 'https://stream.twitter.com/%s/statuses/firehose.json' \ % self.strea...
r"""Stream statuses/firehose :param \*\*params: Parameters to send with your stream request Accepted params found at: https://dev.twitter.com/docs/api/1.1/get/statuses/firehose """ url = 'https://stream.twitter.com/%s/statuses/firehose.json' \ % self.strea...
25
609
132
741
# -*- coding: utf-8 -*- """ twython.streaming.types ~~~~~~~~~~~~~~~~~~~~~~~ This module contains classes and methods for :class:`TwythonStreamer` to use. """ class TwythonStreamerTypes(object): """Class for different stream endpoints Not all streaming endpoints have nested endpoints. User Streams and S...
# -*- coding: utf-8 -*- """ twython.streaming.types ~~~~~~~~~~~~~~~~~~~~~~~ This module contains classes and methods for :class:`TwythonStreamer` to use. """ class TwythonStreamerTypes(object): """Class for different stream endpoints Not all streaming endpoints have nested endpoints. User Streams and S...
39,919
/home/hieuvd/dung_repo/raw/stars_02/s0md3v_sd-webui-roop/sd-webui-roop
/home/hieuvd/dung_repo/raw/stars_02/s0md3v_sd-webui-roop/sd-webui-roop/install.py
14,15
1,31
download
15,20
15,20
import os import subprocess import sys from tqdm import tqdm import urllib.request req_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "requirements.txt") models_dir = os.path.abspath("models/roop") model_url = "https://github.com/dream80/roop_colab/releases/download/v0.0.1/inswapper_128.onnx" mode...
import os import subprocess import sys from tqdm import tqdm import urllib.request req_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "requirements.txt") models_dir = os.path.abspath("models/roop") model_url = "https://github.com/dream80/roop_colab/releases/download/v0.0.1/inswapper_128.onnx" mode...
request = urllib.request.urlopen(url) total = int(request.headers.get('Content-Length', 0)) with tqdm(total=total, desc='Downloading', unit='B', unit_scale=True, unit_divisor=1024) as progress: urllib.request.urlretrieve(url, path, reporthook=lambda count, block_size, total_size: progress.update(blo...
request = urllib.request.urlopen(url) total = int(request.headers.get('Content-Length', 0)) with tqdm(total=total, desc='Downloading', unit='B', unit_scale=True, unit_divisor=1024) as progress: urllib.request.urlretrieve(url, path, reporthook=lambda count, block_size, total_size: progress.update(blo...
22
306
120
426
import os import subprocess import sys from tqdm import tqdm import urllib.request req_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "requirements.txt") models_dir = os.path.abspath("models/roop") model_url = "https://github.com/dream80/roop_colab/releases/download/v0.0.1/inswapper_128.onnx" mode...
import os import subprocess import sys from tqdm import tqdm import urllib.request req_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "requirements.txt") models_dir = os.path.abspath("models/roop") model_url = "https://github.com/dream80/roop_colab/releases/download/v0.0.1/inswapper_128.onnx" mode...
39,920
/home/hieuvd/dung_repo/raw/stars_02/s0md3v_sd-webui-roop/sd-webui-roop
/home/hieuvd/dung_repo/raw/stars_02/s0md3v_sd-webui-roop/sd-webui-roop/scripts/cimage.py
4,5
1,10
convert_to_sd
5,10
5,10
import tempfile from ifnude import detect def convert_to_sd(img): FILL_FUNC_BODY
import tempfile from ifnude import detect def convert_to_sd(img): FILL_FUNC_BODY
shapes = [] chunks = detect(img) for chunk in chunks: shapes.append(chunk["score"] > 0.7) return [any(shapes), tempfile.NamedTemporaryFile(delete=False, suffix=".png")]
shapes = [] chunks = detect(img) for chunk in chunks: shapes.append(chunk["score"] > 0.7) return [any(shapes), tempfile.NamedTemporaryFile(delete=False, suffix=".png")]
17
32
69
101
import tempfile from ifnude import detect def convert_to_sd(img): FILL_FUNC_BODY
import tempfile from ifnude import detect def convert_to_sd(img): FILL_FUNC_BODY
40,151
/home/hieuvd/dung_repo/raw/stars_02/scrapinghub_slackbot/slackbot
/home/hieuvd/dung_repo/raw/stars_02/scrapinghub_slackbot/slackbot/run.py
10,11
1,24
main
11,22
11,22
#!/usr/bin/env python import sys import logging import logging.config from slackbot import settings from slackbot.bot import Bot def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
#!/usr/bin/env python import sys import logging import logging.config from slackbot import settings from slackbot.bot import Bot def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
kw = { 'format': '[%(asctime)s] %(message)s', 'datefmt': '%m/%d/%Y %H:%M:%S', 'level': logging.DEBUG if settings.DEBUG else logging.INFO, 'stream': sys.stdout, } logging.basicConfig(**kw) logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARNI...
kw = { 'format': '[%(asctime)s] %(message)s', 'datefmt': '%m/%d/%Y %H:%M:%S', 'level': logging.DEBUG if settings.DEBUG else logging.INFO, 'stream': sys.stdout, } logging.basicConfig(**kw) logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARNI...
24
67
142
209
#!/usr/bin/env python import sys import logging import logging.config from slackbot import settings from slackbot.bot import Bot def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
#!/usr/bin/env python import sys import logging import logging.config from slackbot import settings from slackbot.bot import Bot def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
40,153
/home/hieuvd/dung_repo/raw/stars_02/scrapinghub_slackbot/slackbot
/home/hieuvd/dung_repo/raw/stars_02/scrapinghub_slackbot/slackbot/slackbot/dispatcher.py
318,319
190,323
docs_reply
Message
319,323
319,323
class Message(object): def __init__(self, slackclient, body): self._client = slackclient self._body = body self._plugins = PluginsManager() def _get_user_id(self): if 'user' in self._body: return self._body['user'] return self._client.find_user_by_name(self....
class Message(object): def __init__(self, slackclient, body): self._client = slackclient self._body = body self._plugins = PluginsManager() def _get_user_id(self): if 'user' in self._body: return self._body['user'] return self._client.find_user_by_name(self....
reply = [u' • `{0}` {1}'.format(v.__name__, v.__doc__ or '') for _, v in six.iteritems(self._plugins.commands['respond_to'])] return u'\n'.join(reply)
reply = [u' • `{0}` {1}'.format(v.__name__, v.__doc__ or '') for _, v in six.iteritems(self._plugins.commands['respond_to'])] return u'\n'.join(reply)
16
1,101
74
1,175
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging import re import time import traceback from functools import wraps import six from slackbot.manager import PluginsManager from slackbot.utils import WorkerPool from slackbot import settings logger = logging.getLogger(__name__) class Mess...
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging import re import time import traceback from functools import wraps import six from slackbot.manager import PluginsManager from slackbot.utils import WorkerPool from slackbot import settings logger = logging.getLogger(__name__) class Mess...
40,154
/home/hieuvd/dung_repo/raw/stars_02/scrapinghub_slackbot/slackbot
/home/hieuvd/dung_repo/raw/stars_02/scrapinghub_slackbot/slackbot/slackbot/dispatcher.py
107,108
18,175
filter_text
MessageDispatcher
108,139
108,139
class MessageDispatcher(object): def __init__(self, slackclient, plugins, errors_to): self._client = slackclient self._pool = WorkerPool(self.dispatch_msg) self._plugins = plugins self._errors_to = None if errors_to: self._errors_to = self._client.find_channel_by_...
class MessageDispatcher(object): def __init__(self, slackclient, plugins, errors_to): self._client = slackclient self._pool = WorkerPool(self.dispatch_msg) self._plugins = plugins self._errors_to = None if errors_to: self._errors_to = self._client.find_channel_by_...
full_text = msg.get('text', '') or '' channel = msg['channel'] bot_name = self._get_bot_name() bot_id = self._get_bot_id() m = self.AT_MESSAGE_MATCHER.match(full_text) if channel[0] == 'C' or channel[0] == 'G': if not m: return ma...
full_text = msg.get('text', '') or '' channel = msg['channel'] bot_name = self._get_bot_name() bot_id = self._get_bot_id() m = self.AT_MESSAGE_MATCHER.match(full_text) if channel[0] == 'C' or channel[0] == 'G': if not m: return ma...
84
1,398
290
1,688
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging import re import time import traceback from functools import wraps import six from slackbot.manager import PluginsManager from slackbot.utils import WorkerPool from slackbot import settings logger = logging.getLogger(__name__) class Mess...
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging import re import time import traceback from functools import wraps import six from slackbot.manager import PluginsManager from slackbot.utils import WorkerPool from slackbot import settings logger = logging.getLogger(__name__) class Mess...
40,155
/home/hieuvd/dung_repo/raw/stars_02/scrapinghub_slackbot/slackbot
/home/hieuvd/dung_repo/raw/stars_02/scrapinghub_slackbot/slackbot/slackbot/manager.py
24,25
14,77
init_plugins
PluginsManager
25,33
25,33
class PluginsManager(object): def __init__(self): pass commands = { 'respond_to': {}, 'listen_to': {}, 'default_reply': {} } def init_plugins(self): FILL_FUNC_BODY def _load_plugins(self, plugin): logger.info('loading plugin "%s"', plugin) path_name =...
class PluginsManager(object): def __init__(self): pass commands = { 'respond_to': {}, 'listen_to': {}, 'default_reply': {} } def init_plugins(self): FILL_FUNC_BODY def _load_plugins(self, plugin): logger.info('loading plugin "%s"', plugin) path_name =...
if hasattr(settings, 'PLUGINS'): plugins = settings.PLUGINS else: plugins = 'slackbot.plugins' for plugin in plugins: self._load_plugins(plugin)
if hasattr(settings, 'PLUGINS'): plugins = settings.PLUGINS else: plugins = 'slackbot.plugins' for plugin in plugins: self._load_plugins(plugin)
15
494
67
561
# -*- coding: utf-8 -*- import os import logging from glob import glob from six import PY2 from importlib import import_module from slackbot import settings from slackbot.utils import to_utf8 logger = logging.getLogger(__name__) class PluginsManager(object): def __init__(self): pass commands = { ...
# -*- coding: utf-8 -*- import os import logging from glob import glob from six import PY2 from importlib import import_module from slackbot import settings from slackbot.utils import to_utf8 logger = logging.getLogger(__name__) class PluginsManager(object): def __init__(self): pass commands = { ...
40,156
/home/hieuvd/dung_repo/raw/stars_02/scrapinghub_slackbot/slackbot
/home/hieuvd/dung_repo/raw/stars_02/scrapinghub_slackbot/slackbot/slackbot/plugins/hello.py
31,33
1,65
hello_reply_formatting
33,37
33,37
#coding: UTF-8 import re from slackbot.bot import respond_to from slackbot.bot import listen_to @respond_to('hello$', re.IGNORECASE) def hello_reply(message): message.reply('hello sender!') @respond_to('^reply_webapi$') def hello_webapi(message): message.reply_webapi('hello there!', attachments=[{ '...
#coding: UTF-8 import re from slackbot.bot import respond_to from slackbot.bot import listen_to @respond_to('hello$', re.IGNORECASE) def hello_reply(message): message.reply('hello sender!') @respond_to('^reply_webapi$') def hello_webapi(message): message.reply_webapi('hello there!', attachments=[{ '...
# Format message with italic style message.reply('_hello_ sender!')
# Format message with italic style message.reply('_hello_ sender!')
8
476
28
504
#coding: UTF-8 import re from slackbot.bot import respond_to from slackbot.bot import listen_to @respond_to('hello$', re.IGNORECASE) def hello_reply(message): message.reply('hello sender!') @respond_to('^reply_webapi$') def hello_webapi(message): message.reply_webapi('hello there!', attachments=[{ '...
#coding: UTF-8 import re from slackbot.bot import respond_to from slackbot.bot import listen_to @respond_to('hello$', re.IGNORECASE) def hello_reply(message): message.reply('hello sender!') @respond_to('^reply_webapi$') def hello_webapi(message): message.reply_webapi('hello there!', attachments=[{ '...
40,157
/home/hieuvd/dung_repo/raw/stars_02/scrapinghub_slackbot/slackbot
/home/hieuvd/dung_repo/raw/stars_02/scrapinghub_slackbot/slackbot/slackbot/plugins/upload.py
26,28
1,32
upload_content
28,32
28,32
# coding=utf8 import os from slackbot.bot import respond_to from slackbot.utils import download_file, create_tmp_file @respond_to(r'upload \<?(.*)\>?') def upload(message, thing): # message.channel.upload_file(slack_filename, local_filename, # initial_comment='') if thing == '...
# coding=utf8 import os from slackbot.bot import respond_to from slackbot.utils import download_file, create_tmp_file @respond_to(r'upload \<?(.*)\>?') def upload(message, thing): # message.channel.upload_file(slack_filename, local_filename, # initial_comment='') if thing == '...
# message.channel.upload_content(slack_filename, content, # initial_comment='') content=u"你好! here's some data\nthat will appear\nas a plain text snippet" message.channel.upload_content('content.txt', content)
# message.channel.upload_content(slack_filename, content, # initial_comment='') content=u"你好! here's some data\nthat will appear\nas a plain text snippet" message.channel.upload_content('content.txt', content)
17
311
76
387
# coding=utf8 import os from slackbot.bot import respond_to from slackbot.utils import download_file, create_tmp_file @respond_to(r'upload \<?(.*)\>?') def upload(message, thing): # message.channel.upload_file(slack_filename, local_filename, # initial_comment='') if thing == '...
# coding=utf8 import os from slackbot.bot import respond_to from slackbot.utils import download_file, create_tmp_file @respond_to(r'upload \<?(.*)\>?') def upload(message, thing): # message.channel.upload_file(slack_filename, local_filename, # initial_comment='') if thing == '...
40,158
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/demo.py
71,72
1,80
RAFT_infer
72,80
72,80
import sys import argparse import os import cv2 import glob import numpy as np import torch from PIL import Image from .raft import RAFT from .utils import flow_viz from .utils.utils import InputPadder DEVICE = 'cuda' def load_image(imfile): img = np.array(Image.open(imfile)).astype(np.uint8) img = torch.f...
import sys import argparse import os import cv2 import glob import numpy as np import torch from PIL import Image from .raft import RAFT from .utils import flow_viz from .utils.utils import InputPadder DEVICE = 'cuda' def load_image(imfile): img = np.array(Image.open(imfile)).astype(np.uint8) img = torch.f...
model = torch.nn.DataParallel(RAFT(args)) model.load_state_dict(torch.load(args.model)) model = model.module model.to(DEVICE) model.eval() return model
model = torch.nn.DataParallel(RAFT(args)) model.load_state_dict(torch.load(args.model)) model = model.module model.to(DEVICE) model.eval() return model
11
669
73
742
import sys import argparse import os import cv2 import glob import numpy as np import torch from PIL import Image from .raft import RAFT from .utils import flow_viz from .utils.utils import InputPadder DEVICE = 'cuda' def load_image(imfile): img = np.array(Image.open(imfile)).astype(np.uint8) img = torch.f...
import sys import argparse import os import cv2 import glob import numpy as np import torch from PIL import Image from .raft import RAFT from .utils import flow_viz from .utils.utils import InputPadder DEVICE = 'cuda' def load_image(imfile): img = np.array(Image.open(imfile)).astype(np.uint8) img = torch.f...
40,159
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/extractor.py
168,169
118,195
forward
BasicEncoder
169,195
169,195
class BasicEncoder(nn.Module): def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0): super(BasicEncoder, self).__init__() self.norm_fn = norm_fn if self.norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64) elif self.norm_f...
class BasicEncoder(nn.Module): def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0): super(BasicEncoder, self).__init__() self.norm_fn = norm_fn if self.norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64) elif self.norm_f...
# if input is list, combine batch dimension is_list = isinstance(x, tuple) or isinstance(x, list) if is_list: batch_dim = x[0].shape[0] x = torch.cat(x, dim=0) x = self.conv1(x) x = self.norm1(x) x = self.relu1(x) x = self.layer1(x) ...
# if input is list, combine batch dimension is_list = isinstance(x, tuple) or isinstance(x, list) if is_list: batch_dim = x[0].shape[0] x = torch.cat(x, dim=0) x = self.conv1(x) x = self.norm1(x) x = self.relu1(x) x = self.layer1(x) ...
65
671
242
913
import torch import torch.nn as nn import torch.nn.functional as F class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) s...
import torch import torch.nn as nn import torch.nn.functional as F class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) s...
40,160
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/extractor.py
107,108
60,118
forward
BottleneckBlock
108,118
108,118
class BottleneckBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(BottleneckBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes//4, kernel_size=1, padding=0) self.conv2 = nn.Conv2d(planes//4, planes//4, kernel_size=3, padding=1, stride=...
class BottleneckBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(BottleneckBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes//4, kernel_size=1, padding=0) self.conv2 = nn.Conv2d(planes//4, planes//4, kernel_size=3, padding=1, stride=...
y = x y = self.relu(self.norm1(self.conv1(y))) y = self.relu(self.norm2(self.conv2(y))) y = self.relu(self.norm3(self.conv3(y))) if self.downsample is not None: x = self.downsample(x) return self.relu(x+y)
y = x y = self.relu(self.norm1(self.conv1(y))) y = self.relu(self.norm2(self.conv2(y))) y = self.relu(self.norm3(self.conv3(y))) if self.downsample is not None: x = self.downsample(x) return self.relu(x+y)
22
698
115
813
import torch import torch.nn as nn import torch.nn.functional as F class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) s...
import torch import torch.nn as nn import torch.nn.functional as F class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) s...
40,161
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/extractor.py
48,49
6,60
forward
ResidualBlock
49,60
49,60
class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1) ...
class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1) ...
y = x y = self.relu(self.norm1(self.conv1(y))) y = self.relu(self.norm2(self.conv2(y))) if self.downsample is not None: x = self.downsample(x) return self.relu(x+y)
y = x y = self.relu(self.norm1(self.conv1(y))) y = self.relu(self.norm2(self.conv2(y))) if self.downsample is not None: x = self.downsample(x) return self.relu(x+y)
19
563
97
660
import torch import torch.nn as nn import torch.nn.functional as F class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) s...
import torch import torch.nn as nn import torch.nn.functional as F class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) s...
40,162
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/extractor.py
244,245
195,268
forward
SmallEncoder
245,268
245,268
class SmallEncoder(nn.Module): def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0): super(SmallEncoder, self).__init__() self.norm_fn = norm_fn if self.norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=8, num_channels=32) elif self.norm_f...
class SmallEncoder(nn.Module): def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0): super(SmallEncoder, self).__init__() self.norm_fn = norm_fn if self.norm_fn == 'group': self.norm1 = nn.GroupNorm(num_groups=8, num_channels=32) elif self.norm_f...
# if input is list, combine batch dimension is_list = isinstance(x, tuple) or isinstance(x, list) if is_list: batch_dim = x[0].shape[0] x = torch.cat(x, dim=0) x = self.conv1(x) x = self.norm1(x) x = self.relu1(x) x = self.layer1(x) ...
# if input is list, combine batch dimension is_list = isinstance(x, tuple) or isinstance(x, list) if is_list: batch_dim = x[0].shape[0] x = torch.cat(x, dim=0) x = self.conv1(x) x = self.norm1(x) x = self.relu1(x) x = self.layer1(x) ...
65
671
236
907
import torch import torch.nn as nn import torch.nn.functional as F class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) s...
import torch import torch.nn as nn import torch.nn.functional as F class ResidualBlock(nn.Module): def __init__(self, in_planes, planes, norm_fn='group', stride=1): super(ResidualBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) s...
40,163
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/raft.py
73,74
24,147
upsample_flow
RAFT
75,87
74,87
class RAFT(nn.Module): def __init__(self, args): super(RAFT, self).__init__() self.args = args if args.small: self.hidden_dim = hdim = 96 self.context_dim = cdim = 64 args.corr_levels = 4 args.corr_radius = 3 else: self.hi...
class RAFT(nn.Module): def __init__(self, args): super(RAFT, self).__init__() self.args = args if args.small: self.hidden_dim = hdim = 96 self.context_dim = cdim = 64 args.corr_levels = 4 args.corr_radius = 3 else: self.hi...
N, _, H, W = flow.shape mask = mask.view(N, 1, 9, 8, 8, H, W) mask = torch.softmax(mask, dim=2) up_flow = F.unfold(8 * flow, [3,3], padding=1) up_flow = up_flow.view(N, 2, 9, 1, 1, H, W) up_flow = torch.sum(mask * up_flow, dim=2) up_flow = up_flow.permute(0, 1, ...
""" Upsample flow field [H/8, W/8, 2] -> [H, W, 2] using convex combination """ N, _, H, W = flow.shape mask = mask.view(N, 1, 9, 8, 8, H, W) mask = torch.softmax(mask, dim=2) up_flow = F.unfold(8 * flow, [3,3], padding=1) up_flow = up_flow.view(N, 2, 9, 1, 1, H, W) ...
54
1,326
201
1,527
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from .update import BasicUpdateBlock, SmallUpdateBlock from .extractor import BasicEncoder, SmallEncoder from .corr import CorrBlock, AlternateCorrBlock from .utils.utils import bilinear_sampler, coords_grid, upflow8 try: autoca...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from .update import BasicUpdateBlock, SmallUpdateBlock from .extractor import BasicEncoder, SmallEncoder from .corr import CorrBlock, AlternateCorrBlock from .utils.utils import bilinear_sampler, coords_grid, upflow8 try: autoca...
40,164
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/update.py
89,90
79,99
forward
BasicMotionEncoder
90,99
90,99
class BasicMotionEncoder(nn.Module): def __init__(self, args): super(BasicMotionEncoder, self).__init__() cor_planes = args.corr_levels * (2*args.corr_radius + 1)**2 self.convc1 = nn.Conv2d(cor_planes, 256, 1, padding=0) self.convc2 = nn.Conv2d(256, 192, 3, padding=1) self.co...
class BasicMotionEncoder(nn.Module): def __init__(self, args): super(BasicMotionEncoder, self).__init__() cor_planes = args.corr_levels * (2*args.corr_radius + 1)**2 self.convc1 = nn.Conv2d(cor_planes, 256, 1, padding=0) self.convc2 = nn.Conv2d(256, 192, 3, padding=1) self.co...
cor = F.relu(self.convc1(corr)) cor = F.relu(self.convc2(cor)) flo = F.relu(self.convf1(flow)) flo = F.relu(self.convf2(flo)) cor_flo = torch.cat([cor, flo], dim=1) out = F.relu(self.conv(cor_flo)) return torch.cat([out, flow], dim=1)
cor = F.relu(self.convc1(corr)) cor = F.relu(self.convc2(cor)) flo = F.relu(self.convf1(flow)) flo = F.relu(self.convf2(flo)) cor_flo = torch.cat([cor, flo], dim=1) out = F.relu(self.conv(cor_flo)) return torch.cat([out, flow], dim=1)
24
251
132
383
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
40,165
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/update.py
127,128
114,140
forward
BasicUpdateBlock
128,140
128,140
class BasicUpdateBlock(nn.Module): def __init__(self, args, hidden_dim=128, input_dim=128): super(BasicUpdateBlock, self).__init__() self.args = args self.encoder = BasicMotionEncoder(args) self.gru = SepConvGRU(hidden_dim=hidden_dim, input_dim=128+hidden_dim) self.flow_head ...
class BasicUpdateBlock(nn.Module): def __init__(self, args, hidden_dim=128, input_dim=128): super(BasicUpdateBlock, self).__init__() self.args = args self.encoder = BasicMotionEncoder(args) self.gru = SepConvGRU(hidden_dim=hidden_dim, input_dim=128+hidden_dim) self.flow_head ...
motion_features = self.encoder(flow, corr) inp = torch.cat([inp, motion_features], dim=1) net = self.gru(net, inp) delta_flow = self.flow_head(net) # scale mask to balence gradients mask = .25 * self.mask(net) return net, mask, delta_flow
motion_features = self.encoder(flow, corr) inp = torch.cat([inp, motion_features], dim=1) net = self.gru(net, inp) delta_flow = self.flow_head(net) # scale mask to balence gradients mask = .25 * self.mask(net) return net, mask, delta_flow
31
242
116
358
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
40,166
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/update.py
23,24
16,33
forward
ConvGRU
24,33
24,33
class ConvGRU(nn.Module): def __init__(self, hidden_dim=128, input_dim=192+128): super(ConvGRU, self).__init__() self.convz = nn.Conv2d(hidden_dim+input_dim, hidden_dim, 3, padding=1) self.convr = nn.Conv2d(hidden_dim+input_dim, hidden_dim, 3, padding=1) self.convq = nn.Conv2d(hidden...
class ConvGRU(nn.Module): def __init__(self, hidden_dim=128, input_dim=192+128): super(ConvGRU, self).__init__() self.convz = nn.Conv2d(hidden_dim+input_dim, hidden_dim, 3, padding=1) self.convr = nn.Conv2d(hidden_dim+input_dim, hidden_dim, 3, padding=1) self.convq = nn.Conv2d(hidden...
hx = torch.cat([h, x], dim=1) z = torch.sigmoid(self.convz(hx)) r = torch.sigmoid(self.convr(hx)) q = torch.tanh(self.convq(torch.cat([r*h, x], dim=1))) h = (1-z) * h + z * q return h
hx = torch.cat([h, x], dim=1) z = torch.sigmoid(self.convz(hx)) r = torch.sigmoid(self.convr(hx)) q = torch.tanh(self.convq(torch.cat([r*h, x], dim=1))) h = (1-z) * h + z * q return h
27
178
117
295
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
40,167
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/update.py
13,14
6,16
forward
FlowHead
14,16
14,16
class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) self.relu = nn.ReLU(inplace=True) def forward(self, x): ...
class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) self.relu = nn.ReLU(inplace=True) def forward(self, x): ...
return self.conv2(self.relu(self.conv1(x)))
return self.conv2(self.relu(self.conv1(x)))
2
144
23
167
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
40,168
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/update.py
45,46
33,62
forward
SepConvGRU
46,62
46,62
class SepConvGRU(nn.Module): def __init__(self, hidden_dim=128, input_dim=192+128): super(SepConvGRU, self).__init__() self.convz1 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (1,5), padding=(0,2)) self.convr1 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (1,5), padding=(0,2)) self....
class SepConvGRU(nn.Module): def __init__(self, hidden_dim=128, input_dim=192+128): super(SepConvGRU, self).__init__() self.convz1 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (1,5), padding=(0,2)) self.convr1 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (1,5), padding=(0,2)) self....
# horizontal hx = torch.cat([h, x], dim=1) z = torch.sigmoid(self.convz1(hx)) r = torch.sigmoid(self.convr1(hx)) q = torch.tanh(self.convq1(torch.cat([r*h, x], dim=1))) h = (1-z) * h + z * q # vertical hx = torch.cat([h, x], dim=1) z = tor...
# horizontal hx = torch.cat([h, x], dim=1) z = torch.sigmoid(self.convz1(hx)) r = torch.sigmoid(self.convr1(hx)) q = torch.tanh(self.convq1(torch.cat([r*h, x], dim=1))) h = (1-z) * h + z * q # vertical hx = torch.cat([h, x], dim=1) z = tor...
56
320
241
561
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
40,169
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/update.py
71,72
62,79
forward
SmallMotionEncoder
72,79
72,79
class SmallMotionEncoder(nn.Module): def __init__(self, args): super(SmallMotionEncoder, self).__init__() cor_planes = args.corr_levels * (2*args.corr_radius + 1)**2 self.convc1 = nn.Conv2d(cor_planes, 96, 1, padding=0) self.convf1 = nn.Conv2d(2, 64, 7, padding=3) self.convf2...
class SmallMotionEncoder(nn.Module): def __init__(self, args): super(SmallMotionEncoder, self).__init__() cor_planes = args.corr_levels * (2*args.corr_radius + 1)**2 self.convc1 = nn.Conv2d(cor_planes, 96, 1, padding=0) self.convf1 = nn.Conv2d(2, 64, 7, padding=3) self.convf2...
cor = F.relu(self.convc1(corr)) flo = F.relu(self.convf1(flow)) flo = F.relu(self.convf2(flo)) cor_flo = torch.cat([cor, flo], dim=1) out = F.relu(self.conv(cor_flo)) return torch.cat([out, flow], dim=1)
cor = F.relu(self.convc1(corr)) flo = F.relu(self.convf1(flow)) flo = F.relu(self.convf2(flo)) cor_flo = torch.cat([cor, flo], dim=1) out = F.relu(self.conv(cor_flo)) return torch.cat([out, flow], dim=1)
21
210
112
322
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
40,170
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/update.py
106,107
99,114
forward
SmallUpdateBlock
107,114
107,114
class SmallUpdateBlock(nn.Module): def __init__(self, args, hidden_dim=96): super(SmallUpdateBlock, self).__init__() self.encoder = SmallMotionEncoder(args) self.gru = ConvGRU(hidden_dim=hidden_dim, input_dim=82+64) self.flow_head = FlowHead(hidden_dim, hidden_dim=128) def forwa...
class SmallUpdateBlock(nn.Module): def __init__(self, args, hidden_dim=96): super(SmallUpdateBlock, self).__init__() self.encoder = SmallMotionEncoder(args) self.gru = ConvGRU(hidden_dim=hidden_dim, input_dim=82+64) self.flow_head = FlowHead(hidden_dim, hidden_dim=128) def forwa...
motion_features = self.encoder(flow, corr) inp = torch.cat([inp, motion_features], dim=1) net = self.gru(net, inp) delta_flow = self.flow_head(net) return net, None, delta_flow
motion_features = self.encoder(flow, corr) inp = torch.cat([inp, motion_features], dim=1) net = self.gru(net, inp) delta_flow = self.flow_head(net) return net, None, delta_flow
20
137
84
221
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
import torch import torch.nn as nn import torch.nn.functional as F class FlowHead(nn.Module): def __init__(self, input_dim=128, hidden_dim=256): super(FlowHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1) ...
40,171
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/utils/augmentor.py
52,53
15,122
eraser_transform
FlowAugmentor
54,67
53,67
class FlowAugmentor: def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=True): # spatial augmentation params self.crop_size = crop_size self.min_scale = min_scale self.max_scale = max_scale self.spatial_aug_prob = 0.8 self.stretch_prob = 0.8...
class FlowAugmentor: def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=True): # spatial augmentation params self.crop_size = crop_size self.min_scale = min_scale self.max_scale = max_scale self.spatial_aug_prob = 0.8 self.stretch_prob = 0.8...
ht, wd = img1.shape[:2] if np.random.rand() < self.eraser_aug_prob: mean_color = np.mean(img2.reshape(-1, 3), axis=0) for _ in range(np.random.randint(1, 3)): x0 = np.random.randint(0, wd) y0 = np.random.randint(0, ht) dx = np.rand...
""" Occlusion augmentation """ ht, wd = img1.shape[:2] if np.random.rand() < self.eraser_aug_prob: mean_color = np.mean(img2.reshape(-1, 3), axis=0) for _ in range(np.random.randint(1, 3)): x0 = np.random.randint(0, wd) y0 = np.random.rand...
42
1,410
204
1,614
import numpy as np import random import math from PIL import Image import cv2 cv2.setNumThreads(0) cv2.ocl.setUseOpenCL(False) import torch from torchvision.transforms import ColorJitter import torch.nn.functional as F class FlowAugmentor: def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=Tru...
import numpy as np import random import math from PIL import Image import cv2 cv2.setNumThreads(0) cv2.ocl.setUseOpenCL(False) import torch from torchvision.transforms import ColorJitter import torch.nn.functional as F class FlowAugmentor: def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=Tru...
40,172
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/utils/augmentor.py
161,162
122,247
resize_sparse_flow_map
SparseFlowAugmentor
162,195
162,195
class SparseFlowAugmentor: def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=False): # spatial augmentation params self.crop_size = crop_size self.min_scale = min_scale self.max_scale = max_scale self.spatial_aug_prob = 0.8 self.stretch_prob = 0.8 ...
class SparseFlowAugmentor: def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=False): # spatial augmentation params self.crop_size = crop_size self.min_scale = min_scale self.max_scale = max_scale self.spatial_aug_prob = 0.8 self.stretch_prob = 0.8 ...
ht, wd = flow.shape[:2] coords = np.meshgrid(np.arange(wd), np.arange(ht)) coords = np.stack(coords, axis=-1) coords = coords.reshape(-1, 2).astype(np.float32) flow = flow.reshape(-1, 2).astype(np.float32) valid = valid.reshape(-1).astype(np.float32) coords0 = c...
ht, wd = flow.shape[:2] coords = np.meshgrid(np.arange(wd), np.arange(ht)) coords = np.stack(coords, axis=-1) coords = coords.reshape(-1, 2).astype(np.float32) flow = flow.reshape(-1, 2).astype(np.float32) valid = valid.reshape(-1).astype(np.float32) coords0 = c...
105
1,474
453
1,927
import numpy as np import random import math from PIL import Image import cv2 cv2.setNumThreads(0) cv2.ocl.setUseOpenCL(False) import torch from torchvision.transforms import ColorJitter import torch.nn.functional as F class FlowAugmentor: def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=Tru...
import numpy as np import random import math from PIL import Image import cv2 cv2.setNumThreads(0) cv2.ocl.setUseOpenCL(False) import torch from torchvision.transforms import ColorJitter import torch.nn.functional as F class FlowAugmentor: def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=Tru...
40,173
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/utils/flow_viz.py
70,71
1,133
flow_uv_to_colors
85,109
71,109
# Flow visualization code used from https://github.com/tomrunia/OpticalFlow_Visualization # MIT License # # Copyright (c) 2018 Tom Runia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software wi...
# Flow visualization code used from https://github.com/tomrunia/OpticalFlow_Visualization # MIT License # # Copyright (c) 2018 Tom Runia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software wi...
flow_image = np.zeros((u.shape[0], u.shape[1], 3), np.uint8) colorwheel = make_colorwheel() # shape [55x3] ncols = colorwheel.shape[0] rad = np.sqrt(np.square(u) + np.square(v)) a = np.arctan2(-v, -u)/np.pi fk = (a+1) / 2*(ncols-1) k0 = np.floor(fk).astype(np.int32) k1 = k0 + 1 k1[k...
""" Applies the flow color wheel to (possibly clipped) flow components u and v. According to the C++ source code of Daniel Scharstein According to the Matlab source code of Deqing Sun Args: u (np.ndarray): Input horizontal flow of shape [H,W] v (np.ndarray): Input vertical flow of ...
113
1,317
394
1,711
# Flow visualization code used from https://github.com/tomrunia/OpticalFlow_Visualization # MIT License # # Copyright (c) 2018 Tom Runia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software wi...
# Flow visualization code used from https://github.com/tomrunia/OpticalFlow_Visualization # MIT License # # Copyright (c) 2018 Tom Runia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software wi...
40,174
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/utils/flow_viz_pt.py
73,75
1,119
_make_colorwheel
83,119
75,119
# Flow visualization code adapted from https://github.com/tomrunia/OpticalFlow_Visualization import torch torch.pi = torch.acos(torch.zeros(1)).item() * 2 # which is 3.1415927410125732 @torch.no_grad() def flow_to_image(flow: torch.Tensor) -> torch.Tensor: """ Converts a flow to an RGB image. Args: ...
# Flow visualization code adapted from https://github.com/tomrunia/OpticalFlow_Visualization import torch torch.pi = torch.acos(torch.zeros(1)).item() * 2 # which is 3.1415927410125732 @torch.no_grad() def flow_to_image(flow: torch.Tensor) -> torch.Tensor: """ Converts a flow to an RGB image. Args: ...
RY = 15 YG = 6 GC = 4 CB = 11 BM = 13 MR = 6 ncols = RY + YG + GC + CB + BM + MR colorwheel = torch.zeros((ncols, 3)) col = 0 # RY colorwheel[0:RY, 0] = 255 colorwheel[0:RY, 1] = torch.floor(255. * torch.arange(0., RY) / RY) col = col + RY # YG colorwheel[c...
""" Generates a color wheel for optical flow visualization as presented in: Baker et al. "A Database and Evaluation Methodology for Optical Flow" (ICCV, 2007) URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdf. Returns: colorwheel (Tensor[55, 3]): Colorwheel Tensor. """ RY ...
199
1,095
546
1,641
# Flow visualization code adapted from https://github.com/tomrunia/OpticalFlow_Visualization import torch torch.pi = torch.acos(torch.zeros(1)).item() * 2 # which is 3.1415927410125732 @torch.no_grad() def flow_to_image(flow: torch.Tensor) -> torch.Tensor: """ Converts a flow to an RGB image. Args: ...
# Flow visualization code adapted from https://github.com/tomrunia/OpticalFlow_Visualization import torch torch.pi = torch.acos(torch.zeros(1)).item() * 2 # which is 3.1415927410125732 @torch.no_grad() def flow_to_image(flow: torch.Tensor) -> torch.Tensor: """ Converts a flow to an RGB image. Args: ...
40,175
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/utils/utils.py
26,27
1,83
forward_interpolate
27,57
27,57
import torch import torch.nn.functional as F import numpy as np from scipy import interpolate class InputPadder: """ Pads images such that dimensions are divisible by 8 """ def __init__(self, dims, mode='sintel'): self.ht, self.wd = dims[-2:] pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8 ...
import torch import torch.nn.functional as F import numpy as np from scipy import interpolate class InputPadder: """ Pads images such that dimensions are divisible by 8 """ def __init__(self, dims, mode='sintel'): self.ht, self.wd = dims[-2:] pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8 ...
flow = flow.detach().cpu().numpy() dx, dy = flow[0], flow[1] ht, wd = dx.shape x0, y0 = np.meshgrid(np.arange(wd), np.arange(ht)) x1 = x0 + dx y1 = y0 + dy x1 = x1.reshape(-1) y1 = y1.reshape(-1) dx = dx.reshape(-1) dy = dy.reshape(-1) valid = (x1 > 0) & (x1 < wd) & (...
flow = flow.detach().cpu().numpy() dx, dy = flow[0], flow[1] ht, wd = dx.shape x0, y0 = np.meshgrid(np.arange(wd), np.arange(ht)) x1 = x0 + dx y1 = y0 + dy x1 = x1.reshape(-1) y1 = y1.reshape(-1) dx = dx.reshape(-1) dy = dy.reshape(-1) valid = (x1 > 0) & (x1 < wd) & (...
95
735
363
1,098
import torch import torch.nn.functional as F import numpy as np from scipy import interpolate class InputPadder: """ Pads images such that dimensions are divisible by 8 """ def __init__(self, dims, mode='sintel'): self.ht, self.wd = dims[-2:] pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8 ...
import torch import torch.nn.functional as F import numpy as np from scipy import interpolate class InputPadder: """ Pads images such that dimensions are divisible by 8 """ def __init__(self, dims, mode='sintel'): self.ht, self.wd = dims[-2:] pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8 ...
40,176
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/RAFT/utils/utils.py
18,19
7,26
pad
InputPadder
19,21
19,21
class InputPadder: """ Pads images such that dimensions are divisible by 8 """ def __init__(self, dims, mode='sintel'): self.ht, self.wd = dims[-2:] pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8 pad_wd = (((self.wd // 8) + 1) * 8 - self.wd) % 8 if mode == 'sintel': ...
class InputPadder: """ Pads images such that dimensions are divisible by 8 """ def __init__(self, dims, mode='sintel'): self.ht, self.wd = dims[-2:] pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8 pad_wd = (((self.wd // 8) + 1) * 8 - self.wd) % 8 if mode == 'sintel': ...
return [F.pad(x, self._pad, mode='replicate') for x in inputs]
return [F.pad(x, self._pad, mode='replicate') for x in inputs]
8
300
29
329
import torch import torch.nn.functional as F import numpy as np from scipy import interpolate class InputPadder: """ Pads images such that dimensions are divisible by 8 """ def __init__(self, dims, mode='sintel'): self.ht, self.wd = dims[-2:] pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8 ...
import torch import torch.nn.functional as F import numpy as np from scipy import interpolate class InputPadder: """ Pads images such that dimensions are divisible by 8 """ def __init__(self, dims, mode='sintel'): self.ht, self.wd = dims[-2:] pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8 ...
40,177
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/core/dist.py
29,30
1,48
get_local_rank
33,41
30,41
import os import torch def get_world_size(): """Find OMPI world size without calling mpi functions :rtype: int """ if os.environ.get('PMI_SIZE') is not None: return int(os.environ.get('PMI_SIZE') or 1) elif os.environ.get('OMPI_COMM_WORLD_SIZE') is not None: return int(os.environ.g...
import os import torch def get_world_size(): """Find OMPI world size without calling mpi functions :rtype: int """ if os.environ.get('PMI_SIZE') is not None: return int(os.environ.get('PMI_SIZE') or 1) elif os.environ.get('OMPI_COMM_WORLD_SIZE') is not None: return int(os.environ.g...
if os.environ.get('MPI_LOCALRANKID') is not None: return int(os.environ.get('MPI_LOCALRANKID') or 0) elif os.environ.get('OMPI_COMM_WORLD_LOCAL_RANK') is not None: return int(os.environ.get('OMPI_COMM_WORLD_LOCAL_RANK') or 0) else: return 0
"""Find OMPI local rank without calling mpi functions :rtype: int """ if os.environ.get('MPI_LOCALRANKID') is not None: return int(os.environ.get('MPI_LOCALRANKID') or 0) elif os.environ.get('OMPI_COMM_WORLD_LOCAL_RANK') is not None: return int(os.environ.get('OMPI_COMM_WORLD_LOCAL_R...
21
467
131
598
import os import torch def get_world_size(): """Find OMPI world size without calling mpi functions :rtype: int """ if os.environ.get('PMI_SIZE') is not None: return int(os.environ.get('PMI_SIZE') or 1) elif os.environ.get('OMPI_COMM_WORLD_SIZE') is not None: return int(os.environ.g...
import os import torch def get_world_size(): """Find OMPI world size without calling mpi functions :rtype: int """ if os.environ.get('PMI_SIZE') is not None: return int(os.environ.get('PMI_SIZE') or 1) elif os.environ.get('OMPI_COMM_WORLD_SIZE') is not None: return int(os.environ.g...
40,178
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/core/prefetch_dataloader.py
80,81
63,84
reset
CPUPrefetcher
81,84
81,84
class CPUPrefetcher(): """CPU prefetcher. Args: loader: Dataloader. """ def __init__(self, loader): self.ori_loader = loader self.loader = iter(loader) def next(self): try: return next(self.loader) except StopIteration: return None ...
class CPUPrefetcher(): """CPU prefetcher. Args: loader: Dataloader. """ def __init__(self, loader): self.ori_loader = loader self.loader = iter(loader) def next(self): try: return next(self.loader) except StopIteration: return None ...
self.loader = iter(self.ori_loader)
self.loader = iter(self.ori_loader)
3
114
19
133
import queue as Queue import threading import torch from torch.utils.data import DataLoader class PrefetchGenerator(threading.Thread): """A general prefetch generator. Ref: https://stackoverflow.com/questions/7323664/python-generator-pre-fetch Args: generator: Python generator. num_p...
import queue as Queue import threading import torch from torch.utils.data import DataLoader class PrefetchGenerator(threading.Thread): """A general prefetch generator. Ref: https://stackoverflow.com/questions/7323664/python-generator-pre-fetch Args: generator: Python generator. num_p...
40,179
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/core/prefetch_dataloader.py
105,106
84,126
preload
CUDAPrefetcher
106,117
106,117
class CUDAPrefetcher(): """CUDA prefetcher. Ref: https://github.com/NVIDIA/apex/issues/304# It may consums more GPU memory. Args: loader: Dataloader. opt (dict): Options. """ def __init__(self, loader, opt): self.ori_loader = loader self.loader = iter(load...
class CUDAPrefetcher(): """CUDA prefetcher. Ref: https://github.com/NVIDIA/apex/issues/304# It may consums more GPU memory. Args: loader: Dataloader. opt (dict): Options. """ def __init__(self, loader, opt): self.ori_loader = loader self.loader = iter(load...
try: self.batch = next(self.loader) # self.batch is a dict except StopIteration: self.batch = None return None # put tensors to gpu with torch.cuda.stream(self.stream): for k, v in self.batch.items(): if torch.is_tensor(v):...
try: self.batch = next(self.loader) # self.batch is a dict except StopIteration: self.batch = None return None # put tensors to gpu with torch.cuda.stream(self.stream): for k, v in self.batch.items(): if torch.is_tensor(v):...
34
262
133
395
import queue as Queue import threading import torch from torch.utils.data import DataLoader class PrefetchGenerator(threading.Thread): """A general prefetch generator. Ref: https://stackoverflow.com/questions/7323664/python-generator-pre-fetch Args: generator: Python generator. num_p...
import queue as Queue import threading import torch from torch.utils.data import DataLoader class PrefetchGenerator(threading.Thread): """A general prefetch generator. Ref: https://stackoverflow.com/questions/7323664/python-generator-pre-fetch Args: generator: Python generator. num_p...
40,180
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/core/prefetch_dataloader.py
25,26
7,40
run
PrefetchGenerator
26,30
26,30
class PrefetchGenerator(threading.Thread): """A general prefetch generator. Ref: https://stackoverflow.com/questions/7323664/python-generator-pre-fetch Args: generator: Python generator. num_prefetch_queue (int): Number of prefetch queue. """ def __init__(self, generator, num_...
class PrefetchGenerator(threading.Thread): """A general prefetch generator. Ref: https://stackoverflow.com/questions/7323664/python-generator-pre-fetch Args: generator: Python generator. num_prefetch_queue (int): Number of prefetch queue. """ def __init__(self, generator, num_...
for item in self.generator: self.queue.put(item) self.queue.put(None)
for item in self.generator: self.queue.put(item) self.queue.put(None)
6
225
34
259
import queue as Queue import threading import torch from torch.utils.data import DataLoader class PrefetchGenerator(threading.Thread): """A general prefetch generator. Ref: https://stackoverflow.com/questions/7323664/python-generator-pre-fetch Args: generator: Python generator. num_p...
import queue as Queue import threading import torch from torch.utils.data import DataLoader class PrefetchGenerator(threading.Thread): """A general prefetch generator. Ref: https://stackoverflow.com/questions/7323664/python-generator-pre-fetch Args: generator: Python generator. num_p...
40,183
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/misc.py
59,60
1,132
gpu_is_available
60,65
60,65
import os import re import random import time import torch import torch.nn as nn import logging import numpy as np from os import path as osp def constant_init(module, val, bias=0): if hasattr(module, 'weight') and module.weight is not None: nn.init.constant_(module.weight, val) if hasattr(module, 'bia...
import os import re import random import time import torch import torch.nn as nn import logging import numpy as np from os import path as osp def constant_init(module, val, bias=0): if hasattr(module, 'weight') and module.weight is not None: nn.init.constant_(module.weight, val) if hasattr(module, 'bia...
if IS_HIGH_VERSION: if torch.backends.mps.is_available(): return True return True if torch.cuda.is_available() and torch.backends.cudnn.is_available() else False
if IS_HIGH_VERSION: if torch.backends.mps.is_available(): return True return True if torch.cuda.is_available() and torch.backends.cudnn.is_available() else False
14
1,395
68
1,463
import os import re import random import time import torch import torch.nn as nn import logging import numpy as np from os import path as osp def constant_init(module, val, bias=0): if hasattr(module, 'weight') and module.weight is not None: nn.init.constant_(module.weight, val) if hasattr(module, 'bia...
import os import re import random import time import torch import torch.nn as nn import logging import numpy as np from os import path as osp def constant_init(module, val, bias=0): if hasattr(module, 'weight') and module.weight is not None: nn.init.constant_(module.weight, val) if hasattr(module, 'bia...
40,184
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/modules/base_module.py
11,12
7,64
print_network
BaseNetwork
12,22
12,22
class BaseNetwork(nn.Module): def __init__(self): super(BaseNetwork, self).__init__() def print_network(self): FILL_FUNC_BODY def init_weights(self, init_type='normal', gain=0.02): ''' initialize network's weights init_type: normal | xavier | kaiming | orthogonal http...
class BaseNetwork(nn.Module): def __init__(self): super(BaseNetwork, self).__init__() def print_network(self): FILL_FUNC_BODY def init_weights(self, init_type='normal', gain=0.02): ''' initialize network's weights init_type: normal | xavier | kaiming | orthogonal http...
if isinstance(self, list): self = self[0] num_params = 0 for param in self.parameters(): num_params += param.numel() print( 'Network [%s] was created. Total number of parameters: %.1f million. ' 'To see the architecture, do print(network).'...
if isinstance(self, list): self = self[0] num_params = 0 for param in self.parameters(): num_params += param.numel() print( 'Network [%s] was created. Total number of parameters: %.1f million. ' 'To see the architecture, do print(network).'...
39
686
122
808
import torch import torch.nn as nn import torch.nn.functional as F from functools import reduce class BaseNetwork(nn.Module): def __init__(self): super(BaseNetwork, self).__init__() def print_network(self): FILL_FUNC_BODY def init_weights(self, init_type='normal', gain=0.02): ''' i...
import torch import torch.nn as nn import torch.nn.functional as F from functools import reduce class BaseNetwork(nn.Module): def __init__(self): super(BaseNetwork, self).__init__() def print_network(self): FILL_FUNC_BODY def init_weights(self, init_type='normal', gain=0.02): ''' i...
40,185
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/modules/base_module.py
104,105
94,132
forward
FusionFeedForward
105,132
105,132
class FusionFeedForward(nn.Module): def __init__(self, dim, hidden_dim=1960, t2t_params=None): super(FusionFeedForward, self).__init__() # We set hidden_dim as a default to 1960 self.fc1 = nn.Sequential(nn.Linear(dim, hidden_dim)) self.fc2 = nn.Sequential(nn.GELU(), nn.Linear(hidden_...
class FusionFeedForward(nn.Module): def __init__(self, dim, hidden_dim=1960, t2t_params=None): super(FusionFeedForward, self).__init__() # We set hidden_dim as a default to 1960 self.fc1 = nn.Sequential(nn.Linear(dim, hidden_dim)) self.fc2 = nn.Sequential(nn.GELU(), nn.Linear(hidden_...
n_vecs = 1 for i, d in enumerate(self.t2t_params['kernel_size']): n_vecs *= int((output_size[i] + 2 * self.t2t_params['padding'][i] - (d - 1) - 1) / self.t2t_params['stride'][i] + 1) x = self.fc1(x) b, n, c = x.size() normalizer = x.new_one...
n_vecs = 1 for i, d in enumerate(self.t2t_params['kernel_size']): n_vecs *= int((output_size[i] + 2 * self.t2t_params['padding'][i] - (d - 1) - 1) / self.t2t_params['stride'][i] + 1) x = self.fc1(x) b, n, c = x.size() normalizer = x.new_one...
78
210
460
670
import torch import torch.nn as nn import torch.nn.functional as F from functools import reduce class BaseNetwork(nn.Module): def __init__(self): super(BaseNetwork, self).__init__() def print_network(self): if isinstance(self, list): self = self[0] num_params = 0 f...
import torch import torch.nn as nn import torch.nn.functional as F from functools import reduce class BaseNetwork(nn.Module): def __init__(self): super(BaseNetwork, self).__init__() def print_network(self): if isinstance(self, list): self = self[0] num_params = 0 f...
40,186
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/modules/base_module.py
79,80
64,94
forward
Vec2Feat
80,94
80,94
class Vec2Feat(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(Vec2Feat, self).__init__() self.relu = nn.LeakyReLU(0.2, inplace=True) c_out = reduce((lambda x, y: x * y), kernel_size) * channel self.embedding = nn.Linear(hidden, c_out) sel...
class Vec2Feat(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(Vec2Feat, self).__init__() self.relu = nn.LeakyReLU(0.2, inplace=True) c_out = reduce((lambda x, y: x * y), kernel_size) * channel self.embedding = nn.Linear(hidden, c_out) sel...
b_, _, _, _, c_ = x.shape x = x.view(b_, -1, c_) feat = self.embedding(x) b, _, c = feat.size() feat = feat.view(b * t, -1, c).permute(0, 2, 1) feat = F.fold(feat, output_size=output_size, kernel_size=self.kernel_size, ...
b_, _, _, _, c_ = x.shape x = x.view(b_, -1, c_) feat = self.embedding(x) b, _, c = feat.size() feat = feat.view(b * t, -1, c).permute(0, 2, 1) feat = F.fold(feat, output_size=output_size, kernel_size=self.kernel_size, ...
41
212
164
376
import torch import torch.nn as nn import torch.nn.functional as F from functools import reduce class BaseNetwork(nn.Module): def __init__(self): super(BaseNetwork, self).__init__() def print_network(self): if isinstance(self, list): self = self[0] num_params = 0 f...
import torch import torch.nn as nn import torch.nn.functional as F from functools import reduce class BaseNetwork(nn.Module): def __init__(self): super(BaseNetwork, self).__init__() def print_network(self): if isinstance(self, list): self = self[0] num_params = 0 f...
40,187
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/modules/deformconv.py
40,41
7,55
init_weights
ModulatedDeformConv2d
41,53
41,53
class ModulatedDeformConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, deform_groups=1, bias...
class ModulatedDeformConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, deform_groups=1, bias...
n = self.in_channels for k in self.kernel_size: n *= k stdv = 1. / math.sqrt(n) self.weight.data.uniform_(-stdv, stdv) if self.bias is not None: self.bias.data.zero_() if hasattr(self, 'conv_offset'): self.conv_offset.weight.data.zero_...
n = self.in_channels for k in self.kernel_size: n *= k stdv = 1. / math.sqrt(n) self.weight.data.uniform_(-stdv, stdv) if self.bias is not None: self.bias.data.zero_() if hasattr(self, 'conv_offset'): self.conv_offset.weight.data.zero_...
28
362
140
502
import torch import torch.nn as nn from torch.nn import init as init from torch.nn.modules.utils import _pair, _single import math class ModulatedDeformConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, ...
import torch import torch.nn as nn from torch.nn import init as init from torch.nn.modules.utils import _pair, _single import math class ModulatedDeformConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, ...
40,189
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/modules/flow_comp_raft.py
232,233
228,247
forward
EdgeLoss
233,247
233,247
class EdgeLoss(nn.Module): def __init__(self): super().__init__() def forward(self, pred_edges, gt_edges, masks): FILL_FUNC_BODY
class EdgeLoss(nn.Module): def __init__(self): super().__init__() def forward(self, pred_edges, gt_edges, masks): FILL_FUNC_BODY
# pred_flows: b t-1 1 h w loss = 0 h, w = pred_edges[0].shape[-2:] masks = [masks[:,:-1,...].contiguous(), masks[:, 1:, ...].contiguous()] for i in range(len(pred_edges)): # print(f'edges_{i}', torch.sum(gt_edges[i])) # debug combined_edge = pred_edges[i]...
# pred_flows: b t-1 1 h w loss = 0 h, w = pred_edges[0].shape[-2:] masks = [masks[:,:-1,...].contiguous(), masks[:, 1:, ...].contiguous()] for i in range(len(pred_edges)): # print(f'edges_{i}', torch.sum(gt_edges[i])) # debug combined_edge = pred_edges[i]...
53
58
273
331
import argparse import torch import torch.nn as nn import torch.nn.functional as F from RAFT import RAFT from model.modules.flow_loss_utils import flow_warp, ternary_loss2 def initialize_RAFT(model_path='weights/raft-things.pth', device='cuda'): """Initializes the RAFT model. """ args = argparse.Argument...
import argparse import torch import torch.nn as nn import torch.nn.functional as F from RAFT import RAFT from model.modules.flow_loss_utils import flow_warp, ternary_loss2 def initialize_RAFT(model_path='weights/raft-things.pth', device='cuda'): """Initializes the RAFT model. """ args = argparse.Argument...
40,190
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/modules/flow_comp_raft.py
178,179
173,207
forward
FlowLoss
179,207
179,207
class FlowLoss(nn.Module): def __init__(self): super().__init__() self.l1_criterion = nn.L1Loss() def forward(self, pred_flows, gt_flows, masks, frames): FILL_FUNC_BODY
class FlowLoss(nn.Module): def __init__(self): super().__init__() self.l1_criterion = nn.L1Loss() def forward(self, pred_flows, gt_flows, masks, frames): FILL_FUNC_BODY
# pred_flows: b t-1 2 h w loss = 0 warp_loss = 0 h, w = pred_flows[0].shape[-2:] masks = [masks[:,:-1,...].contiguous(), masks[:, 1:, ...].contiguous()] frames0 = frames[:,:-1,...] frames1 = frames[:,1:,...] current_frames = [frames0, frames1] next...
# pred_flows: b t-1 2 h w loss = 0 warp_loss = 0 h, w = pred_flows[0].shape[-2:] masks = [masks[:,:-1,...].contiguous(), masks[:, 1:, ...].contiguous()] frames0 = frames[:,:-1,...] frames1 = frames[:,1:,...] current_frames = [frames0, frames1] next...
100
79
580
659
import argparse import torch import torch.nn as nn import torch.nn.functional as F from RAFT import RAFT from model.modules.flow_loss_utils import flow_warp, ternary_loss2 def initialize_RAFT(model_path='weights/raft-things.pth', device='cuda'): """Initializes the RAFT model. """ args = argparse.Argument...
import argparse import torch import torch.nn as nn import torch.nn.functional as F from RAFT import RAFT from model.modules.flow_loss_utils import flow_warp, ternary_loss2 def initialize_RAFT(model_path='weights/raft-things.pth', device='cuda'): """Initializes the RAFT model. """ args = argparse.Argument...
40,191
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/modules/flow_comp_raft.py
252,253
247,266
forward
FlowSimpleLoss
253,266
253,266
class FlowSimpleLoss(nn.Module): def __init__(self): super().__init__() self.l1_criterion = nn.L1Loss() def forward(self, pred_flows, gt_flows): FILL_FUNC_BODY
class FlowSimpleLoss(nn.Module): def __init__(self): super().__init__() self.l1_criterion = nn.L1Loss() def forward(self, pred_flows, gt_flows): FILL_FUNC_BODY
# pred_flows: b t-1 2 h w loss = 0 h, w = pred_flows[0].shape[-2:] h_orig, w_orig = gt_flows[0].shape[-2:] pred_flows = [f.view(-1, 2, h, w) for f in pred_flows] gt_flows = [f.view(-1, 2, h_orig, w_orig) for f in gt_flows] ds_factor = 1.0*h/h_orig gt_flow...
# pred_flows: b t-1 2 h w loss = 0 h, w = pred_flows[0].shape[-2:] h_orig, w_orig = gt_flows[0].shape[-2:] pred_flows = [f.view(-1, 2, h, w) for f in pred_flows] gt_flows = [f.view(-1, 2, h_orig, w_orig) for f in gt_flows] ds_factor = 1.0*h/h_orig gt_flow...
62
75
243
318
import argparse import torch import torch.nn as nn import torch.nn.functional as F from RAFT import RAFT from model.modules.flow_loss_utils import flow_warp, ternary_loss2 def initialize_RAFT(model_path='weights/raft-things.pth', device='cuda'): """Initializes the RAFT model. """ args = argparse.Argument...
import argparse import torch import torch.nn as nn import torch.nn.functional as F from RAFT import RAFT from model.modules.flow_loss_utils import flow_warp, ternary_loss2 def initialize_RAFT(model_path='weights/raft-things.pth', device='cuda'): """Initializes the RAFT model. """ args = argparse.Argument...
40,192
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/modules/flow_comp_raft.py
39,40
27,59
forward
RAFT_bi
40,59
40,59
class RAFT_bi(nn.Module): """Flow completion loss""" def __init__(self, model_path='weights/raft-things.pth', device='cuda'): super().__init__() self.fix_raft = initialize_RAFT(model_path, device=device) for p in self.fix_raft.parameters(): p.requires_grad = False s...
class RAFT_bi(nn.Module): """Flow completion loss""" def __init__(self, model_path='weights/raft-things.pth', device='cuda'): super().__init__() self.fix_raft = initialize_RAFT(model_path, device=device) for p in self.fix_raft.parameters(): p.requires_grad = False s...
b, l_t, c, h, w = gt_local_frames.size() # print(gt_local_frames.shape) with torch.no_grad(): gtlf_1 = gt_local_frames[:, :-1, :, :, :].reshape(-1, c, h, w) gtlf_2 = gt_local_frames[:, 1:, :, :, :].reshape(-1, c, h, w) # print(gtlf_1.shape) _, gt...
b, l_t, c, h, w = gt_local_frames.size() # print(gt_local_frames.shape) with torch.no_grad(): gtlf_1 = gt_local_frames[:, :-1, :, :, :].reshape(-1, c, h, w) gtlf_2 = gt_local_frames[:, 1:, :, :, :].reshape(-1, c, h, w) # print(gtlf_1.shape) _, gt...
65
158
339
497
import argparse import torch import torch.nn as nn import torch.nn.functional as F from RAFT import RAFT from model.modules.flow_loss_utils import flow_warp, ternary_loss2 def initialize_RAFT(model_path='weights/raft-things.pth', device='cuda'): """Initializes the RAFT model. """ args = argparse.Argument...
import argparse import torch import torch.nn as nn import torch.nn.functional as F from RAFT import RAFT from model.modules.flow_loss_utils import flow_warp, ternary_loss2 def initialize_RAFT(model_path='weights/raft-things.pth', device='cuda'): """Initializes the RAFT model. """ args = argparse.Argument...
40,195
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/modules/sparse_transformer.py
74,75
64,104
forward
FusionFeedForward
75,104
75,104
class FusionFeedForward(nn.Module): def __init__(self, dim, hidden_dim=1960, t2t_params=None): super(FusionFeedForward, self).__init__() # We set hidden_dim as a default to 1960 self.fc1 = nn.Sequential(nn.Linear(dim, hidden_dim)) self.fc2 = nn.Sequential(nn.GELU(), nn.Linear(hidden_...
class FusionFeedForward(nn.Module): def __init__(self, dim, hidden_dim=1960, t2t_params=None): super(FusionFeedForward, self).__init__() # We set hidden_dim as a default to 1960 self.fc1 = nn.Sequential(nn.Linear(dim, hidden_dim)) self.fc2 = nn.Sequential(nn.GELU(), nn.Linear(hidden_...
n_vecs = 1 for i, d in enumerate(self.t2t_params['kernel_size']): n_vecs *= int((output_size[i] + 2 * self.t2t_params['padding'][i] - (d - 1) - 1) / self.t2t_params['stride'][i] + 1) x = self.fc1(x) b, n, c = x.size() normalizer = x.new_one...
n_vecs = 1 for i, d in enumerate(self.t2t_params['kernel_size']): n_vecs *= int((output_size[i] + 2 * self.t2t_params['padding'][i] - (d - 1) - 1) / self.t2t_params['stride'][i] + 1) x = self.fc1(x) b, n, c = x.size() normalizer = x.new_one...
78
210
464
674
import math from functools import reduce import torch import torch.nn as nn import torch.nn.functional as F class SoftSplit(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftSplit, self).__init__() self.kernel_size = kernel_size self.stride = stride ...
import math from functools import reduce import torch import torch.nn as nn import torch.nn.functional as F class SoftSplit(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftSplit, self).__init__() self.kernel_size = kernel_size self.stride = stride ...
40,196
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/modules/sparse_transformer.py
49,50
34,64
forward
SoftComp
50,64
50,64
class SoftComp(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftComp, self).__init__() self.relu = nn.LeakyReLU(0.2, inplace=True) c_out = reduce((lambda x, y: x * y), kernel_size) * channel self.embedding = nn.Linear(hidden, c_out) sel...
class SoftComp(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftComp, self).__init__() self.relu = nn.LeakyReLU(0.2, inplace=True) c_out = reduce((lambda x, y: x * y), kernel_size) * channel self.embedding = nn.Linear(hidden, c_out) sel...
b_, _, _, _, c_ = x.shape x = x.view(b_, -1, c_) feat = self.embedding(x) b, _, c = feat.size() feat = feat.view(b * t, -1, c).permute(0, 2, 1) feat = F.fold(feat, output_size=output_size, kernel_size=self.kernel_size, ...
b_, _, _, _, c_ = x.shape x = x.view(b_, -1, c_) feat = self.embedding(x) b, _, c = feat.size() feat = feat.view(b * t, -1, c).permute(0, 2, 1) feat = F.fold(feat, output_size=output_size, kernel_size=self.kernel_size, ...
41
206
164
370
import math from functools import reduce import torch import torch.nn as nn import torch.nn.functional as F class SoftSplit(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftSplit, self).__init__() self.kernel_size = kernel_size self.stride = stride ...
import math from functools import reduce import torch import torch.nn as nn import torch.nn.functional as F class SoftSplit(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftSplit, self).__init__() self.kernel_size = kernel_size self.stride = stride ...
40,197
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/modules/sparse_transformer.py
19,20
7,34
forward
SoftSplit
20,34
20,34
class SoftSplit(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftSplit, self).__init__() self.kernel_size = kernel_size self.stride = stride self.padding = padding self.t2t = nn.Unfold(kernel_size=kernel_size, ...
class SoftSplit(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftSplit, self).__init__() self.kernel_size = kernel_size self.stride = stride self.padding = padding self.t2t = nn.Unfold(kernel_size=kernel_size, ...
f_h = int((output_size[0] + 2 * self.padding[0] - (self.kernel_size[0] - 1) - 1) / self.stride[0] + 1) f_w = int((output_size[1] + 2 * self.padding[1] - (self.kernel_size[1] - 1) - 1) / self.stride[1] + 1) feat = self.t2t(x) feat = feat.permute(0, 2...
f_h = int((output_size[0] + 2 * self.padding[0] - (self.kernel_size[0] - 1) - 1) / self.stride[0] + 1) f_w = int((output_size[1] + 2 * self.padding[1] - (self.kernel_size[1] - 1) - 1) / self.stride[1] + 1) feat = self.t2t(x) feat = feat.permute(0, 2...
68
173
237
410
import math from functools import reduce import torch import torch.nn as nn import torch.nn.functional as F class SoftSplit(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftSplit, self).__init__() self.kernel_size = kernel_size self.stride = stride ...
import math from functools import reduce import torch import torch.nn as nn import torch.nn.functional as F class SoftSplit(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftSplit, self).__init__() self.kernel_size = kernel_size self.stride = stride ...
40,199
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/modules/sparse_transformer.py
294,295
284,317
forward
TemporalSparseTransformer
303,317
295,317
class TemporalSparseTransformer(nn.Module): def __init__(self, dim, n_head, window_size, pool_size, norm_layer=nn.LayerNorm, t2t_params=None): super().__init__() self.window_size = window_size self.attention = SparseWindowAttention(dim, n_head, window_size, pool_size) ...
class TemporalSparseTransformer(nn.Module): def __init__(self, dim, n_head, window_size, pool_size, norm_layer=nn.LayerNorm, t2t_params=None): super().__init__() self.window_size = window_size self.attention = SparseWindowAttention(dim, n_head, window_size, pool_size) ...
B, T, H, W, C = x.shape # 20 36 shortcut = x x = self.norm1(x) att_x = self.attention(x, mask, T_ind) # FFN x = shortcut + att_x y = self.norm2(x) x = x + self.mlp(y.view(B, T * H * W, C), fold_x_size).view(B, T, H, W, C) return x
""" Args: x: image tokens, shape [B T H W C] fold_x_size: fold feature size, shape [60 108] mask: mask tokens, shape [B T H W 1] Returns: out_tokens: shape [B T H W C] """ B, T, H, W, C = x.shape # 20 36 shortcut = x ...
49
271
147
418
import math from functools import reduce import torch import torch.nn as nn import torch.nn.functional as F class SoftSplit(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftSplit, self).__init__() self.kernel_size = kernel_size self.stride = stride ...
import math from functools import reduce import torch import torch.nn as nn import torch.nn.functional as F class SoftSplit(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftSplit, self).__init__() self.kernel_size = kernel_size self.stride = stride ...
40,200
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/modules/sparse_transformer.py
328,329
317,345
forward
TemporalSparseTransformerBlock
337,345
329,345
class TemporalSparseTransformerBlock(nn.Module): def __init__(self, dim, n_head, window_size, pool_size, depths, t2t_params=None): super().__init__() blocks = [] for i in range(depths): blocks.append( TemporalSparseTransformer(dim, n_head, window_size, pool_size,...
class TemporalSparseTransformerBlock(nn.Module): def __init__(self, dim, n_head, window_size, pool_size, depths, t2t_params=None): super().__init__() blocks = [] for i in range(depths): blocks.append( TemporalSparseTransformer(dim, n_head, window_size, pool_size,...
assert self.depths % t_dilation == 0, 'wrong t_dilation input.' T = x.size(1) T_ind = [torch.arange(i, T, t_dilation) for i in range(t_dilation)] * (self.depths // t_dilation) for i in range(0, self.depths): x = self.transformer[i](x, fold_x_size, l_mask, T_ind[i]) ...
""" Args: x: image tokens, shape [B T H W C] fold_x_size: fold feature size, shape [60 108] l_mask: local mask tokens, shape [B T H W 1] Returns: out_tokens: shape [B T H W C] """ assert self.depths % t_dilation == 0, 'wrong t_dilat...
38
263
135
398
import math from functools import reduce import torch import torch.nn as nn import torch.nn.functional as F class SoftSplit(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftSplit, self).__init__() self.kernel_size = kernel_size self.stride = stride ...
import math from functools import reduce import torch import torch.nn as nn import torch.nn.functional as F class SoftSplit(nn.Module): def __init__(self, channel, hidden, kernel_size, stride, padding): super(SoftSplit, self).__init__() self.kernel_size = kernel_size self.stride = stride ...
40,203
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/recurrent_flow_completion.py
66,67
46,127
forward
BidirectionalPropagation
71,127
67,127
class BidirectionalPropagation(nn.Module): def __init__(self, channel): super(BidirectionalPropagation, self).__init__() modules = ['backward_', 'forward_'] self.deform_align = nn.ModuleDict() self.backbone = nn.ModuleDict() self.channel = channel for i, module in en...
class BidirectionalPropagation(nn.Module): def __init__(self, channel): super(BidirectionalPropagation, self).__init__() modules = ['backward_', 'forward_'] self.deform_align = nn.ModuleDict() self.backbone = nn.ModuleDict() self.channel = channel for i, module in en...
b, t, c, h, w = x.shape feats = {} feats['spatial'] = [x[:, i, :, :, :] for i in range(0, t)] for module_name in ['backward_', 'forward_']: feats[module_name] = [] frame_idx = range(0, t) mapping_idx = list(range(0, len(feats['spatial']))) ...
""" x shape : [b, t, c, h, w] return [b, t, c, h, w] """ b, t, c, h, w = x.shape feats = {} feats['spatial'] = [x[:, i, :, :, :] for i in range(0, t)] for module_name in ['backward_', 'forward_']: feats[module_name] = [] frame_id...
197
332
742
1,074
import torch import torch.nn as nn import torch.nn.functional as F import torchvision from model.modules.deformconv import ModulatedDeformConv2d from .misc import constant_init class SecondOrderDeformableAlignment(ModulatedDeformConv2d): """Second-order deformable alignment module.""" def __init__(self, *args...
import torch import torch.nn as nn import torch.nn.functional as F import torchvision from model.modules.deformconv import ModulatedDeformConv2d from .misc import constant_init class SecondOrderDeformableAlignment(ModulatedDeformConv2d): """Second-order deformable alignment module.""" def __init__(self, *args...
40,204
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/recurrent_flow_completion.py
193,194
172,203
forward
EdgeDetection
194,203
194,203
class EdgeDetection(nn.Module): def __init__(self, in_ch=2, out_ch=1, mid_ch=16): super().__init__() self.projection = nn.Sequential( nn.Conv2d(in_ch, mid_ch, 3, 1, 1), nn.LeakyReLU(0.2, inplace=True) ) self.mid_layer_1 = nn.Sequential( nn.Conv2d(...
class EdgeDetection(nn.Module): def __init__(self, in_ch=2, out_ch=1, mid_ch=16): super().__init__() self.projection = nn.Sequential( nn.Conv2d(in_ch, mid_ch, 3, 1, 1), nn.LeakyReLU(0.2, inplace=True) ) self.mid_layer_1 = nn.Sequential( nn.Conv2d(...
flow = self.projection(flow) edge = self.mid_layer_1(flow) edge = self.mid_layer_2(edge) edge = self.l_relu(flow + edge) edge = self.out_layer(edge) edge = torch.sigmoid(edge) return edge
flow = self.projection(flow) edge = self.mid_layer_1(flow) edge = self.mid_layer_2(edge) edge = self.l_relu(flow + edge) edge = self.out_layer(edge) edge = torch.sigmoid(edge) return edge
22
309
94
403
import torch import torch.nn as nn import torch.nn.functional as F import torchvision from model.modules.deformconv import ModulatedDeformConv2d from .misc import constant_init class SecondOrderDeformableAlignment(ModulatedDeformConv2d): """Second-order deformable alignment module.""" def __init__(self, *args...
import torch import torch.nn as nn import torch.nn.functional as F import torchvision from model.modules.deformconv import ModulatedDeformConv2d from .misc import constant_init class SecondOrderDeformableAlignment(ModulatedDeformConv2d): """Second-order deformable alignment module.""" def __init__(self, *args...
40,205
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/recurrent_flow_completion.py
162,163
148,172
forward
P3DBlock
163,172
163,172
class P3DBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, use_residual=0, bias=True): super().__init__() self.conv1 = nn.Sequential( nn.Conv3d(in_channels, out_channels, kernel_size=(1, kernel_size, kernel_size), ...
class P3DBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, use_residual=0, bias=True): super().__init__() self.conv1 = nn.Sequential( nn.Conv3d(in_channels, out_channels, kernel_size=(1, kernel_size, kernel_size), ...
feat1 = self.conv1(feats) feat2 = self.conv2(feat1) if self.use_residual: output = feats + feat2 else: output = feat2 return output
feat1 = self.conv1(feats) feat2 = self.conv2(feat1) if self.use_residual: output = feats + feat2 else: output = feat2 return output
19
283
71
354
import torch import torch.nn as nn import torch.nn.functional as F import torchvision from model.modules.deformconv import ModulatedDeformConv2d from .misc import constant_init class SecondOrderDeformableAlignment(ModulatedDeformConv2d): """Second-order deformable alignment module.""" def __init__(self, *args...
import torch import torch.nn as nn import torch.nn.functional as F import torchvision from model.modules.deformconv import ModulatedDeformConv2d from .misc import constant_init class SecondOrderDeformableAlignment(ModulatedDeformConv2d): """Second-order deformable alignment module.""" def __init__(self, *args...
40,207
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/recurrent_flow_completion.py
30,31
9,46
forward
SecondOrderDeformableAlignment
31,46
31,46
class SecondOrderDeformableAlignment(ModulatedDeformConv2d): """Second-order deformable alignment module.""" def __init__(self, *args, **kwargs): self.max_residue_magnitude = kwargs.pop('max_residue_magnitude', 5) super(SecondOrderDeformableAlignment, self).__init__(*args, **kwargs) se...
class SecondOrderDeformableAlignment(ModulatedDeformConv2d): """Second-order deformable alignment module.""" def __init__(self, *args, **kwargs): self.max_residue_magnitude = kwargs.pop('max_residue_magnitude', 5) super(SecondOrderDeformableAlignment, self).__init__(*args, **kwargs) se...
out = self.conv_offset(extra_feat) o1, o2, mask = torch.chunk(out, 3, dim=1) # offset offset = self.max_residue_magnitude * torch.tanh(torch.cat((o1, o2), dim=1)) offset_1, offset_2 = torch.chunk(offset, 2, dim=1) offset = torch.cat([offset_1, offset_2], dim=1) ...
out = self.conv_offset(extra_feat) o1, o2, mask = torch.chunk(out, 3, dim=1) # offset offset = self.max_residue_magnitude * torch.tanh(torch.cat((o1, o2), dim=1)) offset_1, offset_2 = torch.chunk(offset, 2, dim=1) offset = torch.cat([offset_1, offset_2], dim=1) ...
44
399
213
612
import torch import torch.nn as nn import torch.nn.functional as F import torchvision from model.modules.deformconv import ModulatedDeformConv2d from .misc import constant_init class SecondOrderDeformableAlignment(ModulatedDeformConv2d): """Second-order deformable alignment module.""" def __init__(self, *args...
import torch import torch.nn as nn import torch.nn.functional as F import torchvision from model.modules.deformconv import ModulatedDeformConv2d from .misc import constant_init class SecondOrderDeformableAlignment(ModulatedDeformConv2d): """Second-order deformable alignment module.""" def __init__(self, *args...
40,208
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/recurrent_flow_completion.py
140,141
127,148
forward
deconv
141,148
141,148
class deconv(nn.Module): def __init__(self, input_channel, output_channel, kernel_size=3, padding=0): super().__init__() self.conv = nn.Conv2d(input_channel, output_channel, ...
class deconv(nn.Module): def __init__(self, input_channel, output_channel, kernel_size=3, padding=0): super().__init__() self.conv = nn.Conv2d(input_channel, output_channel, ...
x = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=True) return self.conv(x)
x = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=True) return self.conv(x)
8
118
57
175
import torch import torch.nn as nn import torch.nn.functional as F import torchvision from model.modules.deformconv import ModulatedDeformConv2d from .misc import constant_init class SecondOrderDeformableAlignment(ModulatedDeformConv2d): """Second-order deformable alignment module.""" def __init__(self, *args...
import torch import torch.nn as nn import torch.nn.functional as F import torchvision from model.modules.deformconv import ModulatedDeformConv2d from .misc import constant_init class SecondOrderDeformableAlignment(ModulatedDeformConv2d): """Second-order deformable alignment module.""" def __init__(self, *args...
40,210
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/model/vgg_arch.py
137,138
51,158
forward
VGGFeatureExtractor
146,158
138,158
class VGGFeatureExtractor(nn.Module): """VGG network for feature extraction. In this implementation, we allow users to choose whether use normalization in the input feature and the type of vgg network. Note that the pretrained path must fit the vgg type. Args: layer_name_list (list[str]): ...
class VGGFeatureExtractor(nn.Module): """VGG network for feature extraction. In this implementation, we allow users to choose whether use normalization in the input feature and the type of vgg network. Note that the pretrained path must fit the vgg type. Args: layer_name_list (list[str]): ...
if self.range_norm: x = (x + 1) / 2 if self.use_input_norm: x = (x - self.mean) / self.std output = {} for key, layer in self.vgg_net._modules.items(): x = layer(x) if key in self.layer_name_list: output[key] = x.clone() ...
"""Forward function. Args: x (Tensor): Input tensor with shape (n, c, h, w). Returns: Tensor: Forward results. """ if self.range_norm: x = (x + 1) / 2 if self.use_input_norm: x = (x - self.mean) / self.std output =...
38
1,131
120
1,251
import os import torch from collections import OrderedDict from torch import nn as nn from torchvision.models import vgg as vgg VGG_PRETRAIN_PATH = 'experiments/pretrained_models/vgg19-dcbb9e9d.pth' NAMES = { 'vgg11': [ 'conv1_1', 'relu1_1', 'pool1', 'conv2_1', 'relu2_1', 'pool2', 'conv3_1', 'relu3_1', 'co...
import os import torch from collections import OrderedDict from torch import nn as nn from torchvision.models import vgg as vgg VGG_PRETRAIN_PATH = 'experiments/pretrained_models/vgg19-dcbb9e9d.pth' NAMES = { 'vgg11': [ 'conv1_1', 'relu1_1', 'pool1', 'conv2_1', 'relu2_1', 'pool2', 'conv3_1', 'relu3_1', 'co...
40,212
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/train.py
36,37
1,106
main_worker
37,79
37,79
import os import json import argparse import subprocess from shutil import copyfile import torch.distributed as dist import torch import torch.multiprocessing as mp import core import core.trainer import core.trainer_flow_w_edge # import warnings # warnings.filterwarnings("ignore") from core.dist import ( get...
import os import json import argparse import subprocess from shutil import copyfile import torch.distributed as dist import torch import torch.multiprocessing as mp import core import core.trainer import core.trainer_flow_w_edge # import warnings # warnings.filterwarnings("ignore") from core.dist import ( get...
if 'local_rank' not in config: config['local_rank'] = config['global_rank'] = rank if config['distributed']: torch.cuda.set_device(int(config['local_rank'])) torch.distributed.init_process_group(backend='nccl', init_method=config['init_method'...
if 'local_rank' not in config: config['local_rank'] = config['global_rank'] = rank if config['distributed']: torch.cuda.set_device(int(config['local_rank'])) torch.distributed.init_process_group(backend='nccl', init_method=config['init_method'...
76
570
550
1,120
import os import json import argparse import subprocess from shutil import copyfile import torch.distributed as dist import torch import torch.multiprocessing as mp import core import core.trainer import core.trainer_flow_w_edge # import warnings # warnings.filterwarnings("ignore") from core.dist import ( get...
import os import json import argparse import subprocess from shutil import copyfile import torch.distributed as dist import torch import torch.multiprocessing as mp import core import core.trainer import core.trainer_flow_w_edge # import warnings # warnings.filterwarnings("ignore") from core.dist import ( get...
40,216
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/track_anything.py
16,17
9,41
first_frame_click
TrackingAnything
17,20
17,20
class TrackingAnything(): def __init__(self, sam_checkpoint, cutie_checkpoint, propainter_checkpoint, raft_checkpoint, flow_completion_checkpoint, args): self.args = args self.samcontroler = SamControler(sam_checkpoint, args.sam_model_type, args.device) self.cutie = BaseTracker(cutie_checkpo...
class TrackingAnything(): def __init__(self, sam_checkpoint, cutie_checkpoint, propainter_checkpoint, raft_checkpoint, flow_completion_checkpoint, args): self.args = args self.samcontroler = SamControler(sam_checkpoint, args.sam_model_type, args.device) self.cutie = BaseTracker(cutie_checkpo...
mask, logit, painted_image = self.samcontroler.first_frame_click(image, points, labels, multimask) return mask, logit, painted_image
mask, logit, painted_image = self.samcontroler.first_frame_click(image, points, labels, multimask) return mask, logit, painted_image
12
407
48
455
import numpy as np from tqdm import tqdm from tools.interact_tools import SamControler from tracker.base_tracker import BaseTracker from inpainter.base_inpainter import ProInpainter class TrackingAnything(): def __init__(self, sam_checkpoint, cutie_checkpoint, propainter_checkpoint, raft_checkpoint, flow_complet...
import numpy as np from tqdm import tqdm from tools.interact_tools import SamControler from tracker.base_tracker import BaseTracker from inpainter.base_inpainter import ProInpainter class TrackingAnything(): def __init__(self, sam_checkpoint, cutie_checkpoint, propainter_checkpoint, raft_checkpoint, flow_complet...
40,217
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/inference/object_info.py
9,10
1,25
poke
ObjectInfo
10,12
10,12
class ObjectInfo: """ Store meta information for an object """ def __init__(self, id: int): self.id = id self.poke_count = 0 # count number of detections missed def poke(self) -> None: FILL_FUNC_BODY def unpoke(self) -> None: self.poke_count = 0 def __hash__(self): ...
class ObjectInfo: """ Store meta information for an object """ def __init__(self, id: int): self.id = id self.poke_count = 0 # count number of detections missed def poke(self) -> None: FILL_FUNC_BODY def unpoke(self) -> None: self.poke_count = 0 def __hash__(self): ...
self.poke_count += 1
self.poke_count += 1
3
182
13
195
class ObjectInfo: """ Store meta information for an object """ def __init__(self, id: int): self.id = id self.poke_count = 0 # count number of detections missed def poke(self) -> None: FILL_FUNC_BODY def unpoke(self) -> None: self.poke_count = 0 def __hash__(self): ...
class ObjectInfo: """ Store meta information for an object """ def __init__(self, id: int): self.id = id self.poke_count = 0 # count number of detections missed def poke(self) -> None: FILL_FUNC_BODY def unpoke(self) -> None: self.poke_count = 0 def __hash__(self): ...
40,218
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/inference/utils/burst_utils.py
16,17
6,20
dump
BURSTResultHandler
17,20
17,20
class BURSTResultHandler: def __init__(self, dataset_json): self.dataset_json = copy.deepcopy(dataset_json) # get rid of the segmentations while keeping the metadata self.dataset_json['sequences'] = [] def add_sequence(self, sequence_json): self.dataset_json['sequences'].append...
class BURSTResultHandler: def __init__(self, dataset_json): self.dataset_json = copy.deepcopy(dataset_json) # get rid of the segmentations while keeping the metadata self.dataset_json['sequences'] = [] def add_sequence(self, sequence_json): self.dataset_json['sequences'].append...
json_path = path.join(root, 'predictions.json') with open(json_path, 'w') as f: json.dump(self.dataset_json, f)
json_path = path.join(root, 'predictions.json') with open(json_path, 'w') as f: json.dump(self.dataset_json, f)
11
115
49
164
from os import path import copy import json class BURSTResultHandler: def __init__(self, dataset_json): self.dataset_json = copy.deepcopy(dataset_json) # get rid of the segmentations while keeping the metadata self.dataset_json['sequences'] = [] def add_sequence(self, sequence_json):...
from os import path import copy import json class BURSTResultHandler: def __init__(self, dataset_json): self.dataset_json = copy.deepcopy(dataset_json) # get rid of the segmentations while keeping the metadata self.dataset_json['sequences'] = [] def add_sequence(self, sequence_json):...
40,219
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/inference/utils/frame_utils.py
20,22
7,27
shape
FrameInfo
22,24
22,24
class FrameInfo: def __init__(self, image: torch.Tensor, mask: torch.Tensor, segments_info: List[ObjectInfo], ti: int, info: Dict): self.image = image self.mask = mask self.segments_info = segments_info self.ti = ti self.info = info @property def nam...
class FrameInfo: def __init__(self, image: torch.Tensor, mask: torch.Tensor, segments_info: List[ObjectInfo], ti: int, info: Dict): self.image = image self.mask = mask self.segments_info = segments_info self.ti = ti self.info = info @property def nam...
return self.info['shape']
return self.info['shape']
2
171
12
183
from typing import Dict, List, Tuple import torch from inference.object_info import ObjectInfo class FrameInfo: def __init__(self, image: torch.Tensor, mask: torch.Tensor, segments_info: List[ObjectInfo], ti: int, info: Dict): self.image = image self.mask = mask self.segm...
from typing import Dict, List, Tuple import torch from inference.object_info import ObjectInfo class FrameInfo: def __init__(self, image: torch.Tensor, mask: torch.Tensor, segments_info: List[ObjectInfo], ti: int, info: Dict): self.image = image self.mask = mask self.segm...
40,220
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/model/channel_attn.py
25,26
7,40
forward
CAResBlock
26,40
26,40
class CAResBlock(nn.Module): def __init__(self, in_dim: int, out_dim: int, residual: bool = True): super().__init__() self.residual = residual self.conv1 = nn.Conv2d(in_dim, out_dim, kernel_size=3, padding=1) self.conv2 = nn.Conv2d(out_dim, out_dim, kernel_size=3, padding=1) ...
class CAResBlock(nn.Module): def __init__(self, in_dim: int, out_dim: int, residual: bool = True): super().__init__() self.residual = residual self.conv1 = nn.Conv2d(in_dim, out_dim, kernel_size=3, padding=1) self.conv2 = nn.Conv2d(out_dim, out_dim, kernel_size=3, padding=1) ...
r = x x = self.conv1(F.relu(x)) x = self.conv2(F.relu(x)) b, c = x.shape[:2] w = self.pool(x).view(b, 1, c) w = self.conv(w).transpose(-1, -2).unsqueeze(-1).sigmoid() # B*C*1*1 if self.residual: x = x * w + self.downsample(r) else: ...
r = x x = self.conv1(F.relu(x)) x = self.conv2(F.relu(x)) b, c = x.shape[:2] w = self.pool(x).view(b, 1, c) w = self.conv(w).transpose(-1, -2).unsqueeze(-1).sigmoid() # B*C*1*1 if self.residual: x = x * w + self.downsample(r) else: ...
41
318
161
479
import math import torch import torch.nn as nn import torch.nn.functional as F class CAResBlock(nn.Module): def __init__(self, in_dim: int, out_dim: int, residual: bool = True): super().__init__() self.residual = residual self.conv1 = nn.Conv2d(in_dim, out_dim, kernel_size=3, padding=1) ...
import math import torch import torch.nn as nn import torch.nn.functional as F class CAResBlock(nn.Module): def __init__(self, in_dim: int, out_dim: int, residual: bool = True): super().__init__() self.residual = residual self.conv1 = nn.Conv2d(in_dim, out_dim, kernel_size=3, padding=1) ...
40,221
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/model/transformer/positional_encoding.py
12,13
1,109
get_emb
16,20
13,20
# Reference: # https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/modeling/transformer_decoder/position_encoding.py # https://github.com/tatp22/multidim-positional-encoding/blob/master/positional_encodings/torch_encodings.py import math import numpy as np import torch from torch import nn def get...
# Reference: # https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/modeling/transformer_decoder/position_encoding.py # https://github.com/tatp22/multidim-positional-encoding/blob/master/positional_encodings/torch_encodings.py import math import numpy as np import torch from torch import nn def get...
emb = torch.stack((sin_inp.sin(), sin_inp.cos()), dim=-1) return torch.flatten(emb, -2, -1)
""" Gets a base embedding for one dimension with sin and cos intertwined """ emb = torch.stack((sin_inp.sin(), sin_inp.cos()), dim=-1) return torch.flatten(emb, -2, -1)
9
1,367
51
1,418
# Reference: # https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/modeling/transformer_decoder/position_encoding.py # https://github.com/tatp22/multidim-positional-encoding/blob/master/positional_encodings/torch_encodings.py import math import numpy as np import torch from torch import nn def get...
# Reference: # https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/modeling/transformer_decoder/position_encoding.py # https://github.com/tatp22/multidim-positional-encoding/blob/master/positional_encodings/torch_encodings.py import math import numpy as np import torch from torch import nn def get...
40,222
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/model/transformer/positional_encoding.py
41,42
20,100
forward
PositionalEncoding
49,100
42,100
class PositionalEncoding(nn.Module): def __init__(self, dim: int, scale: float = math.pi * 2, temperature: float = 10000, normalize: bool = True, channel_last: bool = True, transpose_output: bool = False): ...
class PositionalEncoding(nn.Module): def __init__(self, dim: int, scale: float = math.pi * 2, temperature: float = 10000, normalize: bool = True, channel_last: bool = True, transpose_output: bool = False): ...
if len(tensor.shape) != 4 and len(tensor.shape) != 5: raise RuntimeError(f'The input tensor has to be 4/5d, got {tensor.shape}!') if len(tensor.shape) == 5: # take a sample from the k dimension num_objects = tensor.shape[1] tensor = tensor[:, 0] e...
""" :param tensor: A 4/5d tensor of size channel_last=True: (batch_size, h, w, c) or (batch_size, k, h, w, c) channel_last=False: (batch_size, c, h, w) or (batch_size, k, c, h, w) :return: positional encoding tensor that has the same shape as the input if the input is 4d...
176
406
731
1,137
# Reference: # https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/modeling/transformer_decoder/position_encoding.py # https://github.com/tatp22/multidim-positional-encoding/blob/master/positional_encodings/torch_encodings.py import math import numpy as np import torch from torch import nn def get...
# Reference: # https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/modeling/transformer_decoder/position_encoding.py # https://github.com/tatp22/multidim-positional-encoding/blob/master/positional_encodings/torch_encodings.py import math import numpy as np import torch from torch import nn def get...
40,223
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/model/utils/memory_utils.py
7,12
1,96
get_similarity
12,49
12,49
import math import torch from typing import Optional, Union, Tuple # @torch.jit.script def get_similarity(mk: torch.Tensor, ms: torch.Tensor, qk: torch.Tensor, qe: torch.Tensor, add_batch_dim: bool = False) -> torch.Tensor: FILL_FUNC_BODYdef ...
import math import torch from typing import Optional, Union, Tuple # @torch.jit.script def get_similarity(mk: torch.Tensor, ms: torch.Tensor, qk: torch.Tensor, qe: torch.Tensor, add_batch_dim: bool = False) -> torch.Tensor: FILL_FUNC_BODYdef ...
# used for training/inference and memory reading/memory potentiation # mk: B x CK x [N] - Memory keys # ms: B x 1 x [N] - Memory shrinkage # qk: B x CK x [HW/P] - Query keys # qe: B x CK x [HW/P] - Query selection # Dimensions in [] are flattened if add_batch_dim: mk, ms = mk....
# used for training/inference and memory reading/memory potentiation # mk: B x CK x [N] - Memory keys # ms: B x 1 x [N] - Memory shrinkage # qk: B x CK x [HW/P] - Query keys # qe: B x CK x [HW/P] - Query selection # Dimensions in [] are flattened if add_batch_dim: mk, ms = mk....
189
693
555
1,248
import math import torch from typing import Optional, Union, Tuple # @torch.jit.script def get_similarity(mk: torch.Tensor, ms: torch.Tensor, qk: torch.Tensor, qe: torch.Tensor, add_batch_dim: bool = False) -> torch.Tensor: FILL_FUNC_BODYdef ...
import math import torch from typing import Optional, Union, Tuple # @torch.jit.script def get_similarity(mk: torch.Tensor, ms: torch.Tensor, qk: torch.Tensor, qe: torch.Tensor, add_batch_dim: bool = False) -> torch.Tensor: FILL_FUNC_BODYdef ...
40,224
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/model/utils/parameter_groups.py
6,7
1,73
get_parameter_groups
11,73
7,73
import logging log = logging.getLogger() def get_parameter_groups(model, stage_cfg, print_log=False): FILL_FUNC_BODY
import logging log = logging.getLogger() def get_parameter_groups(model, stage_cfg, print_log=False): """ Assign different weight decays and learning rates to different parameters. Returns a parameter group which can be passed to the optimizer. """ FILL_FUNC_BODY
weight_decay = stage_cfg.weight_decay embed_weight_decay = stage_cfg.embed_weight_decay backbone_lr_ratio = stage_cfg.backbone_lr_ratio base_lr = stage_cfg.learning_rate backbone_params = [] embed_params = [] other_params = [] embedding_names = ['summary_pos', 'query_init', 'query_emb'...
""" Assign different weight decays and learning rates to different parameters. Returns a parameter group which can be passed to the optimizer. """ weight_decay = stage_cfg.weight_decay embed_weight_decay = stage_cfg.embed_weight_decay backbone_lr_ratio = stage_cfg.backbone_lr_ratio base_...
140
80
582
662
import logging log = logging.getLogger() def get_parameter_groups(model, stage_cfg, print_log=False): FILL_FUNC_BODY
import logging log = logging.getLogger() def get_parameter_groups(model, stage_cfg, print_log=False): """ Assign different weight decays and learning rates to different parameters. Returns a parameter group which can be passed to the optimizer. """ FILL_FUNC_BODY
40,226
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/model/utils/resnet.py
64,65
51,83
forward
BasicBlock
65,83
65,83
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride=stride, dilation=dilation) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.Re...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride=stride, dilation=dilation) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.Re...
residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return o...
residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return o...
34
208
127
335
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): new_dict = Or...
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): new_dict = Or...
40,227
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/model/utils/resnet.py
104,105
83,127
forward
Bottleneck
105,127
105,127
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d...
residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = se...
residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = se...
43
300
165
465
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): new_dict = Or...
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): new_dict = Or...
40,228
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/model/utils/resnet.py
148,149
127,168
_make_layer
ResNet
149,168
149,168
class ResNet(nn.Module): def __init__(self, block, layers=(3, 4, 23, 3), extra_dim=0): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3 + extra_dim, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU...
class ResNet(nn.Module): def __init__(self, block, layers=(3, 4, 23, 3), extra_dim=0): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3 + extra_dim, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU...
downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, ...
downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, ...
48
436
212
648
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): new_dict = Or...
""" resnet.py - A modified ResNet structure We append extra channels to the first conv by some network surgery """ from collections import OrderedDict import math import torch import torch.nn as nn from torch.utils import model_zoo def load_weights_add_extra_dim(target, source_state, extra_dim=1): new_dict = Or...
40,230
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/utils/load_subset.py
10,11
1,14
load_empty_masks
11,14
11,14
import json def load_subset(path): with open(path, mode='r') as f: subset = set(f.read().splitlines()) return subset def load_empty_masks(path): FILL_FUNC_BODY
import json def load_subset(path): with open(path, mode='r') as f: subset = set(f.read().splitlines()) return subset def load_empty_masks(path): FILL_FUNC_BODY
with open(path, mode='r') as f: empty_masks = json.load(f) return empty_masks
with open(path, mode='r') as f: empty_masks = json.load(f) return empty_masks
10
68
38
106
import json def load_subset(path): with open(path, mode='r') as f: subset = set(f.read().splitlines()) return subset def load_empty_masks(path): FILL_FUNC_BODY
import json def load_subset(path): with open(path, mode='r') as f: subset = set(f.read().splitlines()) return subset def load_empty_masks(path): FILL_FUNC_BODY
40,231
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/utils/mask_mapper.py
4,5
1,79
all_to_onehot
5,15
5,15
import numpy as np import torch def all_to_onehot(masks, labels): FILL_FUNC_BODYclass MaskMapper: """ This class is used to convert a indexed-mask to a one-hot representation. It also takes care of remapping non-continuous indices It has two modes: 1. Default. Only masks with new indices are su...
import numpy as np import torch def all_to_onehot(masks, labels): FILL_FUNC_BODYclass MaskMapper: """ This class is used to convert a indexed-mask to a one-hot representation. It also takes care of remapping non-continuous indices It has two modes: 1. Default. Only masks with new indices are su...
if len(masks.shape) == 3: Ms = np.zeros((len(labels), masks.shape[0], masks.shape[1], masks.shape[2]), dtype=np.uint8) else: Ms = np.zeros((len(labels), masks.shape[0], masks.shape[1]), dtype=np.uint8) for ni, l in enumerate(labels): Ms[ni] = (masks == l).astype(np.uint8) ...
if len(masks.shape) == 3: Ms = np.zeros((len(labels), masks.shape[0], masks.shape[1], masks.shape[2]), dtype=np.uint8) else: Ms = np.zeros((len(labels), masks.shape[0], masks.shape[1]), dtype=np.uint8) for ni, l in enumerate(labels): Ms[ni] = (masks == l).astype(np.uint8) ...
30
726
147
873
import numpy as np import torch def all_to_onehot(masks, labels): FILL_FUNC_BODYclass MaskMapper: """ This class is used to convert a indexed-mask to a one-hot representation. It also takes care of remapping non-continuous indices It has two modes: 1. Default. Only masks with new indices are su...
import numpy as np import torch def all_to_onehot(masks, labels): FILL_FUNC_BODYclass MaskMapper: """ This class is used to convert a indexed-mask to a one-hot representation. It also takes care of remapping non-continuous indices It has two modes: 1. Default. Only masks with new indices are su...
40,232
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/utils/mask_mapper.py
34,35
15,79
clear_labels
MaskMapper
35,40
35,40
class MaskMapper: """ This class is used to convert a indexed-mask to a one-hot representation. It also takes care of remapping non-continuous indices It has two modes: 1. Default. Only masks with new indices are supposed to go into the remapper. This is also the case for YouTubeVOS. ...
class MaskMapper: """ This class is used to convert a indexed-mask to a one-hot representation. It also takes care of remapping non-continuous indices It has two modes: 1. Default. Only masks with new indices are supposed to go into the remapper. This is also the case for YouTubeVOS. ...
self.labels = [] self.remappings = {} # if coherent, no mapping is required self.coherent = True
self.labels = [] self.remappings = {} # if coherent, no mapping is required self.coherent = True
16
667
39
706
import numpy as np import torch def all_to_onehot(masks, labels): if len(masks.shape) == 3: Ms = np.zeros((len(labels), masks.shape[0], masks.shape[1], masks.shape[2]), dtype=np.uint8) else: Ms = np.zeros((len(labels), masks.shape[0], masks.shape[1]), dtype=np.uint8) for ni, l in enumerate...
import numpy as np import torch def all_to_onehot(masks, labels): if len(masks.shape) == 3: Ms = np.zeros((len(labels), masks.shape[0], masks.shape[1], masks.shape[2]), dtype=np.uint8) else: Ms = np.zeros((len(labels), masks.shape[0], masks.shape[1]), dtype=np.uint8) for ni, l in enumerate...
40,233
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/utils/pano_utils.py
18,19
5,31
convert
ID2RGBConverter
19,31
19,31
class ID2RGBConverter: def __init__(self): self.all_id = [] self.obj_to_id = {} self.lock = Lock() def _id_to_rgb(self, id: int): rgb = np.zeros((3, ), dtype=np.uint8) for i in range(3): rgb[i] = id % 256 id = id // 256 return rgb def...
class ID2RGBConverter: def __init__(self): self.all_id = [] self.obj_to_id = {} self.lock = Lock() def _id_to_rgb(self, id: int): rgb = np.zeros((3, ), dtype=np.uint8) for i in range(3): rgb[i] = id % 256 id = id // 256 return rgb def...
with self.lock: if obj in self.obj_to_id: id = self.obj_to_id[obj] else: while True: id = np.random.randint(255, 256**3) if id not in self.all_id: break self.obj_to_id[obj] = i...
with self.lock: if obj in self.obj_to_id: id = self.obj_to_id[obj] else: while True: id = np.random.randint(255, 256**3) if id not in self.all_id: break self.obj_to_id[obj] = i...
29
143
135
278
import numpy as np from threading import Lock class ID2RGBConverter: def __init__(self): self.all_id = [] self.obj_to_id = {} self.lock = Lock() def _id_to_rgb(self, id: int): rgb = np.zeros((3, ), dtype=np.uint8) for i in range(3): rgb[i] = id % 256 ...
import numpy as np from threading import Lock class ID2RGBConverter: def __init__(self): self.all_id = [] self.obj_to_id = {} self.lock = Lock() def _id_to_rgb(self, id: int): rgb = np.zeros((3, ), dtype=np.uint8) for i in range(3): rgb[i] = id % 256 ...
40,234
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/utils/point_features.py
62,64
1,112
get_uncertain_point_coords_with_randomness
82,112
64,112
# This file is copied from https://github.com/facebookresearch/detectron2/blob/main/projects/PointRend/point_rend/point_features.py # such that users do not need to install detectron2 just for these two functions # Copyright (c) Facebook, Inc. and its affiliates. from typing import List import torch from torch.nn impo...
# This file is copied from https://github.com/facebookresearch/detectron2/blob/main/projects/PointRend/point_rend/point_features.py # such that users do not need to install detectron2 just for these two functions # Copyright (c) Facebook, Inc. and its affiliates. from typing import List import torch from torch.nn impo...
assert oversample_ratio >= 1 assert importance_sample_ratio <= 1 and importance_sample_ratio >= 0 num_boxes = coarse_logits.shape[0] num_sampled = int(num_points * oversample_ratio) point_coords = torch.rand(num_boxes, num_sampled, 2, device=coarse_logits.device) point_logits = point_sample(coar...
""" Sample points in [0, 1] x [0, 1] coordinate space based on their uncertainty. The uncertainties are calculated for each point using 'uncertainty_func' function that takes point's logit prediction as input. See PointRend paper for details. Args: coarse_logits (Tensor): A tenso...
173
1,176
552
1,728
# This file is copied from https://github.com/facebookresearch/detectron2/blob/main/projects/PointRend/point_rend/point_features.py # such that users do not need to install detectron2 just for these two functions # Copyright (c) Facebook, Inc. and its affiliates. from typing import List import torch from torch.nn impo...
# This file is copied from https://github.com/facebookresearch/detectron2/blob/main/projects/PointRend/point_rend/point_features.py # such that users do not need to install detectron2 just for these two functions # Copyright (c) Facebook, Inc. and its affiliates. from typing import List import torch from torch.nn impo...
40,235
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter
/home/hieuvd/dung_repo/raw/stars_02/sczhou_ProPainter/ProPainter/web-demos/hugging_face/tracker/utils/tensor_utils.py
7,8
1,63
pad_divide_by
8,25
8,25
from typing import List, Iterable import torch import torch.nn.functional as F # STM def pad_divide_by(in_img: torch.Tensor, d: int) -> (torch.Tensor, Iterable[int]): FILL_FUNC_BODYdef unpad(img: torch.Tensor, pad: Iterable[int]) -> torch.Tensor: if len(img.shape) == 4: if pad[2] + pad[3] > 0: ...
from typing import List, Iterable import torch import torch.nn.functional as F # STM def pad_divide_by(in_img: torch.Tensor, d: int) -> (torch.Tensor, Iterable[int]): FILL_FUNC_BODYdef unpad(img: torch.Tensor, pad: Iterable[int]) -> torch.Tensor: if len(img.shape) == 4: if pad[2] + pad[3] > 0: ...
h, w = in_img.shape[-2:] if h % d > 0: new_h = h + d - h % d else: new_h = h if w % d > 0: new_w = w + d - w % d else: new_w = w lh, uh = int((new_h - h) / 2), int(new_h - h) - int((new_h - h) / 2) lw, uw = int((new_w - w) / 2), int(new_w - w) - int((new_w - ...
h, w = in_img.shape[-2:] if h % d > 0: new_h = h + d - h % d else: new_h = h if w % d > 0: new_w = w + d - w % d else: new_w = w lh, uh = int((new_h - h) / 2), int(new_h - h) - int((new_h - h) / 2) lw, uw = int((new_w - w) / 2), int(new_w - w) - int((new_w - ...
89
636
232
868
from typing import List, Iterable import torch import torch.nn.functional as F # STM def pad_divide_by(in_img: torch.Tensor, d: int) -> (torch.Tensor, Iterable[int]): FILL_FUNC_BODYdef unpad(img: torch.Tensor, pad: Iterable[int]) -> torch.Tensor: if len(img.shape) == 4: if pad[2] + pad[3] > 0: ...
from typing import List, Iterable import torch import torch.nn.functional as F # STM def pad_divide_by(in_img: torch.Tensor, d: int) -> (torch.Tensor, Iterable[int]): FILL_FUNC_BODYdef unpad(img: torch.Tensor, pad: Iterable[int]) -> torch.Tensor: if len(img.shape) == 4: if pad[2] + pad[3] > 0: ...