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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
38,652 | /home/hieuvd/dung_repo/raw/stars_02/my8100_scrapydweb/scrapydweb | /home/hieuvd/dung_repo/raw/stars_02/my8100_scrapydweb/scrapydweb/scrapydweb/views/utilities/parse.py | 30,31 | 23,57 | dispatch_request | UploadLogView | 31,57 | 31,57 | class UploadLogView(BaseView):
def __init__(self):
super(UploadLogView, self).__init__()
self.template = 'scrapydweb/parse.html'
def dispatch_request(self, **kwargs):
FILL_FUNC_BODY | class UploadLogView(BaseView):
def __init__(self):
super(UploadLogView, self).__init__()
self.template = 'scrapydweb/parse.html'
def dispatch_request(self, **kwargs):
FILL_FUNC_BODY | if self.POST:
file = request.files.get('file')
if not file:
flash('No file selected', self.WARN)
return redirect(request.url)
if file.filename == '':
flash('Filename not found', self.WARN)
return redirect(reques... | if self.POST:
file = request.files.get('file')
if not file:
flash('No file selected', self.WARN)
return redirect(request.url)
if file.filename == '':
flash('Filename not found', self.WARN)
return redirect(reques... | 84 | 73 | 358 | 431 | # coding: utf-8
import io
import os
import re
from flask import Blueprint, flash, redirect, render_template, request, send_from_directory, url_for
from logparser import parse
from werkzeug.utils import secure_filename
from ...vars import PARSE_PATH
from ..baseview import BaseView
ALLOWED_EXTENSIONS = {'log', 'txt'}... | # coding: utf-8
import io
import os
import re
from flask import Blueprint, flash, redirect, render_template, request, send_from_directory, url_for
from logparser import parse
from werkzeug.utils import secure_filename
from ...vars import PARSE_PATH
from ..baseview import BaseView
ALLOWED_EXTENSIONS = {'log', 'txt'}... |
38,653 | /home/hieuvd/dung_repo/raw/stars_02/my8100_scrapydweb/scrapydweb | /home/hieuvd/dung_repo/raw/stars_02/my8100_scrapydweb/scrapydweb/scrapydweb/views/utilities/parse.py | 70,71 | 57,105 | dispatch_request | UploadedLogView | 71,93 | 71,93 | class UploadedLogView(BaseView):
def __init__(self):
super(UploadedLogView, self).__init__()
self.filename = self.view_args['filename']
self.template = 'scrapydweb/stats.html'
self.text = ''
self.project = ''
self.spider = ''
self.job = ''
def dispatch... | class UploadedLogView(BaseView):
def __init__(self):
super(UploadedLogView, self).__init__()
self.filename = self.view_args['filename']
self.template = 'scrapydweb/stats.html'
self.text = ''
self.project = ''
self.spider = ''
self.job = ''
def dispatch... | try:
# Use io.open for compatibility with Python 2
with io.open(os.path.join(self.PARSE_PATH, self.filename), encoding='utf-8', errors='ignore') as f:
self.text = f.read()
except Exception as err:
return render_template(self.template_fail, node=self.no... | try:
# Use io.open for compatibility with Python 2
with io.open(os.path.join(self.PARSE_PATH, self.filename), encoding='utf-8', errors='ignore') as f:
self.text = f.read()
except Exception as err:
return render_template(self.template_fail, node=self.no... | 69 | 450 | 336 | 786 | # coding: utf-8
import io
import os
import re
from flask import Blueprint, flash, redirect, render_template, request, send_from_directory, url_for
from logparser import parse
from werkzeug.utils import secure_filename
from ...vars import PARSE_PATH
from ..baseview import BaseView
ALLOWED_EXTENSIONS = {'log', 'txt'}... | # coding: utf-8
import io
import os
import re
from flask import Blueprint, flash, redirect, render_template, request, send_from_directory, url_for
from logparser import parse
from werkzeug.utils import secure_filename
from ...vars import PARSE_PATH
from ..baseview import BaseView
ALLOWED_EXTENSIONS = {'log', 'txt'}... |
38,654 | /home/hieuvd/dung_repo/raw/stars_02/my8100_scrapydweb/scrapydweb | /home/hieuvd/dung_repo/raw/stars_02/my8100_scrapydweb/scrapydweb/scrapydweb/views/utilities/send_text.py | 95,96 | 27,139 | send_slack | SendTextApiView | 96,118 | 96,118 | class SendTextApiView(BaseView):
# https://api.slack.com/methods/chat.postMessage
# https://www.codementor.io/garethdwyer/building-a-telegram-bot-using-python-part-1-goi5fncay
# slack_help = 'https://api.slack.com/apps'
# telegram_help = 'https://core.telegram.org/bots#6-botfather'
def __init__(sel... | class SendTextApiView(BaseView):
# https://api.slack.com/methods/chat.postMessage
# https://www.codementor.io/garethdwyer/building-a-telegram-bot-using-python-part-1-goi5fncay
# slack_help = 'https://api.slack.com/apps'
# telegram_help = 'https://core.telegram.org/bots#6-botfather'
def __init__(sel... | if not self.SLACK_TOKEN:
self.js = dict(status=self.ERROR, result="The SLACK_TOKEN option is unset")
return
url = 'https://slack.com/api/chat.postMessage'
data = dict(token=self.SLACK_TOKEN, channel=self.channel_chatid_subject, text=self.text)
status_code, js = se... | if not self.SLACK_TOKEN:
self.js = dict(status=self.ERROR, result="The SLACK_TOKEN option is unset")
return
url = 'https://slack.com/api/chat.postMessage'
data = dict(token=self.SLACK_TOKEN, channel=self.channel_chatid_subject, text=self.text)
status_code, js = se... | 80 | 1,551 | 402 | 1,953 | # coding: utf-8
import re
from flask import render_template, request, url_for
from ...utils.send_email import send_email
from ..baseview import BaseView
class SendTextView(BaseView):
def __init__(self):
super(SendTextView, self).__init__()
self.template = 'scrapydweb/send_text.html'
def d... | # coding: utf-8
import re
from flask import render_template, request, url_for
from ...utils.send_email import send_email
from ..baseview import BaseView
class SendTextView(BaseView):
def __init__(self):
super(SendTextView, self).__init__()
self.template = 'scrapydweb/send_text.html'
def d... |
38,655 | /home/hieuvd/dung_repo/raw/stars_02/my8100_scrapydweb/scrapydweb | /home/hieuvd/dung_repo/raw/stars_02/my8100_scrapydweb/scrapydweb/scrapydweb/views/utilities/send_text.py | 17,18 | 10,27 | dispatch_request | SendTextView | 18,27 | 18,27 | class SendTextView(BaseView):
def __init__(self):
super(SendTextView, self).__init__()
self.template = 'scrapydweb/send_text.html'
def dispatch_request(self, **kwargs):
FILL_FUNC_BODY | class SendTextView(BaseView):
def __init__(self):
super(SendTextView, self).__init__()
self.template = 'scrapydweb/send_text.html'
def dispatch_request(self, **kwargs):
FILL_FUNC_BODY | kwargs = dict(
node=self.node,
url_slack=url_for('sendtextapi', opt='slack', channel_chatid_subject=None, text='some-text'),
url_telegram=url_for('sendtextapi', opt='telegram', channel_chatid_subject=None, text='some-text'),
url_email=url_for('sendtextapi', opt='e... | kwargs = dict(
node=self.node,
url_slack=url_for('sendtextapi', opt='slack', channel_chatid_subject=None, text='some-text'),
url_telegram=url_for('sendtextapi', opt='telegram', channel_chatid_subject=None, text='some-text'),
url_email=url_for('sendtextapi', opt='e... | 20 | 72 | 153 | 225 | # coding: utf-8
import re
from flask import render_template, request, url_for
from ...utils.send_email import send_email
from ..baseview import BaseView
class SendTextView(BaseView):
def __init__(self):
super(SendTextView, self).__init__()
self.template = 'scrapydweb/send_text.html'
def d... | # coding: utf-8
import re
from flask import render_template, request, url_for
from ...utils.send_email import send_email
from ..baseview import BaseView
class SendTextView(BaseView):
def __init__(self):
super(SendTextView, self).__init__()
self.template = 'scrapydweb/send_text.html'
def d... |
38,662 | /home/hieuvd/dung_repo/raw/stars_02/nbei_Deep-Flow-Guided-Video-Inpainting/Deep-Flow-Guided-Video-Inpainting | /home/hieuvd/dung_repo/raw/stars_02/nbei_Deep-Flow-Guided-Video-Inpainting/Deep-Flow-Guided-Video-Inpainting/models/DeepFill_Models/DeepFill.py | 45,46 | 31,54 | forward | CoarseNet | 46,54 | 46,54 | class CoarseNet(nn.Module):
'''
# input: B x 5 x W x H
# after down: B x 128(32*4) x W/4 x H/4
# after atrous: same with the output size of the down module
# after up : same with the input size
'''
def __init__(self, in_ch, out_ch, device=None):
super(CoarseNet,self).__init__()
... | class CoarseNet(nn.Module):
'''
# input: B x 5 x W x H
# after down: B x 128(32*4) x W/4 x H/4
# after atrous: same with the output size of the down module
# after up : same with the input size
'''
def __init__(self, in_ch, out_ch, device=None):
super(CoarseNet,self).__init__()
... | x = self.down(x)
resized_mask = down_sample(mask, scale_factor=0.25, mode='nearest', device=self.device)
x = self.atrous(x)
x = self.up(x)
return x, resized_mask
| x = self.down(x)
resized_mask = down_sample(mask, scale_factor=0.25, mode='nearest', device=self.device)
x = self.atrous(x)
x = self.up(x)
return x, resized_mask
| 18 | 206 | 85 | 291 | from .ops import *
class Generator(nn.Module):
def __init__(self, first_dim=32, isCheck=False, device=None):
super(Generator, self).__init__()
self.isCheck = isCheck
self.device = device
self.stage_1 = CoarseNet(5, first_dim, device=device)
self.stage_2 = RefinementNet(5, f... | from .ops import *
class Generator(nn.Module):
def __init__(self, first_dim=32, isCheck=False, device=None):
super(Generator, self).__init__()
self.isCheck = isCheck
self.device = device
self.stage_1 = CoarseNet(5, first_dim, device=device)
self.stage_2 = RefinementNet(5, f... |
38,663 | /home/hieuvd/dung_repo/raw/stars_02/nbei_Deep-Flow-Guided-Video-Inpainting/Deep-Flow-Guided-Video-Inpainting | /home/hieuvd/dung_repo/raw/stars_02/nbei_Deep-Flow-Guided-Video-Inpainting/Deep-Flow-Guided-Video-Inpainting/models/DeepFill_Models/DeepFill.py | 12,13 | 4,31 | forward | Generator | 13,31 | 13,31 | class Generator(nn.Module):
def __init__(self, first_dim=32, isCheck=False, device=None):
super(Generator, self).__init__()
self.isCheck = isCheck
self.device = device
self.stage_1 = CoarseNet(5, first_dim, device=device)
self.stage_2 = RefinementNet(5, first_dim, device=devi... | class Generator(nn.Module):
def __init__(self, first_dim=32, isCheck=False, device=None):
super(Generator, self).__init__()
self.isCheck = isCheck
self.device = device
self.stage_1 = CoarseNet(5, first_dim, device=device)
self.stage_2 = RefinementNet(5, first_dim, device=devi... | # border, maybe
mask = mask.expand(masked_img.size(0),1,masked_img.size(2),masked_img.size(3))
small_mask = small_mask.expand(masked_img.size(0), 1, masked_img.size(2) // 8, masked_img.size(3) // 8)
if self.device:
ones = to_var(torch.ones(mask.size()), device=self.device)
... | # border, maybe
mask = mask.expand(masked_img.size(0),1,masked_img.size(2),masked_img.size(3))
small_mask = small_mask.expand(masked_img.size(0), 1, masked_img.size(2) // 8, masked_img.size(3) // 8)
if self.device:
ones = to_var(torch.ones(mask.size()), device=self.device)
... | 61 | 147 | 339 | 486 | from .ops import *
class Generator(nn.Module):
def __init__(self, first_dim=32, isCheck=False, device=None):
super(Generator, self).__init__()
self.isCheck = isCheck
self.device = device
self.stage_1 = CoarseNet(5, first_dim, device=device)
self.stage_2 = RefinementNet(5, f... | from .ops import *
class Generator(nn.Module):
def __init__(self, first_dim=32, isCheck=False, device=None):
super(Generator, self).__init__()
self.isCheck = isCheck
self.device = device
self.stage_1 = CoarseNet(5, first_dim, device=device)
self.stage_2 = RefinementNet(5, f... |
38,664 | /home/hieuvd/dung_repo/raw/stars_02/nbei_Deep-Flow-Guided-Video-Inpainting/Deep-Flow-Guided-Video-Inpainting | /home/hieuvd/dung_repo/raw/stars_02/nbei_Deep-Flow-Guided-Video-Inpainting/Deep-Flow-Guided-Video-Inpainting/models/DeepFill_Models/DeepFill.py | 69,70 | 54,84 | forward | RefinementNet | 70,84 | 70,84 | class RefinementNet(nn.Module):
'''
# input: B x 5 x W x H
# after down: B x 128(32*4) x W/4 x H/4
# after atrous: same with the output size of the down module
# after up : same with the input size
'''
def __init__(self, in_ch, out_ch, device=None):
super(RefinementNet,self).__init__... | class RefinementNet(nn.Module):
'''
# input: B x 5 x W x H
# after down: B x 128(32*4) x W/4 x H/4
# after atrous: same with the output size of the down module
# after up : same with the input size
'''
def __init__(self, in_ch, out_ch, device=None):
super(RefinementNet,self).__init__... | # conv branch
conv_x = self.down_conv_branch(x)
conv_x = self.atrous(conv_x)
# attention branch
attn_x = self.down_attn_branch(x)
attn_x, offset_flow = self.CAttn(attn_x, attn_x, mask=resized_mask)
# concat two branches
deconv_x = torch.cat([conv_x, att... | # conv branch
conv_x = self.down_conv_branch(x)
conv_x = self.atrous(conv_x)
# attention branch
attn_x = self.down_attn_branch(x)
attn_x, offset_flow = self.CAttn(attn_x, attn_x, mask=resized_mask)
# concat two branches
deconv_x = torch.cat([conv_x, att... | 46 | 295 | 184 | 479 | from .ops import *
class Generator(nn.Module):
def __init__(self, first_dim=32, isCheck=False, device=None):
super(Generator, self).__init__()
self.isCheck = isCheck
self.device = device
self.stage_1 = CoarseNet(5, first_dim, device=device)
self.stage_2 = RefinementNet(5, f... | from .ops import *
class Generator(nn.Module):
def __init__(self, first_dim=32, isCheck=False, device=None):
super(Generator, self).__init__()
self.isCheck = isCheck
self.device = device
self.stage_1 = CoarseNet(5, first_dim, device=device)
self.stage_2 = RefinementNet(5, f... |
38,803 | /home/hieuvd/dung_repo/raw/stars_02/nyaadevs_nyaa/nyaa | /home/hieuvd/dung_repo/raw/stars_02/nyaadevs_nyaa/nyaa/nyaa/bencode.py | 34,35 | 1,168 | _bencode_decode | 38,126 | 35,126 | from io import BytesIO
def _pairwise(iterable):
""" Returns items from an iterable two at a time, ala
[0, 1, 2, 3, ...] -> [(0, 1), (2, 3), ...] """
iterable = iter(iterable)
return zip(iterable, iterable)
__all__ = ['encode', 'decode', 'BencodeException', 'MalformedBencodeException']
# https:/... | from io import BytesIO
def _pairwise(iterable):
""" Returns items from an iterable two at a time, ala
[0, 1, 2, 3, ...] -> [(0, 1), (2, 3), ...] """
iterable = iter(iterable)
return zip(iterable, iterable)
__all__ = ['encode', 'decode', 'BencodeException', 'MalformedBencodeException']
# https:/... | if isinstance(file_object, str):
file_object = file_object.encode('utf8')
if isinstance(file_object, bytes):
file_object = BytesIO(file_object)
def create_ex(msg):
return MalformedBencodeException(
'{0} at position {1} (0x{1:02X} hex)'.format(msg, file_object.tell()))
... | """ Decodes a bencoded value, raising a MalformedBencodeException on errors.
decode_keys_as_utf8 controls decoding dict keys as utf8 (which they
almost always are) """
if isinstance(file_object, str):
file_object = file_object.encode('utf8')
if isinstance(file_object, bytes):
... | 312 | 801 | 998 | 1,799 | from io import BytesIO
def _pairwise(iterable):
""" Returns items from an iterable two at a time, ala
[0, 1, 2, 3, ...] -> [(0, 1), (2, 3), ...] """
iterable = iter(iterable)
return zip(iterable, iterable)
__all__ = ['encode', 'decode', 'BencodeException', 'MalformedBencodeException']
# https:/... | from io import BytesIO
def _pairwise(iterable):
""" Returns items from an iterable two at a time, ala
[0, 1, 2, 3, ...] -> [(0, 1), (2, 3), ...] """
iterable = iter(iterable)
return zip(iterable, iterable)
__all__ = ['encode', 'decode', 'BencodeException', 'MalformedBencodeException']
# https:/... | |
38,867 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/examples/archive_medias.py | 18,19 | 1,35 | archive_medias | 19,24 | 19,24 | """
instabot example
Workflow:
Archive medias.
"""
import argparse
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def archive_medias(bot, medias):
FILL_FUNC_BODYparser = argparse.ArgumentParser(add_help=True)
pars... | """
instabot example
Workflow:
Archive medias.
"""
import argparse
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def archive_medias(bot, medias):
FILL_FUNC_BODYparser = argparse.ArgumentParser(add_help=True)
pars... | for media in tqdm(medias, desc="Medias"):
bot.archive(media)
return True
| for media in tqdm(medias, desc="Medias"):
bot.archive(media)
return True
| 8 | 261 | 38 | 299 | """
instabot example
Workflow:
Archive medias.
"""
import argparse
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def archive_medias(bot, medias):
FILL_FUNC_BODYparser = argparse.ArgumentParser(add_help=True)
pars... | """
instabot example
Workflow:
Archive medias.
"""
import argparse
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def archive_medias(bot, medias):
FILL_FUNC_BODYparser = argparse.ArgumentParser(add_help=True)
pars... | |
38,868 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/examples/comment_medias_by_location.py | 29,30 | 1,102 | comment_location_feed | 30,50 | 30,50 | # coding=utf-8
"""
instabot example
Workflow:
Comment medias by location.
"""
import argparse
import codecs
import os
import sys
from tqdm import tqdm
stdout = sys.stdout
sys.stdout = codecs.getwriter("utf8")(sys.stdout)
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # ... | # coding=utf-8
"""
instabot example
Workflow:
Comment medias by location.
"""
import argparse
import codecs
import os
import sys
from tqdm import tqdm
stdout = sys.stdout
sys.stdout = codecs.getwriter("utf8")(sys.stdout)
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # ... | counter = 0
max_id = ""
with tqdm(total=amount) as pbar:
while counter < amount:
if new_bot.api.get_location_feed(
new_location["location"]["pk"], max_id=max_id
):
location_feed = new_bot.api.last_json
for media in new_bot.filte... | counter = 0
max_id = ""
with tqdm(total=amount) as pbar:
while counter < amount:
if new_bot.api.get_location_feed(
new_location["location"]["pk"], max_id=max_id
):
location_feed = new_bot.api.last_json
for media in new_bot.filte... | 46 | 822 | 209 | 1,031 | # coding=utf-8
"""
instabot example
Workflow:
Comment medias by location.
"""
import argparse
import codecs
import os
import sys
from tqdm import tqdm
stdout = sys.stdout
sys.stdout = codecs.getwriter("utf8")(sys.stdout)
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # ... | # coding=utf-8
"""
instabot example
Workflow:
Comment medias by location.
"""
import argparse
import codecs
import os
import sys
from tqdm import tqdm
stdout = sys.stdout
sys.stdout = codecs.getwriter("utf8")(sys.stdout)
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # ... | |
38,869 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/examples/get_hashtags_from_keywords.py | 23,24 | 1,68 | dispositions | 24,39 | 24,39 | from __future__ import unicode_literals
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
if len(sys.argv) < 2:
print(
"Please provide keywords separated by space\n"
"Usage:\n"
"python get_hashtags_from_key... | from __future__ import unicode_literals
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
if len(sys.argv) < 2:
print(
"Please provide keywords separated by space\n"
"Usage:\n"
"python get_hashtags_from_key... | from itertools import permutations
print("Generating dispositions...")
res = []
res += [a for a in l]
length = len(l)
num = 2
while num <= length:
p = list(permutations(l, num))
res += [" ".join(c) for c in p]
num += 1
print("Generated {} dispositions".format(len... | from itertools import permutations
print("Generating dispositions...")
res = []
res += [a for a in l]
length = len(l)
num = 2
while num <= length:
p = list(permutations(l, num))
res += [" ".join(c) for c in p]
num += 1
print("Generated {} dispositions".format(len... | 46 | 520 | 125 | 645 | from __future__ import unicode_literals
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
if len(sys.argv) < 2:
print(
"Please provide keywords separated by space\n"
"Usage:\n"
"python get_hashtags_from_key... | from __future__ import unicode_literals
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
if len(sys.argv) < 2:
print(
"Please provide keywords separated by space\n"
"Usage:\n"
"python get_hashtags_from_key... | |
38,870 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/examples/interact_DM.py | 28,29 | 1,58 | choice | 29,39 | 29,39 | # -*- coding: utf-8 -*-
"""
instabot example
Workflow:
read and reply your DM
"""
import argparse
import os
import sys
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
try:
input = raw_input
except NameError:
pass
parser = argparse.ArgumentParser(add_... | # -*- coding: utf-8 -*-
"""
instabot example
Workflow:
read and reply your DM
"""
import argparse
import os
import sys
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
try:
input = raw_input
except NameError:
pass
parser = argparse.ArgumentParser(add_... | get_choice = input(message)
if get_choice == "y":
return True
elif get_choice == "n":
return False
else:
print("Invalid Input")
return choice(message)
| get_choice = input(message)
if get_choice == "y":
return True
elif get_choice == "n":
return False
else:
print("Invalid Input")
return choice(message)
| 20 | 446 | 68 | 514 | # -*- coding: utf-8 -*-
"""
instabot example
Workflow:
read and reply your DM
"""
import argparse
import os
import sys
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
try:
input = raw_input
except NameError:
pass
parser = argparse.ArgumentParser(add_... | # -*- coding: utf-8 -*-
"""
instabot example
Workflow:
read and reply your DM
"""
import argparse
import os
import sys
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
try:
input = raw_input
except NameError:
pass
parser = argparse.ArgumentParser(add_... | |
38,871 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/examples/like_and_follow_media_likers.py | 26,27 | 1,44 | like_and_follow_media_likers | 27,33 | 27,33 | """
instabot example
Workflow:
Like and follow you last media likers.
"""
import argparse
import os
import random
import sys
import time
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def like_and_follow(bot, user_id, nlikes=3):
b... | """
instabot example
Workflow:
Like and follow you last media likers.
"""
import argparse
import os
import random
import sys
import time
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def like_and_follow(bot, user_id, nlikes=3):
b... | for user in tqdm(bot.get_media_likers(media), desc="Media likers"):
like_and_follow(bot, user, nlikes)
time.sleep(10 + 20 * random.random())
return True
| for user in tqdm(bot.get_media_likers(media), desc="Media likers"):
like_and_follow(bot, user, nlikes)
time.sleep(10 + 20 * random.random())
return True
| 16 | 336 | 72 | 408 | """
instabot example
Workflow:
Like and follow you last media likers.
"""
import argparse
import os
import random
import sys
import time
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def like_and_follow(bot, user_id, nlikes=3):
b... | """
instabot example
Workflow:
Like and follow you last media likers.
"""
import argparse
import os
import random
import sys
import time
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def like_and_follow(bot, user_id, nlikes=3):
b... | |
38,872 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/examples/like_and_follow_your_last_media_likers.py | 26,27 | 1,49 | like_and_follow_media_likers | 27,33 | 27,33 | """
instabot example
Workflow:
Like and follow likers of last medias from your timeline feed.
"""
import argparse
import os
import random
import sys
import time
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def like_and_follow(bot, u... | """
instabot example
Workflow:
Like and follow likers of last medias from your timeline feed.
"""
import argparse
import os
import random
import sys
import time
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def like_and_follow(bot, u... | for user in tqdm(bot.get_media_likers(media), desc="Media likers"):
like_and_follow(bot, user, nlikes)
time.sleep(10 + 20 * random.random())
return True
| for user in tqdm(bot.get_media_likers(media), desc="Media likers"):
like_and_follow(bot, user, nlikes)
time.sleep(10 + 20 * random.random())
return True
| 16 | 410 | 72 | 482 | """
instabot example
Workflow:
Like and follow likers of last medias from your timeline feed.
"""
import argparse
import os
import random
import sys
import time
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def like_and_follow(bot, u... | """
instabot example
Workflow:
Like and follow likers of last medias from your timeline feed.
"""
import argparse
import os
import random
import sys
import time
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def like_and_follow(bot, u... | |
38,873 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/examples/like_medias_by_location.py | 29,30 | 1,106 | like_location_feed | 30,51 | 30,51 | # coding=utf-8
"""
instabot example
Workflow:
Like medias by location.
"""
import argparse
import codecs
import os
import sys
from tqdm import tqdm
stdout = sys.stdout
sys.stdout = codecs.getwriter("utf8")(sys.stdout)
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noq... | # coding=utf-8
"""
instabot example
Workflow:
Like medias by location.
"""
import argparse
import codecs
import os
import sys
from tqdm import tqdm
stdout = sys.stdout
sys.stdout = codecs.getwriter("utf8")(sys.stdout)
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noq... | counter = 0
max_id = ""
with tqdm(total=amount) as pbar:
while counter < amount:
if new_bot.api.get_location_feed(
new_location["location"]["pk"], max_id=max_id
):
location_feed = new_bot.api.last_json
for media in new_bot.filte... | counter = 0
max_id = ""
with tqdm(total=amount) as pbar:
while counter < amount:
if new_bot.api.get_location_feed(
new_location["location"]["pk"], max_id=max_id
):
location_feed = new_bot.api.last_json
for media in new_bot.filte... | 45 | 821 | 209 | 1,030 | # coding=utf-8
"""
instabot example
Workflow:
Like medias by location.
"""
import argparse
import codecs
import os
import sys
from tqdm import tqdm
stdout = sys.stdout
sys.stdout = codecs.getwriter("utf8")(sys.stdout)
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noq... | # coding=utf-8
"""
instabot example
Workflow:
Like medias by location.
"""
import argparse
import codecs
import os
import sys
from tqdm import tqdm
stdout = sys.stdout
sys.stdout = codecs.getwriter("utf8")(sys.stdout)
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noq... | |
38,874 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/examples/like_your_last_media_likers.py | 17,18 | 1,37 | like_media_likers | 18,23 | 18,23 | """
instabot example
Workflow:
Like likers of last medias from your timeline feed.
"""
import argparse
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def like_media_likers(bot, media, nlikes=3):
FILL_FUNC_BODYdef l... | """
instabot example
Workflow:
Like likers of last medias from your timeline feed.
"""
import argparse
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def like_media_likers(bot, media, nlikes=3):
FILL_FUNC_BODYdef l... | for user in tqdm(bot.get_media_likers(media), desc="Media likers"):
bot.like_user(user, nlikes)
return True
| for user in tqdm(bot.get_media_likers(media), desc="Media likers"):
bot.like_user(user, nlikes)
return True
| 10 | 307 | 53 | 360 | """
instabot example
Workflow:
Like likers of last medias from your timeline feed.
"""
import argparse
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def like_media_likers(bot, media, nlikes=3):
FILL_FUNC_BODYdef l... | """
instabot example
Workflow:
Like likers of last medias from your timeline feed.
"""
import argparse
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
def like_media_likers(bot, media, nlikes=3):
FILL_FUNC_BODYdef l... | |
38,876 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/examples/repost_best_photos_from_users.py | 72,73 | 1,115 | repost_photo | 73,96 | 73,96 | """
instabot example
Workflow:
Repost best photos from users to your account
By default bot checks username_database.txt
The file should contain one username per line!
"""
import argparse
import os
import sys
import random
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
fr... | """
instabot example
Workflow:
Repost best photos from users to your account
By default bot checks username_database.txt
The file should contain one username per line!
"""
import argparse
import os
import sys
import random
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
fr... | if exists_in_posted_medias(new_media_id, path):
bot.logger.warning("Media {} was uploaded earlier".format(new_media_id))
return False
photo_path = bot.download_photo(new_media_id, save_description=True)
if not photo_path or not isinstance(photo_path, str):
# photo_path could be True,... | if exists_in_posted_medias(new_media_id, path):
bot.logger.warning("Media {} was uploaded earlier".format(new_media_id))
return False
photo_path = bot.download_photo(new_media_id, save_description=True)
if not photo_path or not isinstance(photo_path, str):
# photo_path could be True,... | 81 | 980 | 310 | 1,290 | """
instabot example
Workflow:
Repost best photos from users to your account
By default bot checks username_database.txt
The file should contain one username per line!
"""
import argparse
import os
import sys
import random
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
fr... | """
instabot example
Workflow:
Repost best photos from users to your account
By default bot checks username_database.txt
The file should contain one username per line!
"""
import argparse
import os
import sys
import random
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], "../"))
fr... | |
38,877 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/examples/repost_photo.py | 21,22 | 1,53 | update_posted_medias | 22,29 | 22,29 | """
instabot example
Workflow:
1) Repost photo to your account
"""
import os
import sys
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
from instabot.bot.bot_support import read_list_from_file # noqa: E402
def exists_in_posted_medias(new_media_id, path="config/... | """
instabot example
Workflow:
1) Repost photo to your account
"""
import os
import sys
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
from instabot.bot.bot_support import read_list_from_file # noqa: E402
def exists_in_posted_medias(new_media_id, path="config/... | medias = read_list_from_file(path)
medias.append(str(new_media_id))
with open(path, "w") as file:
file.writelines("\n".join(medias))
return True
| medias = read_list_from_file(path)
medias.append(str(new_media_id))
with open(path, "w") as file:
file.writelines("\n".join(medias))
return True
| 12 | 467 | 70 | 537 | """
instabot example
Workflow:
1) Repost photo to your account
"""
import os
import sys
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
from instabot.bot.bot_support import read_list_from_file # noqa: E402
def exists_in_posted_medias(new_media_id, path="config/... | """
instabot example
Workflow:
1) Repost photo to your account
"""
import os
import sys
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
from instabot.bot.bot_support import read_list_from_file # noqa: E402
def exists_in_posted_medias(new_media_id, path="config/... | |
38,878 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/examples/reset_following.py | 52,54 | 16,79 | one | Task | 54,66 | 54,66 | class Task(object):
# getting the user to pick what to do
@staticmethod
def start(bot):
answer = input(
"""
Please select
1) Create Friends List
Make a list of the users you follow before you follow bot.
2) Restore Friends List
Unfollow all... | class Task(object):
# getting the user to pick what to do
@staticmethod
def start(bot):
answer = input(
"""
Please select
1) Create Friends List
Make a list of the users you follow before you follow bot.
2) Restore Friends List
Unfollow all... | print("Creating List")
friends = bot.following
with open(
"friends_{}.txt".format(bot.username), "w"
) as file: # writing to the file
for user_id in friends:
file.write(str(user_id) + "\n")
print("Task Done")
Task.start(bot) # go ... | print("Creating List")
friends = bot.following
with open(
"friends_{}.txt".format(bot.username), "w"
) as file: # writing to the file
for user_id in friends:
file.write(str(user_id) + "\n")
print("Task Done")
Task.start(bot) # go ... | 38 | 373 | 117 | 490 | """
This is a account reset tool.
Use this before you start boting.
You can then reset the users you follow to what you had before botting.
"""
import os
import sys
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
# class of all the tasks
class Task(object):
# getting th... | """
This is a account reset tool.
Use this before you start boting.
You can then reset the users you follow to what you had before botting.
"""
import os
import sys
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
# class of all the tasks
class Task(object):
# getting th... |
38,879 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/examples/ultimate_schedule/ultimate.py | 82,83 | 1,151 | upload_pictures | 83,114 | 83,114 | # -*- coding: utf-8 -*-
import os
import sys
import threading
import time
import argparse
import config
from glob import glob
sys.path.append(os.path.join(sys.path[0], "../../"))
import schedule # noqa: E402
from instabot import Bot, utils # noqa: E402
bot = Bot(
comments_file=config.COMMENTS_FILE,
black... | # -*- coding: utf-8 -*-
import os
import sys
import threading
import time
import argparse
import config
from glob import glob
sys.path.append(os.path.join(sys.path[0], "../../"))
import schedule # noqa: E402
from instabot import Bot, utils # noqa: E402
bot = Bot(
comments_file=config.COMMENTS_FILE,
black... | try:
for pic in pics:
if pic in posted_pic_list:
continue
caption = photo_captions_file.random()
full_caption = caption + "\n" + config.FOLLOW_MESSAGE
bot.logger.info("Uploading pic with caption: " + caption)
bot.upload_photo(confi... | try:
for pic in pics:
if pic in posted_pic_list:
continue
caption = photo_captions_file.random()
full_caption = caption + "\n" + config.FOLLOW_MESSAGE
bot.logger.info("Uploading pic with caption: " + caption)
bot.upload_photo(confi... | 106 | 1,376 | 407 | 1,783 | # -*- coding: utf-8 -*-
import os
import sys
import threading
import time
import argparse
import config
from glob import glob
sys.path.append(os.path.join(sys.path[0], "../../"))
import schedule # noqa: E402
from instabot import Bot, utils # noqa: E402
bot = Bot(
comments_file=config.COMMENTS_FILE,
black... | # -*- coding: utf-8 -*-
import os
import sys
import threading
import time
import argparse
import config
from glob import glob
sys.path.append(os.path.join(sys.path[0], "../../"))
import schedule # noqa: E402
from instabot import Bot, utils # noqa: E402
bot = Bot(
comments_file=config.COMMENTS_FILE,
black... | |
38,880 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/examples/welcome_message.py | 44,45 | 1,86 | main | 45,84 | 45,84 | """
instabot example
Workflow:
Welcome message for new followers.
"""
import argparse
import datetime
import os
import sys
import time
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
RETRY_DELAY = 60
DELAY = 30 * 60
def get_recent_followers(bot, from_time):
followers = ... | """
instabot example
Workflow:
Welcome message for new followers.
"""
import argparse
import datetime
import os
import sys
import time
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
RETRY_DELAY = 60
DELAY = 30 * 60
def get_recent_followers(bot, from_time):
followers = ... | parser = argparse.ArgumentParser(add_help=True)
parser.add_argument("-u", type=str, help="username")
parser.add_argument("-p", type=str, help="password")
parser.add_argument("-proxy", type=str, help="proxy")
parser.add_argument(
"-message",
type=str,
nargs="?",
help="... | parser = argparse.ArgumentParser(add_help=True)
parser.add_argument("-u", type=str, help="username")
parser.add_argument("-p", type=str, help="password")
parser.add_argument("-proxy", type=str, help="proxy")
parser.add_argument(
"-message",
type=str,
nargs="?",
help="... | 72 | 350 | 398 | 748 | """
instabot example
Workflow:
Welcome message for new followers.
"""
import argparse
import datetime
import os
import sys
import time
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
RETRY_DELAY = 60
DELAY = 30 * 60
def get_recent_followers(bot, from_time):
followers = ... | """
instabot example
Workflow:
Welcome message for new followers.
"""
import argparse
import datetime
import os
import sys
import time
sys.path.append(os.path.join(sys.path[0], "../"))
from instabot import Bot # noqa: E402
RETRY_DELAY = 60
DELAY = 30 * 60
def get_recent_followers(bot, from_time):
followers = ... | |
38,882 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/instabot/api/api_story.py | 31,32 | 1,93 | upload_story_photo | 32,73 | 32,73 | from __future__ import unicode_literals
import json
import os
import shutil
import time
from random import randint
from requests_toolbelt import MultipartEncoder
from . import config
from .api_photo import get_image_size, stories_shaper
def download_story(self, filename, story_url, username):
path = "stories/{... | from __future__ import unicode_literals
import json
import os
import shutil
import time
from random import randint
from requests_toolbelt import MultipartEncoder
from . import config
from .api_photo import get_image_size, stories_shaper
def download_story(self, filename, story_url, username):
path = "stories/{... | if upload_id is None:
upload_id = str(int(time.time() * 1000))
photo = stories_shaper(photo)
if not photo:
return False
with open(photo, "rb") as f:
photo_bytes = f.read()
data = {
"upload_id": upload_id,
"_uuid": self.uuid,
"_csrftoken": self.token,... | if upload_id is None:
upload_id = str(int(time.time() * 1000))
photo = stories_shaper(photo)
if not photo:
return False
with open(photo, "rb") as f:
photo_bytes = f.read()
data = {
"upload_id": upload_id,
"_uuid": self.uuid,
"_csrftoken": self.token,... | 88 | 599 | 432 | 1,031 | from __future__ import unicode_literals
import json
import os
import shutil
import time
from random import randint
from requests_toolbelt import MultipartEncoder
from . import config
from .api_photo import get_image_size, stories_shaper
def download_story(self, filename, story_url, username):
path = "stories/{... | from __future__ import unicode_literals
import json
import os
import shutil
import time
from random import randint
from requests_toolbelt import MultipartEncoder
from . import config
from .api_photo import get_image_size, stories_shaper
def download_story(self, filename, story_url, username):
path = "stories/{... | |
38,883 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/instabot/bot/bot_archive.py | 33,34 | 1,46 | unarchive_medias | 34,46 | 34,46 | from tqdm import tqdm
def archive(self, media_id, undo=False):
self.small_delay()
media = self.get_media_info(media_id)
media = media[0] if isinstance(media, list) else media
if self.api.archive_media(media, undo):
self.total["archived"] += int(not undo)
self.total["unarchived"] += int... | from tqdm import tqdm
def archive(self, media_id, undo=False):
self.small_delay()
media = self.get_media_info(media_id)
media = media[0] if isinstance(media, list) else media
if self.api.archive_media(media, undo):
self.total["archived"] += int(not undo)
self.total["unarchived"] += int... | broken_items = []
if not medias:
self.logger.info("Nothing to unarchive.")
return broken_items
self.logger.info("Going to unarchive %d medias." % (len(medias)))
for media in tqdm(medias):
if not self.unarchive(media):
self.error_delay()
broken_items = medi... | broken_items = []
if not medias:
self.logger.info("Nothing to unarchive.")
return broken_items
self.logger.info("Going to unarchive %d medias." % (len(medias)))
for media in tqdm(medias):
if not self.unarchive(media):
self.error_delay()
broken_items = medi... | 40 | 343 | 158 | 501 | from tqdm import tqdm
def archive(self, media_id, undo=False):
self.small_delay()
media = self.get_media_info(media_id)
media = media[0] if isinstance(media, list) else media
if self.api.archive_media(media, undo):
self.total["archived"] += int(not undo)
self.total["unarchived"] += int... | from tqdm import tqdm
def archive(self, media_id, undo=False):
self.small_delay()
media = self.get_media_info(media_id)
media = media[0] if isinstance(media, list) else media
if self.api.archive_media(media, undo):
self.total["archived"] += int(not undo)
self.total["unarchived"] += int... | |
38,884 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/instabot/bot/bot_block.py | 32,33 | 1,68 | block_users | 33,44 | 33,44 | import random
from tqdm import tqdm
def block(self, user_id):
user_id = self.convert_to_user_id(user_id)
if self.check_not_bot(user_id):
return True
if not self.reached_limit("blocks"):
self.delay("block")
if self.api.block(user_id):
self.total["blocks"] += 1
... | import random
from tqdm import tqdm
def block(self, user_id):
user_id = self.convert_to_user_id(user_id)
if self.check_not_bot(user_id):
return True
if not self.reached_limit("blocks"):
self.delay("block")
if self.api.block(user_id):
self.total["blocks"] += 1
... | broken_items = []
self.logger.info("Going to block %d users." % len(user_ids))
for user_id in tqdm(user_ids):
if not self.block(user_id):
self.error_delay()
broken_items = user_ids[user_ids.index(user_id) :]
break
self.logger.info("DONE: Total blocked %d users... | broken_items = []
self.logger.info("Going to block %d users." % len(user_ids))
for user_id in tqdm(user_ids):
if not self.block(user_id):
self.error_delay()
broken_items = user_ids[user_ids.index(user_id) :]
break
self.logger.info("DONE: Total blocked %d users... | 32 | 569 | 134 | 703 | import random
from tqdm import tqdm
def block(self, user_id):
user_id = self.convert_to_user_id(user_id)
if self.check_not_bot(user_id):
return True
if not self.reached_limit("blocks"):
self.delay("block")
if self.api.block(user_id):
self.total["blocks"] += 1
... | import random
from tqdm import tqdm
def block(self, user_id):
user_id = self.convert_to_user_id(user_id)
if self.check_not_bot(user_id):
return True
if not self.reached_limit("blocks"):
self.delay("block")
if self.api.block(user_id):
self.total["blocks"] += 1
... | |
38,885 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/instabot/bot/bot_checkpoint.py | 54,55 | 1,68 | load_checkpoint | 55,68 | 55,68 | """
Instabot Checkpoint methods.
"""
import os
import pickle
from datetime import datetime
CHECKPOINT_PATH = "{fname}.checkpoint"
class Checkpoint(object):
"""
Checkpoint for instabot.Bot class which can store:
.total[<name>] - all Bot's counters
.blocked_actions[<name>] - Bo... | """
Instabot Checkpoint methods.
"""
import os
import pickle
from datetime import datetime
CHECKPOINT_PATH = "{fname}.checkpoint"
class Checkpoint(object):
"""
Checkpoint for instabot.Bot class which can store:
.total[<name>] - all Bot's counters
.blocked_actions[<name>] - Bo... | try:
fname = CHECKPOINT_PATH.format(fname=self.api.username)
fname = os.path.join(self.base_path, fname)
self.logger.debug("Loading Checkpoint file from: {}".format(fname))
with open(fname, "rb") as f:
checkpoint = pickle.load(f)
if isinstance(checkpoint, Checkpoi... | try:
fname = CHECKPOINT_PATH.format(fname=self.api.username)
fname = os.path.join(self.base_path, fname)
self.logger.debug("Loading Checkpoint file from: {}".format(fname))
with open(fname, "rb") as f:
checkpoint = pickle.load(f)
if isinstance(checkpoint, Checkpoi... | 33 | 530 | 151 | 681 | """
Instabot Checkpoint methods.
"""
import os
import pickle
from datetime import datetime
CHECKPOINT_PATH = "{fname}.checkpoint"
class Checkpoint(object):
"""
Checkpoint for instabot.Bot class which can store:
.total[<name>] - all Bot's counters
.blocked_actions[<name>] - Bo... | """
Instabot Checkpoint methods.
"""
import os
import pickle
from datetime import datetime
CHECKPOINT_PATH = "{fname}.checkpoint"
class Checkpoint(object):
"""
Checkpoint for instabot.Bot class which can store:
.total[<name>] - all Bot's counters
.blocked_actions[<name>] - Bo... | |
38,886 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/instabot/bot/bot_checkpoint.py | 37,38 | 12,44 | fill_followers | Checkpoint | 38,40 | 38,40 | class Checkpoint(object):
"""
Checkpoint for instabot.Bot class which can store:
.total[<name>] - all Bot's counters
.blocked_actions[<name>] - Bot's blocked actions
.following (list of user_ids)
.followers (list of user_ids)
.date (of checkpoint c... | class Checkpoint(object):
"""
Checkpoint for instabot.Bot class which can store:
.total[<name>] - all Bot's counters
.blocked_actions[<name>] - Bot's blocked actions
.following (list of user_ids)
.followers (list of user_ids)
.date (of checkpoint c... | self._followers = [item["pk"] for item in bot.api.get_total_self_followers()]
| self._followers = [item["pk"] for item in bot.api.get_total_self_followers()]
| 7 | 328 | 32 | 360 | """
Instabot Checkpoint methods.
"""
import os
import pickle
from datetime import datetime
CHECKPOINT_PATH = "{fname}.checkpoint"
class Checkpoint(object):
"""
Checkpoint for instabot.Bot class which can store:
.total[<name>] - all Bot's counters
.blocked_actions[<name>] - Bo... | """
Instabot Checkpoint methods.
"""
import os
import pickle
from datetime import datetime
CHECKPOINT_PATH = "{fname}.checkpoint"
class Checkpoint(object):
"""
Checkpoint for instabot.Bot class which can store:
.total[<name>] - all Bot's counters
.blocked_actions[<name>] - Bo... |
38,887 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/instabot/bot/bot_comment.py | 129,130 | 1,144 | comment_users | 130,137 | 130,137 | """
Bot functions to generate and post a comments.
Instructions to file with comments:
one line - one comment.
Example:
lol
kek
"""
from tqdm import tqdm
def comment(self, media_id, comment_text):
if self.is_commented(media_id):
return True
if not self.reached_li... | """
Bot functions to generate and post a comments.
Instructions to file with comments:
one line - one comment.
Example:
lol
kek
"""
from tqdm import tqdm
def comment(self, media_id, comment_text):
if self.is_commented(media_id):
return True
if not self.reached_li... | for user_id in user_ids:
if self.reached_limit("comments"):
self.logger.info("Out of comments for today.")
return
self.comment_user(user_id, amount=ncomments)
| for user_id in user_ids:
if self.reached_limit("comments"):
self.logger.info("Out of comments for today.")
return
self.comment_user(user_id, amount=ncomments)
| 14 | 1,418 | 67 | 1,485 | """
Bot functions to generate and post a comments.
Instructions to file with comments:
one line - one comment.
Example:
lol
kek
"""
from tqdm import tqdm
def comment(self, media_id, comment_text):
if self.is_commented(media_id):
return True
if not self.reached_li... | """
Bot functions to generate and post a comments.
Instructions to file with comments:
one line - one comment.
Example:
lol
kek
"""
from tqdm import tqdm
def comment(self, media_id, comment_text):
if self.is_commented(media_id):
return True
if not self.reached_li... | |
38,888 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/instabot/bot/bot_delete.py | 14,15 | 1,39 | delete_medias | 15,31 | 15,31 | from tqdm import tqdm
def delete_media(self, media_id):
self.small_delay()
media = self.get_media_info(media_id)
media = media[0] if isinstance(media, list) else media
if self.api.delete_media(media):
return True
self.logger.info("Media with {} is not {}.".format(media.get("id"), "deleted"... | from tqdm import tqdm
def delete_media(self, media_id):
self.small_delay()
media = self.get_media_info(media_id)
media = media[0] if isinstance(media, list) else media
if self.api.delete_media(media):
return True
self.logger.info("Media with {} is not {}.".format(media.get("id"), "deleted"... | broken_items = []
if not medias:
self.logger.info("Nothing to delete.")
return broken_items
self.logger.info("Going to delete %d medias." % (len(medias)))
for media in tqdm(medias):
if not self.delete_media(media):
self.error_delay()
broken_items = medias[... | broken_items = []
if not medias:
self.logger.info("Nothing to delete.")
return broken_items
self.logger.info("Going to delete %d medias." % (len(medias)))
for media in tqdm(medias):
if not self.delete_media(media):
self.error_delay()
broken_items = medias[... | 44 | 224 | 171 | 395 | from tqdm import tqdm
def delete_media(self, media_id):
self.small_delay()
media = self.get_media_info(media_id)
media = media[0] if isinstance(media, list) else media
if self.api.delete_media(media):
return True
self.logger.info("Media with {} is not {}.".format(media.get("id"), "deleted"... | from tqdm import tqdm
def delete_media(self, media_id):
self.small_delay()
media = self.get_media_info(media_id)
media = media[0] if isinstance(media, list) else media
if self.api.delete_media(media):
return True
self.logger.info("Media with {} is not {}.".format(media.get("id"), "deleted"... | |
38,894 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/instabot/bot/bot_photo.py | 94,95 | 1,108 | download_photos | 95,108 | 95,108 | import os
from io import open
from tqdm import tqdm
def upload_photo(
self, photo, caption=None, upload_id=None, from_video=False, options={}, user_tags=None, is_sidecar=False
):
"""Upload photo to Instagram
@param photo Path to photo file (String)
@param caption Media description (String)... | import os
from io import open
from tqdm import tqdm
def upload_photo(
self, photo, caption=None, upload_id=None, from_video=False, options={}, user_tags=None, is_sidecar=False
):
"""Upload photo to Instagram
@param photo Path to photo file (String)
@param caption Media description (String)... | broken_items = []
if not medias:
self.logger.info("Nothing to downloads.")
return broken_items
self.logger.info("Going to download {} medias.".format(len(medias)))
for media in tqdm(medias):
if not self.download_photo(media, folder, save_description=save_description):
... | broken_items = []
if not medias:
self.logger.info("Nothing to downloads.")
return broken_items
self.logger.info("Going to download {} medias.".format(len(medias)))
for media in tqdm(medias):
if not self.download_photo(media, folder, save_description=save_description):
... | 32 | 971 | 138 | 1,109 | import os
from io import open
from tqdm import tqdm
def upload_photo(
self, photo, caption=None, upload_id=None, from_video=False, options={}, user_tags=None, is_sidecar=False
):
"""Upload photo to Instagram
@param photo Path to photo file (String)
@param caption Media description (String)... | import os
from io import open
from tqdm import tqdm
def upload_photo(
self, photo, caption=None, upload_id=None, from_video=False, options={}, user_tags=None, is_sidecar=False
):
"""Upload photo to Instagram
@param photo Path to photo file (String)
@param caption Media description (String)... | |
38,895 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/instabot/bot/bot_stats.py | 12,13 | 1,50 | get_header_line | 13,17 | 13,17 | import datetime
import os
def get_tsv_line(dictionary):
line = ""
for key in sorted(dictionary):
line += str(dictionary[key]) + "\t"
return line[:-1] + "\n"
def get_header_line(dictionary):
FILL_FUNC_BODYdef ensure_dir(file_path):
directory = os.path.dirname(file_path)
if not os.path.exi... | import datetime
import os
def get_tsv_line(dictionary):
line = ""
for key in sorted(dictionary):
line += str(dictionary[key]) + "\t"
return line[:-1] + "\n"
def get_header_line(dictionary):
FILL_FUNC_BODYdef ensure_dir(file_path):
directory = os.path.dirname(file_path)
if not os.path.exi... | line = "\t".join(sorted(dictionary))
return line + "\n"
| line = "\t".join(sorted(dictionary))
return line + "\n"
| 7 | 473 | 29 | 502 | import datetime
import os
def get_tsv_line(dictionary):
line = ""
for key in sorted(dictionary):
line += str(dictionary[key]) + "\t"
return line[:-1] + "\n"
def get_header_line(dictionary):
FILL_FUNC_BODYdef ensure_dir(file_path):
directory = os.path.dirname(file_path)
if not os.path.exi... | import datetime
import os
def get_tsv_line(dictionary):
line = ""
for key in sorted(dictionary):
line += str(dictionary[key]) + "\t"
return line[:-1] + "\n"
def get_header_line(dictionary):
FILL_FUNC_BODYdef ensure_dir(file_path):
directory = os.path.dirname(file_path)
if not os.path.exi... | |
38,896 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/instabot/bot/bot_story.py | 29,30 | 1,66 | watch_users_reels | 37,66 | 30,66 | def download_stories(self, username):
user_id = self.get_user_id_from_username(username)
list_image, list_video = self.get_user_stories(user_id)
if list_image == [] and list_video == []:
self.logger.error(
(
"Make sure that '{}' is NOT private and that " "posted some stor... | def download_stories(self, username):
user_id = self.get_user_id_from_username(username)
list_image, list_video = self.get_user_stories(user_id)
if list_image == [] and list_video == []:
self.logger.error(
(
"Make sure that '{}' is NOT private and that " "posted some stor... |
# In case of only one user were passed
if not isinstance(user_ids, list):
user_ids = [user_ids]
# Get users reels
reels = self.api.get_users_reel(user_ids[:max_users])
# Filter to have users with at least 1 reel
if isinstance(reels, list):
# strange output
return False... | """
user_ids - the list of user_id to get their stories
max_users - max amount of users to get stories from.
It seems like Instagram doesn't allow to get stories
from more that 100 users at once.
"""
# In case of only one user were passed
if not isinstance(user_ids, lis... | 118 | 432 | 348 | 780 | def download_stories(self, username):
user_id = self.get_user_id_from_username(username)
list_image, list_video = self.get_user_stories(user_id)
if list_image == [] and list_video == []:
self.logger.error(
(
"Make sure that '{}' is NOT private and that " "posted some stor... | def download_stories(self, username):
user_id = self.get_user_id_from_username(username)
list_image, list_video = self.get_user_stories(user_id)
if list_image == [] and list_video == []:
self.logger.error(
(
"Make sure that '{}' is NOT private and that " "posted some stor... | |
38,898 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/instabot/bot/bot_unfollow.py | 5,6 | 1,130 | unfollow | 6,94 | 6,94 | from tqdm import tqdm
import time
def unfollow(self, user_id):
FILL_FUNC_BODYdef unfollow_users(self, user_ids):
broken_items = []
self.logger.info("Going to unfollow {} users.".format(len(user_ids)))
user_ids = set(map(str, user_ids))
filtered_user_ids = list(set(user_ids) - set(self.whitelist))
... | from tqdm import tqdm
import time
def unfollow(self, user_id):
FILL_FUNC_BODYdef unfollow_users(self, user_ids):
broken_items = []
self.logger.info("Going to unfollow {} users.".format(len(user_ids)))
user_ids = set(map(str, user_ids))
filtered_user_ids = list(set(user_ids) - set(self.whitelist))
... | user_id = self.convert_to_user_id(user_id)
user_info = self.get_user_info(user_id)
if not user_info:
self.logger.info("Can't get user_id=%s info" % str(user_id))
return False # No user_info
username = user_info.get("username")
if self.log_follow_unfollow:
msg = "Going to ... | user_id = self.convert_to_user_id(user_id)
user_info = self.get_user_info(user_id)
if not user_info:
self.logger.info("Can't get user_id=%s info" % str(user_id))
return False # No user_info
username = user_info.get("username")
if self.log_follow_unfollow:
msg = "Going to ... | 229 | 524 | 1,009 | 1,533 | from tqdm import tqdm
import time
def unfollow(self, user_id):
FILL_FUNC_BODYdef unfollow_users(self, user_ids):
broken_items = []
self.logger.info("Going to unfollow {} users.".format(len(user_ids)))
user_ids = set(map(str, user_ids))
filtered_user_ids = list(set(user_ids) - set(self.whitelist))
... | from tqdm import tqdm
import time
def unfollow(self, user_id):
FILL_FUNC_BODYdef unfollow_users(self, user_ids):
broken_items = []
self.logger.info("Going to unfollow {} users.".format(len(user_ids)))
user_ids = set(map(str, user_ids))
filtered_user_ids = list(set(user_ids) - set(self.whitelist))
... | |
38,899 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/instabot/bot/bot_unlike.py | 21,22 | 1,64 | unlike_media_comments | 22,47 | 22,47 | from tqdm import tqdm
def unlike(self, media_id):
if not self.reached_limit("unlikes"):
self.delay("unlike")
if self.api.unlike(media_id):
self.total["unlikes"] += 1
return True
else:
self.logger.info("Out of unlikes for today.")
return False
def unlike_co... | from tqdm import tqdm
def unlike(self, media_id):
if not self.reached_limit("unlikes"):
self.delay("unlike")
if self.api.unlike(media_id):
self.total["unlikes"] += 1
return True
else:
self.logger.info("Out of unlikes for today.")
return False
def unlike_co... | broken_items = []
media_comments = self.get_media_comments(media_id)
comment_ids = [item["pk"] for item in media_comments if item["has_liked_comment"]]
if not comment_ids:
self.logger.info(
"None comments received: comments not found"
" or comments have been filtered."
... | broken_items = []
media_comments = self.get_media_comments(media_id)
comment_ids = [item["pk"] for item in media_comments if item["has_liked_comment"]]
if not comment_ids:
self.logger.info(
"None comments received: comments not found"
" or comments have been filtered."
... | 65 | 390 | 260 | 650 | from tqdm import tqdm
def unlike(self, media_id):
if not self.reached_limit("unlikes"):
self.delay("unlike")
if self.api.unlike(media_id):
self.total["unlikes"] += 1
return True
else:
self.logger.info("Out of unlikes for today.")
return False
def unlike_co... | from tqdm import tqdm
def unlike(self, media_id):
if not self.reached_limit("unlikes"):
self.delay("unlike")
if self.api.unlike(media_id):
self.total["unlikes"] += 1
return True
else:
self.logger.info("Out of unlikes for today.")
return False
def unlike_co... | |
38,900 | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot | /home/hieuvd/dung_repo/raw/stars_02/ohld_igbot/igbot/instabot/bot/bot_video.py | 29,32 | 1,47 | download_video | 32,47 | 32,47 | import os
def upload_video(self, video, caption="", thumbnail=None, options={}):
"""Upload video to Instagram
@param video Path to video file (String)
@param caption Media description (String)
@param thumbnail Path to thumbnail for video (String). When None, then
thumbn... | import os
def upload_video(self, video, caption="", thumbnail=None, options={}):
"""Upload video to Instagram
@param video Path to video file (String)
@param caption Media description (String)
@param thumbnail Path to thumbnail for video (String). When None, then
thumbn... | self.small_delay()
if not os.path.exists(folder):
os.makedirs(folder)
if save_description:
media = self.get_media_info(media_id)[0]
caption = media["caption"]["text"] if media["caption"] else ""
username = media["user"]["username"]
fname = os.path.join(folder, "{}_{}.... | self.small_delay()
if not os.path.exists(folder):
os.makedirs(folder)
if save_description:
media = self.get_media_info(media_id)[0]
caption = media["caption"]["text"] if media["caption"] else ""
username = media["user"]["username"]
fname = os.path.join(folder, "{}_{}.... | 48 | 324 | 215 | 539 | import os
def upload_video(self, video, caption="", thumbnail=None, options={}):
"""Upload video to Instagram
@param video Path to video file (String)
@param caption Media description (String)
@param thumbnail Path to thumbnail for video (String). When None, then
thumbn... | import os
def upload_video(self, video, caption="", thumbnail=None, options={}):
"""Upload video to Instagram
@param video Path to video file (String)
@param caption Media description (String)
@param thumbnail Path to thumbnail for video (String). When None, then
thumbn... | |
38,925 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/data/prepare_consumer_to_shop.py | 41,42 | 1,146 | split_bbox | 42,76 | 42,76 | import os
PREFIX = 'Consumer_to_shop/Anno'
def split_img():
fn = open('Consumer_to_shop/Eval/list_eval_partition.txt').readlines()
# train dataset
train_consumer2shop = open(
os.path.join(PREFIX, 'train_consumer2shop.txt'), 'w')
train_imgs = []
# test dataset
test_consumer = open(os... | import os
PREFIX = 'Consumer_to_shop/Anno'
def split_img():
fn = open('Consumer_to_shop/Eval/list_eval_partition.txt').readlines()
# train dataset
train_consumer2shop = open(
os.path.join(PREFIX, 'train_consumer2shop.txt'), 'w')
train_imgs = []
# test dataset
test_consumer = open(os... | rf = open(os.path.join(PREFIX, 'list_bbox_consumer2shop.txt')).readlines()
img2bbox = {}
for i, line in enumerate(rf[2:]):
aline = line.strip('\n').split()
img = aline[0]
bbox = aline[-4:]
img2bbox[img] = bbox
wf_train = open(os.path.join(PREFIX, 'list_bbox_train.txt'), ... | rf = open(os.path.join(PREFIX, 'list_bbox_consumer2shop.txt')).readlines()
img2bbox = {}
for i, line in enumerate(rf[2:]):
aline = line.strip('\n').split()
img = aline[0]
bbox = aline[-4:]
img2bbox[img] = bbox
wf_train = open(os.path.join(PREFIX, 'list_bbox_train.txt'), ... | 147 | 1,358 | 521 | 1,879 | import os
PREFIX = 'Consumer_to_shop/Anno'
def split_img():
fn = open('Consumer_to_shop/Eval/list_eval_partition.txt').readlines()
# train dataset
train_consumer2shop = open(
os.path.join(PREFIX, 'train_consumer2shop.txt'), 'w')
train_imgs = []
# test dataset
test_consumer = open(os... | import os
PREFIX = 'Consumer_to_shop/Anno'
def split_img():
fn = open('Consumer_to_shop/Eval/list_eval_partition.txt').readlines()
# train dataset
train_consumer2shop = open(
os.path.join(PREFIX, 'train_consumer2shop.txt'), 'w')
train_imgs = []
# test dataset
test_consumer = open(os... | |
38,926 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/data/prepare_in_shop.py | 32,33 | 1,152 | split_label | 33,60 | 33,60 | import os
PREFIX = 'In-shop/Anno'
def split_img():
fn = open('In-shop/Eval/list_eval_partition.txt').readlines()
train = open(os.path.join(PREFIX, 'train_img.txt'), 'w')
query = open(os.path.join(PREFIX, 'query_img.txt'), 'w')
gallery = open(os.path.join(PREFIX, 'gallery_img.txt'), 'w')
for i, l... | import os
PREFIX = 'In-shop/Anno'
def split_img():
fn = open('In-shop/Eval/list_eval_partition.txt').readlines()
train = open(os.path.join(PREFIX, 'train_img.txt'), 'w')
query = open(os.path.join(PREFIX, 'query_img.txt'), 'w')
gallery = open(os.path.join(PREFIX, 'gallery_img.txt'), 'w')
for i, l... | id2label = {}
labelf = open(os.path.join(PREFIX, 'list_attr_items.txt')).readlines()
for line in labelf[2:]:
aline = line.strip('\n').split()
id, label = aline[0], aline[1:]
id2label[id] = label
def get_label(fn, prefix):
rf = open(fn).readlines()
wf = open(os.pa... | id2label = {}
labelf = open(os.path.join(PREFIX, 'list_attr_items.txt')).readlines()
for line in labelf[2:]:
aline = line.strip('\n').split()
id, label = aline[0], aline[1:]
id2label[id] = label
def get_label(fn, prefix):
rf = open(fn).readlines()
wf = open(os.pa... | 72 | 1,427 | 345 | 1,772 | import os
PREFIX = 'In-shop/Anno'
def split_img():
fn = open('In-shop/Eval/list_eval_partition.txt').readlines()
train = open(os.path.join(PREFIX, 'train_img.txt'), 'w')
query = open(os.path.join(PREFIX, 'query_img.txt'), 'w')
gallery = open(os.path.join(PREFIX, 'gallery_img.txt'), 'w')
for i, l... | import os
PREFIX = 'In-shop/Anno'
def split_img():
fn = open('In-shop/Eval/list_eval_partition.txt').readlines()
train = open(os.path.join(PREFIX, 'train_img.txt'), 'w')
query = open(os.path.join(PREFIX, 'query_img.txt'), 'w')
gallery = open(os.path.join(PREFIX, 'gallery_img.txt'), 'w')
for i, l... | |
38,927 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/data/prepare_landmark_detect.py | 27,28 | 1,114 | split_landmark | 28,73 | 28,73 | import os
PREFIX = 'Landmark_Detect/Anno'
def split_img():
rf = open('Landmark_Detect/Eval//list_eval_partition.txt').readlines()
wf1 = open(os.path.join(PREFIX, 'train.txt'), 'w')
wf2 = open(os.path.join(PREFIX, 'test.txt'), 'w')
wf3 = open(os.path.join(PREFIX, 'val.txt'), 'w')
for i, line in e... | import os
PREFIX = 'Landmark_Detect/Anno'
def split_img():
rf = open('Landmark_Detect/Eval//list_eval_partition.txt').readlines()
wf1 = open(os.path.join(PREFIX, 'train.txt'), 'w')
wf2 = open(os.path.join(PREFIX, 'test.txt'), 'w')
wf3 = open(os.path.join(PREFIX, 'val.txt'), 'w')
for i, line in e... | rf = open(os.path.join(PREFIX, 'list_landmarks.txt')).readlines()
wf1 = open(os.path.join(PREFIX, 'train_landmarks.txt'), 'w')
wf2 = open(os.path.join(PREFIX, 'test_landmarks.txt'), 'w')
wf3 = open(os.path.join(PREFIX, 'val_landmarks.txt'), 'w')
def sort_landmark():
d = dict()
for i... | rf = open(os.path.join(PREFIX, 'list_landmarks.txt')).readlines()
wf1 = open(os.path.join(PREFIX, 'train_landmarks.txt'), 'w')
wf2 = open(os.path.join(PREFIX, 'test_landmarks.txt'), 'w')
wf3 = open(os.path.join(PREFIX, 'val_landmarks.txt'), 'w')
def sort_landmark():
d = dict()
for i... | 123 | 822 | 540 | 1,362 | import os
PREFIX = 'Landmark_Detect/Anno'
def split_img():
rf = open('Landmark_Detect/Eval//list_eval_partition.txt').readlines()
wf1 = open(os.path.join(PREFIX, 'train.txt'), 'w')
wf2 = open(os.path.join(PREFIX, 'test.txt'), 'w')
wf3 = open(os.path.join(PREFIX, 'val.txt'), 'w')
for i, line in e... | import os
PREFIX = 'Landmark_Detect/Anno'
def split_img():
rf = open('Landmark_Detect/Eval//list_eval_partition.txt').readlines()
wf1 = open(os.path.join(PREFIX, 'train.txt'), 'w')
wf2 = open(os.path.join(PREFIX, 'test.txt'), 'w')
wf3 = open(os.path.join(PREFIX, 'val.txt'), 'w')
for i, line in e... | |
38,928 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/apis/env.py | 25,26 | 1,69 | _init_dist_pytorch | 26,33 | 26,33 | import logging
import os
import random
import subprocess
import numpy as np
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
def init_dist(launcher, backend='nccl', **kwargs):
if mp.get_start_method(allow_none=True) is None:
mp.set_start_method('spawn')
if launcher == ... | import logging
import os
import random
import subprocess
import numpy as np
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
def init_dist(launcher, backend='nccl', **kwargs):
if mp.get_start_method(allow_none=True) is None:
mp.set_start_method('spawn')
if launcher == ... | # TODO: use local_rank instead of rank % num_gpus
rank = int(os.environ['RANK'])
num_gpus = torch.cuda.device_count()
torch.cuda.set_device(rank % num_gpus)
dist.init_process_group(backend=backend, **kwargs)
| # TODO: use local_rank instead of rank % num_gpus
rank = int(os.environ['RANK'])
num_gpus = torch.cuda.device_count()
torch.cuda.set_device(rank % num_gpus)
dist.init_process_group(backend=backend, **kwargs)
| 20 | 666 | 96 | 762 | import logging
import os
import random
import subprocess
import numpy as np
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
def init_dist(launcher, backend='nccl', **kwargs):
if mp.get_start_method(allow_none=True) is None:
mp.set_start_method('spawn')
if launcher == ... | import logging
import os
import random
import subprocess
import numpy as np
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
def init_dist(launcher, backend='nccl', **kwargs):
if mp.get_start_method(allow_none=True) is None:
mp.set_start_method('spawn')
if launcher == ... | |
38,929 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/apis/test_virtual_tryon.py | 74,75 | 1,106 | _non_dist_test_tryon | 75,103 | 75,103 | from __future__ import division
import os
from ..datasets import build_dataloader
from ..utils import save_imgs
from .env import get_root_logger
def test_geometric_matching(model,
dataset,
cfg,
distributed=False,
... | from __future__ import division
import os
from ..datasets import build_dataloader
from ..utils import save_imgs
from .env import get_root_logger
def test_geometric_matching(model,
dataset,
cfg,
distributed=False,
... | data_loader = build_dataloader(
dataset,
cfg.data.imgs_per_gpu,
cfg.data.workers_per_gpu,
len(cfg.gpus.test),
dist=False,
shuffle=False)
# save dir
try_on_dir = os.path.join(cfg.data.test.TOM.save_dir, 'try-on')
if not os.path.exists(try_on_dir):
... | data_loader = build_dataloader(
dataset,
cfg.data.imgs_per_gpu,
cfg.data.workers_per_gpu,
len(cfg.gpus.test),
dist=False,
shuffle=False)
# save dir
try_on_dir = os.path.join(cfg.data.test.TOM.save_dir, 'try-on')
if not os.path.exists(try_on_dir):
... | 52 | 783 | 312 | 1,095 | from __future__ import division
import os
from ..datasets import build_dataloader
from ..utils import save_imgs
from .env import get_root_logger
def test_geometric_matching(model,
dataset,
cfg,
distributed=False,
... | from __future__ import division
import os
from ..datasets import build_dataloader
from ..utils import save_imgs
from .env import get_root_logger
def test_geometric_matching(model,
dataset,
cfg,
distributed=False,
... | |
38,930 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/apis/utils.py | 16,17 | 1,42 | build_criterion | 17,42 | 17,42 | import torch.nn as nn
import torch.optim as optim
def build_optimizer(model, optim_cfg):
if optim_cfg['type'] == 'SGD':
optimizer = optim.SGD(
model.parameters(), lr=optim_cfg.lr, momentum=optim_cfg.momentum)
elif optim_cfg['type'] == 'Adam':
optimizer = optim.Adam(model.parameters... | import torch.nn as nn
import torch.optim as optim
def build_optimizer(model, optim_cfg):
if optim_cfg['type'] == 'SGD':
optimizer = optim.SGD(
model.parameters(), lr=optim_cfg.lr, momentum=optim_cfg.momentum)
elif optim_cfg['type'] == 'Adam':
optimizer = optim.Adam(model.parameters... |
if loss_dict.type == 'CrossEntropyLoss':
weight = loss_dict.weight
size_average = loss_dict.size_average
reduce = loss_dict.reduce
reduction = loss_dict.reduction
if loss_dict.use_sigmoid:
return nn.BCEWithLogitsLoss(
weight=weight,
... |
if loss_dict.type == 'CrossEntropyLoss':
weight = loss_dict.weight
size_average = loss_dict.size_average
reduce = loss_dict.reduce
reduction = loss_dict.reduction
if loss_dict.use_sigmoid:
return nn.BCEWithLogitsLoss(
weight=weight,
... | 44 | 172 | 265 | 437 | import torch.nn as nn
import torch.optim as optim
def build_optimizer(model, optim_cfg):
if optim_cfg['type'] == 'SGD':
optimizer = optim.SGD(
model.parameters(), lr=optim_cfg.lr, momentum=optim_cfg.momentum)
elif optim_cfg['type'] == 'Adam':
optimizer = optim.Adam(model.parameters... | import torch.nn as nn
import torch.optim as optim
def build_optimizer(model, optim_cfg):
if optim_cfg['type'] == 'SGD':
optimizer = optim.SGD(
model.parameters(), lr=optim_cfg.lr, momentum=optim_cfg.momentum)
elif optim_cfg['type'] == 'Adam':
optimizer = optim.Adam(model.parameters... | |
38,931 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/core/evaluation/attr_predict_demo.py | 27,28 | 5,41 | show_prediction | AttrPredictor | 28,41 | 28,41 | class AttrPredictor(object):
def __init__(self, cfg, tops_type=[3, 5, 10]):
"""Create the empty array to count true positive(tp),
true negative(tn), false positive(fp) and false negative(fn).
Args:
class_num : number of classes in the dataset
tops_type : default... | class AttrPredictor(object):
def __init__(self, cfg, tops_type=[3, 5, 10]):
"""Create the empty array to count true positive(tp),
true negative(tn), false positive(fp) and false negative(fn).
Args:
class_num : number of classes in the dataset
tops_type : default... | if isinstance(pred, torch.Tensor):
data = pred.data.cpu().numpy()
elif isinstance(pred, np.ndarray):
data = pred
else:
raise TypeError('type {} cannot be calculated.'.format(type(pred)))
for i in range(pred.size(0)):
indexes = np.argsort(d... | if isinstance(pred, torch.Tensor):
data = pred.data.cpu().numpy()
elif isinstance(pred, np.ndarray):
data = pred
else:
raise TypeError('type {} cannot be calculated.'.format(type(pred)))
for i in range(pred.size(0)):
indexes = np.argsort(d... | 41 | 262 | 169 | 431 | import numpy as np
import torch
class AttrPredictor(object):
def __init__(self, cfg, tops_type=[3, 5, 10]):
"""Create the empty array to count true positive(tp),
true negative(tn), false positive(fp) and false negative(fn).
Args:
class_num : number of classes in the datas... | import numpy as np
import torch
class AttrPredictor(object):
def __init__(self, cfg, tops_type=[3, 5, 10]):
"""Create the empty array to count true positive(tp),
true negative(tn), false positive(fp) and false negative(fn).
Args:
class_num : number of classes in the datas... |
38,932 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/core/evaluation/attr_predict_eval.py | 80,81 | 5,178 | index_to_attribute_name | AttrCalculator | 81,85 | 81,85 | class AttrCalculator(object):
def __init__(self,
cfg,
topns=[3, 5, 10],
show_attr_name=False,
attr_name_file=None):
"""Create the empty array to count true positive(tp),
true negative(tn), false positive(fp) and false negative(... | class AttrCalculator(object):
def __init__(self,
cfg,
topns=[3, 5, 10],
show_attr_name=False,
attr_name_file=None):
"""Create the empty array to count true positive(tp),
true negative(tn), false positive(fp) and false negative(... | for pred_i in index:
pred_attr_name = self.attr_dict[pred_i]
print(pred_attr_name)
| for pred_i in index:
pred_attr_name = self.attr_dict[pred_i]
print(pred_attr_name)
| 8 | 1,954 | 42 | 1,996 | import numpy as np
import torch
class AttrCalculator(object):
def __init__(self,
cfg,
topns=[3, 5, 10],
show_attr_name=False,
attr_name_file=None):
"""Create the empty array to count true positive(tp),
true negative(tn), fals... | import numpy as np
import torch
class AttrCalculator(object):
def __init__(self,
cfg,
topns=[3, 5, 10],
show_attr_name=False,
attr_name_file=None):
"""Create the empty array to count true positive(tp),
true negative(tn), fals... |
38,933 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/core/evaluation/cate_predict_demo.py | 27,28 | 5,41 | show_prediction | CatePredictor | 28,41 | 28,41 | class CatePredictor(object):
def __init__(self, cfg, tops_type=[1, 3, 5]):
"""Create the empty array to count true positive(tp),
true negative(tn), false positive(fp) and false negative(fn).
Args:
class_num : number of classes in the dataset
tops_type : default ... | class CatePredictor(object):
def __init__(self, cfg, tops_type=[1, 3, 5]):
"""Create the empty array to count true positive(tp),
true negative(tn), false positive(fp) and false negative(fn).
Args:
class_num : number of classes in the dataset
tops_type : default ... | if isinstance(pred, torch.Tensor):
data = pred.data.cpu().numpy()
elif isinstance(pred, np.ndarray):
data = pred
else:
raise TypeError('type {} cannot be calculated.'.format(type(pred)))
for i in range(pred.size(0)):
indexes = np.argsort(d... | if isinstance(pred, torch.Tensor):
data = pred.data.cpu().numpy()
elif isinstance(pred, np.ndarray):
data = pred
else:
raise TypeError('type {} cannot be calculated.'.format(type(pred)))
for i in range(pred.size(0)):
indexes = np.argsort(d... | 41 | 268 | 169 | 437 | import numpy as np
import torch
class CatePredictor(object):
def __init__(self, cfg, tops_type=[1, 3, 5]):
"""Create the empty array to count true positive(tp),
true negative(tn), false positive(fp) and false negative(fn).
Args:
class_num : number of classes in the datase... | import numpy as np
import torch
class CatePredictor(object):
def __init__(self, cfg, tops_type=[1, 3, 5]):
"""Create the empty array to count true positive(tp),
true negative(tn), false positive(fp) and false negative(fn).
Args:
class_num : number of classes in the datase... |
38,934 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/core/evaluation/cate_predict_eval.py | 46,47 | 5,89 | collect_result | CateCalculator | 47,61 | 47,61 | class CateCalculator(object):
"""Calculate Category prediction top-k recall rate
"""
def __init__(self, cfg, topns=[1, 3]):
self.collector = dict()
self.num_cate = cfg.category_num
self.topns = topns
# true positive
for topi in topns:
self.collector['top%... | class CateCalculator(object):
"""Calculate Category prediction top-k recall rate
"""
def __init__(self, cfg, topns=[1, 3]):
self.collector = dict()
self.num_cate = cfg.category_num
self.topns = topns
# true positive
for topi in topns:
self.collector['top%... | if isinstance(pred, torch.Tensor):
data = pred.data.cpu().numpy()
elif isinstance(pred, np.ndarray):
data = pred
else:
raise TypeError('type {} cannot be calculated.'.format(type(pred)))
for i in range(pred.size(0)):
self.total += 1
... | if isinstance(pred, torch.Tensor):
data = pred.data.cpu().numpy()
elif isinstance(pred, np.ndarray):
data = pred
else:
raise TypeError('type {} cannot be calculated.'.format(type(pred)))
for i in range(pred.size(0)):
self.total += 1
... | 41 | 822 | 162 | 984 | import numpy as np
import torch
class CateCalculator(object):
"""Calculate Category prediction top-k recall rate
"""
def __init__(self, cfg, topns=[1, 3]):
self.collector = dict()
self.num_cate = cfg.category_num
self.topns = topns
# true positive
for topi in topns... | import numpy as np
import torch
class CateCalculator(object):
"""Calculate Category prediction top-k recall rate
"""
def __init__(self, cfg, topns=[1, 3]):
self.collector = dict()
self.num_cate = cfg.category_num
self.topns = topns
# true positive
for topi in topns... |
38,935 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/core/evaluation/retrieval_demo.py | 28,29 | 7,41 | show_retrieved_images | ClothesRetriever | 29,41 | 29,41 | class ClothesRetriever(object):
def __init__(self,
gallery_im_fn,
data_dir,
img_path,
topks=[5],
extract_feature=False):
self.topks = topks
self.data_dir = data_dir
self.img_path = img_path
self.gal... | class ClothesRetriever(object):
def __init__(self,
gallery_im_fn,
data_dir,
img_path,
topks=[5],
extract_feature=False):
self.topks = topks
self.data_dir = data_dir
self.img_path = img_path
self.gal... | query_dist = []
for i, feat in enumerate(gallery_embeds):
cosine_dist = cosine(
feat.reshape(1, -1), query_feat.reshape(1, -1))
query_dist.append(cosine_dist)
query_dist = np.array(query_dist)
order = np.argsort(query_dist)
for topk in se... | query_dist = []
for i, feat in enumerate(gallery_embeds):
cosine_dist = cosine(
feat.reshape(1, -1), query_feat.reshape(1, -1))
query_dist.append(cosine_dist)
query_dist = np.array(query_dist)
order = np.argsort(query_dist)
for topk in se... | 32 | 265 | 157 | 422 | import os
import numpy as np
from scipy.spatial.distance import cosine as cosine
class ClothesRetriever(object):
def __init__(self,
gallery_im_fn,
data_dir,
img_path,
topks=[5],
extract_feature=False):
self.topks = topk... | import os
import numpy as np
from scipy.spatial.distance import cosine as cosine
class ClothesRetriever(object):
def __init__(self,
gallery_im_fn,
data_dir,
img_path,
topks=[5],
extract_feature=False):
self.topks = topk... |
38,936 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/core/evaluation/retrieval_eval.py | 37,38 | 5,127 | load_dict | Evaluator | 38,44 | 38,44 | class Evaluator(object):
def __init__(self,
query_dict_fn,
gallery_dict_fn,
topks=[3, 5, 10, 20, 30, 50],
extract_feature=False):
"""Create the empty array to count
Args:
query_dict_fn(dict): the mapping of the index t... | class Evaluator(object):
def __init__(self,
query_dict_fn,
gallery_dict_fn,
topks=[3, 5, 10, 20, 30, 50],
extract_feature=False):
"""Create the empty array to count
Args:
query_dict_fn(dict): the mapping of the index t... | dic = dict()
rf = open(fn).readlines()
for i, line in enumerate(rf):
dic[i] = int(line.strip('\n'))
return dic
| dic = dict()
rf = open(fn).readlines()
for i, line in enumerate(rf):
dic[i] = int(line.strip('\n'))
return dic
| 16 | 1,257 | 57 | 1,314 | import numpy as np
from scipy.spatial.distance import cosine as cosine
class Evaluator(object):
def __init__(self,
query_dict_fn,
gallery_dict_fn,
topks=[3, 5, 10, 20, 30, 50],
extract_feature=False):
"""Create the empty array to count
... | import numpy as np
from scipy.spatial.distance import cosine as cosine
class Evaluator(object):
def __init__(self,
query_dict_fn,
gallery_dict_fn,
topks=[3, 5, 10, 20, 30, 50],
extract_feature=False):
"""Create the empty array to count
... |
38,938 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/datasets/builder.py | 6,7 | 1,19 | _concat_dataset | 7,13 | 7,13 | from ..utils import build_from_cfg
from .dataset_wrappers import ConcatDataset
from .registry import DATASETS
def _concat_dataset(cfgs):
FILL_FUNC_BODYdef build_dataset(cfg):
if isinstance(cfg, (list, tuple)):
dataset = _concat_dataset(cfg)
else:
dataset = build_from_cfg(cfg, DATASETS)
ret... | from ..utils import build_from_cfg
from .dataset_wrappers import ConcatDataset
from .registry import DATASETS
def _concat_dataset(cfgs):
FILL_FUNC_BODYdef build_dataset(cfg):
if isinstance(cfg, (list, tuple)):
dataset = _concat_dataset(cfg)
else:
dataset = build_from_cfg(cfg, DATASETS)
ret... | datasets = []
for cfg in cfgs:
datasets.append(build_from_cfg(cfg, DATASETS))
return ConcatDataset(datasets)
| datasets = []
for cfg in cfgs:
datasets.append(build_from_cfg(cfg, DATASETS))
return ConcatDataset(datasets)
| 11 | 113 | 53 | 166 | from ..utils import build_from_cfg
from .dataset_wrappers import ConcatDataset
from .registry import DATASETS
def _concat_dataset(cfgs):
FILL_FUNC_BODYdef build_dataset(cfg):
if isinstance(cfg, (list, tuple)):
dataset = _concat_dataset(cfg)
else:
dataset = build_from_cfg(cfg, DATASETS)
ret... | from ..utils import build_from_cfg
from .dataset_wrappers import ConcatDataset
from .registry import DATASETS
def _concat_dataset(cfgs):
FILL_FUNC_BODYdef build_dataset(cfg):
if isinstance(cfg, (list, tuple)):
dataset = _concat_dataset(cfg)
else:
dataset = build_from_cfg(cfg, DATASETS)
ret... | |
38,939 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/datasets/loader/build_loader.py | 4,11 | 1,24 | build_dataloader | 11,24 | 11,24 | from torch.utils.data import DataLoader
def build_dataloader(dataset,
imgs_per_gpu,
workers_per_gpu,
num_gpus,
drop_last=False,
dist=False,
**kwargs):
FILL_FUNC_BODY | from torch.utils.data import DataLoader
def build_dataloader(dataset,
imgs_per_gpu,
workers_per_gpu,
num_gpus,
drop_last=False,
dist=False,
**kwargs):
FILL_FUNC_BODY | shuffle = kwargs.get('shuffle', True)
batch_size = num_gpus * imgs_per_gpu
num_workers = num_gpus * workers_per_gpu
data_loader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle,
num_workers=num_workers,
drop_last=drop_last,
pin_memory=False)
... | shuffle = kwargs.get('shuffle', True)
batch_size = num_gpus * imgs_per_gpu
num_workers = num_gpus * workers_per_gpu
data_loader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle,
num_workers=num_workers,
drop_last=drop_last,
pin_memory=False)
... | 25 | 77 | 132 | 209 | from torch.utils.data import DataLoader
def build_dataloader(dataset,
imgs_per_gpu,
workers_per_gpu,
num_gpus,
drop_last=False,
dist=False,
**kwargs):
FILL_FUNC_BODY | from torch.utils.data import DataLoader
def build_dataloader(dataset,
imgs_per_gpu,
workers_per_gpu,
num_gpus,
drop_last=False,
dist=False,
**kwargs):
FILL_FUNC_BODY | |
38,940 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/attr_cate_predictor/attr_predictor.py | 25,26 | 8,44 | forward_train | AttrPredictor | 26,30 | 26,30 | @ATTRPREDICTOR.register_module
class AttrPredictor(nn.Module):
def __init__(self,
inchannels,
outchannels,
loss_attr=dict(
type='BCEWithLogitsLoss',
ratio=1,
weight=None,
size_aver... | @ATTRPREDICTOR.register_module
class AttrPredictor(nn.Module):
def __init__(self,
inchannels,
outchannels,
loss_attr=dict(
type='BCEWithLogitsLoss',
ratio=1,
weight=None,
size_aver... | attr_pred = self.linear_attr(x)
loss_attr = self.loss_attr(attr_pred, attr)
return loss_attr
| attr_pred = self.linear_attr(x)
loss_attr = self.loss_attr(attr_pred, attr)
return loss_attr
| 9 | 333 | 43 | 376 | import torch
import torch.nn as nn
from ..builder import build_loss
from ..registry import ATTRPREDICTOR
@ATTRPREDICTOR.register_module
class AttrPredictor(nn.Module):
def __init__(self,
inchannels,
outchannels,
loss_attr=dict(
type='BCEWit... | import torch
import torch.nn as nn
from ..builder import build_loss
from ..registry import ATTRPREDICTOR
@ATTRPREDICTOR.register_module
class AttrPredictor(nn.Module):
def __init__(self,
inchannels,
outchannels,
loss_attr=dict(
type='BCEWit... |
38,941 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/attr_cate_predictor/cate_predictor.py | 30,31 | 8,44 | forward_test | CatePredictor | 31,34 | 31,34 | @CATEPREDICTOR.register_module
class CatePredictor(nn.Module):
def __init__(self,
inchannels,
outchannels,
loss_cate=dict(
type='CELoss',
ratio=1,
weight=None,
size_average=None,
... | @CATEPREDICTOR.register_module
class CatePredictor(nn.Module):
def __init__(self,
inchannels,
outchannels,
loss_cate=dict(
type='CELoss',
ratio=1,
weight=None,
size_average=None,
... | cate_pred = torch.sigmoid(self.linear_cate(x))
return cate_pred
| cate_pred = torch.sigmoid(self.linear_cate(x))
return cate_pred
| 5 | 359 | 34 | 393 | import torch
import torch.nn as nn
from ..builder import build_loss
from ..registry import CATEPREDICTOR
@CATEPREDICTOR.register_module
class CatePredictor(nn.Module):
def __init__(self,
inchannels,
outchannels,
loss_cate=dict(
type='CELoss... | import torch
import torch.nn as nn
from ..builder import build_loss
from ..registry import CATEPREDICTOR
@CATEPREDICTOR.register_module
class CatePredictor(nn.Module):
def __init__(self,
inchannels,
outchannels,
loss_cate=dict(
type='CELoss... |
38,942 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/concats/concat.py | 24,25 | 7,28 | init_weights | Concat | 25,28 | 25,28 | @CONCATS.register_module
class Concat(nn.Module):
def __init__(self, inchannels, outchannels):
super(Concat, self).__init__()
# concat global and local
self.fc_fusion = nn.Linear(inchannels, outchannels)
def forward(self, global_x, local_x=None):
if local_x is not None:
... | @CONCATS.register_module
class Concat(nn.Module):
def __init__(self, inchannels, outchannels):
super(Concat, self).__init__()
# concat global and local
self.fc_fusion = nn.Linear(inchannels, outchannels)
def forward(self, global_x, local_x=None):
if local_x is not None:
... | nn.init.xavier_uniform_(self.fc_fusion.weight)
if self.fc_fusion.bias is not None:
self.fc_fusion.bias.data.fill_(0.01)
| nn.init.xavier_uniform_(self.fc_fusion.weight)
if self.fc_fusion.bias is not None:
self.fc_fusion.bias.data.fill_(0.01)
| 7 | 174 | 61 | 235 | import torch
import torch.nn as nn
from ..registry import CONCATS
@CONCATS.register_module
class Concat(nn.Module):
def __init__(self, inchannels, outchannels):
super(Concat, self).__init__()
# concat global and local
self.fc_fusion = nn.Linear(inchannels, outchannels)
def forward(s... | import torch
import torch.nn as nn
from ..registry import CONCATS
@CONCATS.register_module
class Concat(nn.Module):
def __init__(self, inchannels, outchannels):
super(Concat, self).__init__()
# concat global and local
self.fc_fusion = nn.Linear(inchannels, outchannels)
def forward(s... |
38,944 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/embed_extractor/embed_extract.py | 68,69 | 7,76 | init_weights | EmbedExtractor | 69,76 | 69,76 | @EMBEDEXTRACTOR.register_module
class EmbedExtractor(nn.Module):
def __init__(self,
inchannels,
inter_channels,
loss_id=dict(
type='CELoss',
ratio=1,
weight=None,
size_average=None... | @EMBEDEXTRACTOR.register_module
class EmbedExtractor(nn.Module):
def __init__(self,
inchannels,
inter_channels,
loss_id=dict(
type='CELoss',
ratio=1,
weight=None,
size_average=None... | nn.init.xavier_uniform_(self.embed_linear.weight)
if self.embed_linear.bias is not None:
self.embed_linear.bias.data.fill_(0.01)
nn.init.xavier_uniform_(self.id_linear.weight)
if self.id_linear.bias is not None:
self.id_linear.bias.data.fill_(0.01)
| nn.init.xavier_uniform_(self.embed_linear.weight)
if self.embed_linear.bias is not None:
self.embed_linear.bias.data.fill_(0.01)
nn.init.xavier_uniform_(self.id_linear.weight)
if self.id_linear.bias is not None:
self.id_linear.bias.data.fill_(0.01)
| 14 | 635 | 118 | 753 | import torch.nn as nn
from ..builder import build_loss
from ..registry import EMBEDEXTRACTOR
@EMBEDEXTRACTOR.register_module
class EmbedExtractor(nn.Module):
def __init__(self,
inchannels,
inter_channels,
loss_id=dict(
type='CELoss',
... | import torch.nn as nn
from ..builder import build_loss
from ..registry import EMBEDEXTRACTOR
@EMBEDEXTRACTOR.register_module
class EmbedExtractor(nn.Module):
def __init__(self,
inchannels,
inter_channels,
loss_id=dict(
type='CELoss',
... |
38,945 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/fashion_recommender/base.py | 43,44 | 7,47 | init_weights | BaseFashionRecommender | 44,47 | 44,47 | class BaseFashionRecommender(nn.Module):
''' Base class for fashion recommender'''
__metaclass__ = ABCMeta
def __init__(self):
super(BaseFashionRecommender, self).__init__()
@abstractmethod
def forward_test(self, imgs):
pass
@abstractmethod
def forward_train(self, img, tex... | class BaseFashionRecommender(nn.Module):
''' Base class for fashion recommender'''
__metaclass__ = ABCMeta
def __init__(self):
super(BaseFashionRecommender, self).__init__()
@abstractmethod
def forward_test(self, imgs):
pass
@abstractmethod
def forward_train(self, img, tex... | if pretrained is not None:
logger = logging.getLogger()
logger.info('load model from: {}'.format(pretrained))
| if pretrained is not None:
logger = logging.getLogger()
logger.info('load model from: {}'.format(pretrained))
| 12 | 334 | 38 | 372 | import logging
from abc import ABCMeta, abstractmethod
import torch.nn as nn
class BaseFashionRecommender(nn.Module):
''' Base class for fashion recommender'''
__metaclass__ = ABCMeta
def __init__(self):
super(BaseFashionRecommender, self).__init__()
@abstractmethod
def forward_test(sel... | import logging
from abc import ABCMeta, abstractmethod
import torch.nn as nn
class BaseFashionRecommender(nn.Module):
''' Base class for fashion recommender'''
__metaclass__ = ABCMeta
def __init__(self):
super(BaseFashionRecommender, self).__init__()
@abstractmethod
def forward_test(sel... |
38,946 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/fashion_recommender/type_aware_recommend.py | 68,69 | 6,80 | forward_test | TypeAwareRecommender | 69,74 | 69,74 | @RECOMMENDER.register_module
class TypeAwareRecommender(BaseFashionRecommender):
def __init__(self,
backbone,
global_pool,
type_specific_net,
triplet_net,
loss_embed=dict(type='L2NormLoss', loss_weight=5e-4),
loss... | @RECOMMENDER.register_module
class TypeAwareRecommender(BaseFashionRecommender):
def __init__(self,
backbone,
global_pool,
type_specific_net,
triplet_net,
loss_embed=dict(type='L2NormLoss', loss_weight=5e-4),
loss... | embed = self.backbone(img)
embed = self.global_pool(embed)
type_aware_embed = self.type_specific_net(embed, return_loss=False)
return type_aware_embed
| embed = self.backbone(img)
embed = self.global_pool(embed)
type_aware_embed = self.type_specific_net(embed, return_loss=False)
return type_aware_embed
| 12 | 945 | 61 | 1,006 | from .. import builder
from ..registry import RECOMMENDER
from .base import BaseFashionRecommender
@RECOMMENDER.register_module
class TypeAwareRecommender(BaseFashionRecommender):
def __init__(self,
backbone,
global_pool,
type_specific_net,
trip... | from .. import builder
from ..registry import RECOMMENDER
from .base import BaseFashionRecommender
@RECOMMENDER.register_module
class TypeAwareRecommender(BaseFashionRecommender):
def __init__(self,
backbone,
global_pool,
type_specific_net,
trip... |
38,947 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/feature_extractor/feature_correlation.py | 13,14 | 7,25 | forward | FeatureCorrelation | 14,25 | 14,25 | @FEATURECORRELATION.register_module
class FeatureCorrelation(nn.Module):
def __init__(self):
super(FeatureCorrelation, self).__init__()
def forward(self, feat_a, feat_b):
FILL_FUNC_BODY | @FEATURECORRELATION.register_module
class FeatureCorrelation(nn.Module):
def __init__(self):
super(FeatureCorrelation, self).__init__()
def forward(self, feat_a, feat_b):
FILL_FUNC_BODY | bs, c, h, w = feat_a.size()
# reshape features for matrix multiplication
feat_a = feat_a.transpose(2, 3).contiguous().view(bs, c, h * w)
feat_b = feat_b.view(bs, c, h * w).transpose(1, 2)
# perform matrix multiplication
feat_mul = torch.bmm(feat_b, feat_a)
correl... | bs, c, h, w = feat_a.size()
# reshape features for matrix multiplication
feat_a = feat_a.transpose(2, 3).contiguous().view(bs, c, h * w)
feat_b = feat_b.view(bs, c, h * w).transpose(1, 2)
# perform matrix multiplication
feat_mul = torch.bmm(feat_b, feat_a)
correl... | 48 | 72 | 178 | 250 | import torch
import torch.nn as nn
from ..registry import FEATURECORRELATION
@FEATURECORRELATION.register_module
class FeatureCorrelation(nn.Module):
def __init__(self):
super(FeatureCorrelation, self).__init__()
def forward(self, feat_a, feat_b):
FILL_FUNC_BODY | import torch
import torch.nn as nn
from ..registry import FEATURECORRELATION
@FEATURECORRELATION.register_module
class FeatureCorrelation(nn.Module):
def __init__(self):
super(FeatureCorrelation, self).__init__()
def forward(self, feat_a, feat_b):
FILL_FUNC_BODY |
38,948 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/feature_extractor/feature_norm.py | 14,15 | 7,20 | forward | FeatureNorm | 15,20 | 15,20 | @FEATURENORM.register_module
class FeatureNorm(nn.Module):
def __init__(self, eps=1e-6):
super(FeatureNorm, self).__init__()
self.eps = eps
def forward(self, feature):
FILL_FUNC_BODY | @FEATURENORM.register_module
class FeatureNorm(nn.Module):
def __init__(self, eps=1e-6):
super(FeatureNorm, self).__init__()
self.eps = eps
def forward(self, feature):
FILL_FUNC_BODY | norm_feat = torch.sum(torch.pow(feature, 2), 1) + self.eps
norm_feat = torch.pow(norm_feat, 0.5).unsqueeze(1)
norm_feat = norm_feat.expand_as(feature)
norm_feat = torch.div(feature, norm_feat)
return norm_feat
| norm_feat = torch.sum(torch.pow(feature, 2), 1) + self.eps
norm_feat = torch.pow(norm_feat, 0.5).unsqueeze(1)
norm_feat = norm_feat.expand_as(feature)
norm_feat = torch.div(feature, norm_feat)
return norm_feat
| 20 | 77 | 107 | 184 | import torch
import torch.nn as nn
from ..registry import FEATURENORM
@FEATURENORM.register_module
class FeatureNorm(nn.Module):
def __init__(self, eps=1e-6):
super(FeatureNorm, self).__init__()
self.eps = eps
def forward(self, feature):
FILL_FUNC_BODY | import torch
import torch.nn as nn
from ..registry import FEATURENORM
@FEATURENORM.register_module
class FeatureNorm(nn.Module):
def __init__(self, eps=1e-6):
super(FeatureNorm, self).__init__()
self.eps = eps
def forward(self, feature):
FILL_FUNC_BODY |
38,949 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/geometric_matching/geometric_matching.py | 36,37 | 7,50 | forward | GeometricMatching | 37,47 | 37,47 | @GEOMETRICMATCHING.register_module
class GeometricMatching(nn.Module):
def __init__(self,
feature_extractor_a,
feature_extractor_b,
feature_norm,
feature_correlation,
feature_regression,
tps_warp,
... | @GEOMETRICMATCHING.register_module
class GeometricMatching(nn.Module):
def __init__(self,
feature_extractor_a,
feature_extractor_b,
feature_norm,
feature_correlation,
feature_regression,
tps_warp,
... | feat_a = self.feature_extractora_a(a)
feat_b = self.feature_extractora_b(b)
feat_a = self.feature_norm(feat_a)
feat_b = self.feature_norm(feat_b)
correlation = self.feature_correlation(feat_a, feat_b)
theta = self.feature_regression(correlation)
grid = self.tps_w... | feat_a = self.feature_extractora_a(a)
feat_b = self.feature_extractora_b(b)
feat_a = self.feature_norm(feat_a)
feat_b = self.feature_norm(feat_b)
correlation = self.feature_correlation(feat_a, feat_b)
theta = self.feature_regression(correlation)
grid = self.tps_w... | 25 | 355 | 138 | 493 | import torch.nn as nn
from .. import builder
from ..registry import GEOMETRICMATCHING
@GEOMETRICMATCHING.register_module
class GeometricMatching(nn.Module):
def __init__(self,
feature_extractor_a,
feature_extractor_b,
feature_norm,
feature_corr... | import torch.nn as nn
from .. import builder
from ..registry import GEOMETRICMATCHING
@GEOMETRICMATCHING.register_module
class GeometricMatching(nn.Module):
def __init__(self,
feature_extractor_a,
feature_extractor_b,
feature_norm,
feature_corr... |
38,950 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/global_pool/global_pool.py | 34,35 | 8,45 | init_weights | GlobalPooling | 35,45 | 35,45 | @GLOBALPOOLING.register_module
class GlobalPooling(nn.Module):
def __init__(self, inplanes, pool_plane, inter_channels, outchannels):
super(GlobalPooling, self).__init__()
self.avgpool = nn.AdaptiveAvgPool2d(inplanes)
inter_plane = inter_channels[0] * inplanes[0] * inplanes[1]
if l... | @GLOBALPOOLING.register_module
class GlobalPooling(nn.Module):
def __init__(self, inplanes, pool_plane, inter_channels, outchannels):
super(GlobalPooling, self).__init__()
self.avgpool = nn.AdaptiveAvgPool2d(inplanes)
inter_plane = inter_channels[0] * inplanes[0] * inplanes[1]
if l... | if isinstance(self.global_layers, nn.Linear):
nn.init.normal_(self.global_layers.weight, 0, 0.01)
if self.global_layers.bias is not None:
nn.init.constant_(self.global_layers.bias, 0)
elif isinstance(self.global_layers, nn.Sequential):
for m in self.gl... | if isinstance(self.global_layers, nn.Linear):
nn.init.normal_(self.global_layers.weight, 0, 0.01)
if self.global_layers.bias is not None:
nn.init.constant_(self.global_layers.bias, 0)
elif isinstance(self.global_layers, nn.Sequential):
for m in self.gl... | 34 | 331 | 182 | 513 | from __future__ import division
import torch.nn as nn
from ..registry import GLOBALPOOLING
@GLOBALPOOLING.register_module
class GlobalPooling(nn.Module):
def __init__(self, inplanes, pool_plane, inter_channels, outchannels):
super(GlobalPooling, self).__init__()
self.avgpool = nn.AdaptiveAvgPoo... | from __future__ import division
import torch.nn as nn
from ..registry import GLOBALPOOLING
@GLOBALPOOLING.register_module
class GlobalPooling(nn.Module):
def __init__(self, inplanes, pool_plane, inter_channels, outchannels):
super(GlobalPooling, self).__init__()
self.avgpool = nn.AdaptiveAvgPoo... |
38,951 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/landmark_detector/landmark_detector.py | 52,53 | 6,78 | simple_test | LandmarkDetector | 53,62 | 53,62 | @LANDMARKDETECTOR.register_module
class LandmarkDetector(BaseLandmarkDetector):
def __init__(self,
backbone,
global_pool,
landmark_feature_extractor,
visibility_classifier,
landmark_regression,
pretrained=None):
... | @LANDMARKDETECTOR.register_module
class LandmarkDetector(BaseLandmarkDetector):
def __init__(self,
backbone,
global_pool,
landmark_feature_extractor,
visibility_classifier,
landmark_regression,
pretrained=None):
... | x = x.unsqueeze(0)
x = self.backbone(x)
x = self.global_pool(x)
landmark_feat = self.landmark_feature_extractor(x)
pred_vis = self.visibility_classifier(landmark_feat, return_loss=False)
pred_lm = self.landmark_regression(
landmark_feat, pred_vis, return_loss=... | x = x.unsqueeze(0)
x = self.backbone(x)
x = self.global_pool(x)
landmark_feat = self.landmark_feature_extractor(x)
pred_vis = self.visibility_classifier(landmark_feat, return_loss=False)
pred_lm = self.landmark_regression(
landmark_feat, pred_vis, return_loss=... | 25 | 693 | 139 | 832 | from .. import builder
from ..registry import LANDMARKDETECTOR
from .base import BaseLandmarkDetector
@LANDMARKDETECTOR.register_module
class LandmarkDetector(BaseLandmarkDetector):
def __init__(self,
backbone,
global_pool,
landmark_feature_extractor,
... | from .. import builder
from ..registry import LANDMARKDETECTOR
from .base import BaseLandmarkDetector
@LANDMARKDETECTOR.register_module
class LandmarkDetector(BaseLandmarkDetector):
def __init__(self,
backbone,
global_pool,
landmark_feature_extractor,
... |
38,952 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/landmark_feature_extractor/landmark_feature_extract.py | 15,16 | 6,24 | forward | LandmarkFeatureExtractor | 16,20 | 16,20 | @LANDMARKFEATUREEXTRACTOR.register_module
class LandmarkFeatureExtractor(nn.Module):
def __init__(self, inchannels, feature_dim, landmarks):
super(LandmarkFeatureExtractor, self).__init__()
self.linear = nn.Linear(inchannels, landmarks * feature_dim)
self.landmarks = landmarks
self.... | @LANDMARKFEATUREEXTRACTOR.register_module
class LandmarkFeatureExtractor(nn.Module):
def __init__(self, inchannels, feature_dim, landmarks):
super(LandmarkFeatureExtractor, self).__init__()
self.linear = nn.Linear(inchannels, landmarks * feature_dim)
self.landmarks = landmarks
self.... | x = self.linear(x)
x = x.view(-1, self.landmarks, self.feature_dim)
return x
| x = self.linear(x)
x = x.view(-1, self.landmarks, self.feature_dim)
return x
| 10 | 183 | 40 | 223 | import torch.nn as nn
from ..registry import LANDMARKFEATUREEXTRACTOR
@LANDMARKFEATUREEXTRACTOR.register_module
class LandmarkFeatureExtractor(nn.Module):
def __init__(self, inchannels, feature_dim, landmarks):
super(LandmarkFeatureExtractor, self).__init__()
self.linear = nn.Linear(inchannels, ... | import torch.nn as nn
from ..registry import LANDMARKFEATUREEXTRACTOR
@LANDMARKFEATUREEXTRACTOR.register_module
class LandmarkFeatureExtractor(nn.Module):
def __init__(self, inchannels, feature_dim, landmarks):
super(LandmarkFeatureExtractor, self).__init__()
self.linear = nn.Linear(inchannels, ... |
38,953 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/landmark_regression/landmark_regression.py | 21,22 | 7,48 | forward_train | LandmarkRegression | 22,29 | 22,29 | @LANDMARKREGRESSION.register_module
class LandmarkRegression(nn.Module):
def __init__(self,
inchannels,
outchannels,
landmark_num,
loss_regress=dict(
type='MSELoss', ratio=0.0001, reduction='mean')):
super(LandmarkRegr... | @LANDMARKREGRESSION.register_module
class LandmarkRegression(nn.Module):
def __init__(self,
inchannels,
outchannels,
landmark_num,
loss_regress=dict(
type='MSELoss', ratio=0.0001, reduction='mean')):
super(LandmarkRegr... | pred_lm = self.linear(x).view(-1, self.landmark_num, 2)
pred_vis = pred_vis.view(-1, self.landmark_num, 1)
landmark = landmark.view(-1, self.landmark_num, 2)
vis = vis.view(-1, self.landmark_num, 1)
loss_regress = self.loss_regress(vis * pred_lm, vis * landmark)
return lo... | pred_lm = self.linear(x).view(-1, self.landmark_num, 2)
pred_vis = pred_vis.view(-1, self.landmark_num, 1)
landmark = landmark.view(-1, self.landmark_num, 2)
vis = vis.view(-1, self.landmark_num, 1)
loss_regress = self.loss_regress(vis * pred_lm, vis * landmark)
return lo... | 30 | 352 | 132 | 484 | import torch.nn as nn
from ..builder import build_loss
from ..registry import LANDMARKREGRESSION
@LANDMARKREGRESSION.register_module
class LandmarkRegression(nn.Module):
def __init__(self,
inchannels,
outchannels,
landmark_num,
loss_regress=dic... | import torch.nn as nn
from ..builder import build_loss
from ..registry import LANDMARKREGRESSION
@LANDMARKREGRESSION.register_module
class LandmarkRegression(nn.Module):
def __init__(self,
inchannels,
outchannels,
landmark_num,
loss_regress=dic... |
38,954 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/losses/bce_with_logit_loss.py | 18,19 | 7,22 | forward | BCEWithLogitsLoss | 19,22 | 19,22 | @LOSSES.register_module
class BCEWithLogitsLoss(nn.Module):
def __init__(self, ratio, weight, size_average, reduce, reduction):
super(BCEWithLogitsLoss, self).__init__()
self.weight = weight
self.reduce = reduce
self.reduction = reduction
self.ratio = ratio
def forward... | @LOSSES.register_module
class BCEWithLogitsLoss(nn.Module):
def __init__(self, ratio, weight, size_average, reduce, reduction):
super(BCEWithLogitsLoss, self).__init__()
self.weight = weight
self.reduce = reduce
self.reduction = reduction
self.ratio = ratio
def forward... | target = target.float()
return self.ratio * F.binary_cross_entropy_with_logits(
input, target, self.weight, reduction=self.reduction)
| target = target.float()
return self.ratio * F.binary_cross_entropy_with_logits(
input, target, self.weight, reduction=self.reduction)
| 11 | 117 | 49 | 166 | import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class BCEWithLogitsLoss(nn.Module):
def __init__(self, ratio, weight, size_average, reduce, reduction):
super(BCEWithLogitsLoss, self).__init__()
self.weight = weight
self.reduce =... | import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class BCEWithLogitsLoss(nn.Module):
def __init__(self, ratio, weight, size_average, reduce, reduction):
super(BCEWithLogitsLoss, self).__init__()
self.weight = weight
self.reduce =... |
38,955 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/losses/ce_loss.py | 23,24 | 7,39 | forward | CELoss | 32,39 | 24,39 | @LOSSES.register_module
class CELoss(nn.Module):
def __init__(self,
ratio=1,
weight=None,
size_average=None,
ignore_index=-100,
reduce=None,
reduction='mean'):
super(CELoss, self).__init__()
self.r... | @LOSSES.register_module
class CELoss(nn.Module):
def __init__(self,
ratio=1,
weight=None,
size_average=None,
ignore_index=-100,
reduce=None,
reduction='mean'):
super(CELoss, self).__init__()
self.r... | target = target.squeeze_()
return self.ratio * F.cross_entropy(
input,
target,
weight=self.weight,
ignore_index=self.ignore_index,
reduction=self.reduction)
| """
Calculate the cross-entropy loss
:param input(torch.Tensor): The prediction with shape (N, C),
C is the number of classes.
:param target(torch.Tensor): The learning label(N, 1) of
the prediction.
:return... | 12 | 232 | 69 | 301 | import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class CELoss(nn.Module):
def __init__(self,
ratio=1,
weight=None,
size_average=None,
ignore_index=-100,
reduce=None,
... | import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class CELoss(nn.Module):
def __init__(self,
ratio=1,
weight=None,
size_average=None,
ignore_index=-100,
reduce=None,
... |
38,956 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/losses/cosine_embed_loss.py | 19,20 | 7,26 | forward | CosineEmbeddingLoss | 20,26 | 20,26 | @LOSSES.register_module
class CosineEmbeddingLoss(nn.Module):
def __init__(self,
margin=0.,
size_average=None,
reduce=None,
reduction='mean'):
super(CosineEmbeddingLoss, self).__init__()
self.margin = margin
self.reduction ... | @LOSSES.register_module
class CosineEmbeddingLoss(nn.Module):
def __init__(self,
margin=0.,
size_average=None,
reduce=None,
reduction='mean'):
super(CosineEmbeddingLoss, self).__init__()
self.margin = margin
self.reduction ... | return F.cosine_embedding_loss(
input1,
input2,
target,
margin=self.margin,
reduction=self.reduction)
| return F.cosine_embedding_loss(
input1,
input2,
target,
margin=self.margin,
reduction=self.reduction)
| 7 | 122 | 50 | 172 | import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class CosineEmbeddingLoss(nn.Module):
def __init__(self,
margin=0.,
size_average=None,
reduce=None,
reduction='mean'):
super(Cos... | import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class CosineEmbeddingLoss(nn.Module):
def __init__(self,
margin=0.,
size_average=None,
reduce=None,
reduction='mean'):
super(Cos... |
38,957 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/losses/l1_loss.py | 16,17 | 7,18 | forward | L1Loss | 17,18 | 17,18 | @LOSSES.register_module
class L1Loss(nn.Module):
def __init__(self, size_average=None, reduce=None, reduction='mean'):
super(L1Loss, self).__init__()
self.size_average = size_average
self.reduce = reduce
self.reduction = reduction
def forward(self, input, target):
FILL_FUNC_BOD... | @LOSSES.register_module
class L1Loss(nn.Module):
def __init__(self, size_average=None, reduce=None, reduction='mean'):
super(L1Loss, self).__init__()
self.size_average = size_average
self.reduce = reduce
self.reduction = reduction
def forward(self, input, target):
FILL_FUNC_BOD... | return F.l1_loss(input, target, reduction=self.reduction)
| return F.l1_loss(input, target, reduction=self.reduction)
| 4 | 113 | 22 | 135 | import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class L1Loss(nn.Module):
def __init__(self, size_average=None, reduce=None, reduction='mean'):
super(L1Loss, self).__init__()
self.size_average = size_average
self.reduce = reduce
... | import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class L1Loss(nn.Module):
def __init__(self, size_average=None, reduce=None, reduction='mean'):
super(L1Loss, self).__init__()
self.size_average = size_average
self.reduce = reduce
... |
38,958 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/losses/loss_norm.py | 28,29 | 20,34 | forward | L1NormLoss | 29,34 | 29,34 | @LOSSES.register_module
class L1NormLoss(nn.Module):
def __init__(self, loss_weight=5e-4, average=True):
super(L1NormLoss, self).__init__()
self.loss_weight = loss_weight
self.average = average
def forward(self, x1, x2, x3, length):
FILL_FUNC_BODY | @LOSSES.register_module
class L1NormLoss(nn.Module):
def __init__(self, loss_weight=5e-4, average=True):
super(L1NormLoss, self).__init__()
self.loss_weight = loss_weight
self.average = average
def forward(self, x1, x2, x3, length):
FILL_FUNC_BODY | loss_norm = (x1 + x2 + x3) / 3
if self.average:
loss_norm = loss_norm / length
return self.loss_weight * loss_norm
| loss_norm = (x1 + x2 + x3) / 3
if self.average:
loss_norm = loss_norm / length
return self.loss_weight * loss_norm
| 20 | 108 | 56 | 164 | import numpy as np
import torch.nn as nn
from ..registry import LOSSES
@LOSSES.register_module
class L2NormLoss(nn.Module):
def __init__(self, loss_weight=5e-4):
super(L2NormLoss, self).__init__()
self.loss_weight = loss_weight
def forward(self, x1, x2, x3, length):
x_norm = (x1 + x... | import numpy as np
import torch.nn as nn
from ..registry import LOSSES
@LOSSES.register_module
class L2NormLoss(nn.Module):
def __init__(self, loss_weight=5e-4):
super(L2NormLoss, self).__init__()
self.loss_weight = loss_weight
def forward(self, x1, x2, x3, length):
x_norm = (x1 + x... |
38,959 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/losses/loss_norm.py | 14,15 | 7,20 | forward | L2NormLoss | 15,20 | 15,20 | @LOSSES.register_module
class L2NormLoss(nn.Module):
def __init__(self, loss_weight=5e-4):
super(L2NormLoss, self).__init__()
self.loss_weight = loss_weight
def forward(self, x1, x2, x3, length):
FILL_FUNC_BODY | @LOSSES.register_module
class L2NormLoss(nn.Module):
def __init__(self, loss_weight=5e-4):
super(L2NormLoss, self).__init__()
self.loss_weight = loss_weight
def forward(self, x1, x2, x3, length):
FILL_FUNC_BODY | x_norm = (x1 + x2 + x3) / 3
loss_norm = x_norm / np.sqrt(length)
return self.loss_weight * loss_norm
| x_norm = (x1 + x2 + x3) / 3
loss_norm = x_norm / np.sqrt(length)
return self.loss_weight * loss_norm
| 18 | 96 | 54 | 150 | import numpy as np
import torch.nn as nn
from ..registry import LOSSES
@LOSSES.register_module
class L2NormLoss(nn.Module):
def __init__(self, loss_weight=5e-4):
super(L2NormLoss, self).__init__()
self.loss_weight = loss_weight
def forward(self, x1, x2, x3, length):
FILL_FUNC_BODY@LOSSES.re... | import numpy as np
import torch.nn as nn
from ..registry import LOSSES
@LOSSES.register_module
class L2NormLoss(nn.Module):
def __init__(self, loss_weight=5e-4):
super(L2NormLoss, self).__init__()
self.loss_weight = loss_weight
def forward(self, x1, x2, x3, length):
FILL_FUNC_BODY@LOSSES.re... |
38,960 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/losses/margin_ranking_loss.py | 22,23 | 8,31 | forward | MarginRankingLoss | 23,31 | 23,31 | @LOSSES.register_module
class MarginRankingLoss(nn.Module):
def __init__(self,
margin=0.2,
loss_weight=5e-5,
size_average=None,
reduce=None,
reduction='mean'):
super(MarginRankingLoss, self).__init__()
self.margin ... | @LOSSES.register_module
class MarginRankingLoss(nn.Module):
def __init__(self,
margin=0.2,
loss_weight=5e-5,
size_average=None,
reduce=None,
reduction='mean'):
super(MarginRankingLoss, self).__init__()
self.margin ... | return self.loss_weight * F.margin_ranking_loss(
input1,
input2,
target,
margin=self.margin,
reduction=self.reduction)
| return self.loss_weight * F.margin_ranking_loss(
input1,
input2,
target,
margin=self.margin,
reduction=self.reduction)
| 9 | 145 | 59 | 204 | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class MarginRankingLoss(nn.Module):
def __init__(self,
margin=0.2,
loss_weight=5e-5,
size_average=None,
reduce=None,
... | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class MarginRankingLoss(nn.Module):
def __init__(self,
margin=0.2,
loss_weight=5e-5,
size_average=None,
reduce=None,
... |
38,961 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/losses/margin_ranking_loss.py | 39,40 | 31,45 | forward | SelectiveMarginLoss | 40,45 | 40,45 | @LOSSES.register_module
class SelectiveMarginLoss(nn.Module):
def __init__(self, loss_weight=5e-5, margin=0.2):
super(SelectiveMarginLoss, self).__init__()
self.margin = margin
self.loss_weight = loss_weight
def forward(self, pos_samples, neg_samples, has_sample):
FILL_FUNC_BODY | @LOSSES.register_module
class SelectiveMarginLoss(nn.Module):
def __init__(self, loss_weight=5e-5, margin=0.2):
super(SelectiveMarginLoss, self).__init__()
self.margin = margin
self.loss_weight = loss_weight
def forward(self, pos_samples, neg_samples, has_sample):
FILL_FUNC_BODY | margin_diff = torch.clamp(
(pos_samples - neg_samples) + self.margin, min=0, max=1e6)
num_sample = max(torch.sum(has_sample), 1)
return self.loss_weight * (
torch.sum(margin_diff * has_sample) / num_sample)
| margin_diff = torch.clamp(
(pos_samples - neg_samples) + self.margin, min=0, max=1e6)
num_sample = max(torch.sum(has_sample), 1)
return self.loss_weight * (
torch.sum(margin_diff * has_sample) / num_sample)
| 23 | 114 | 95 | 209 | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class MarginRankingLoss(nn.Module):
def __init__(self,
margin=0.2,
loss_weight=5e-5,
size_average=None,
reduce=None,
... | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class MarginRankingLoss(nn.Module):
def __init__(self,
margin=0.2,
loss_weight=5e-5,
size_average=None,
reduce=None,
... |
38,962 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/losses/mse_loss.py | 21,22 | 7,23 | forward | MSELoss | 22,23 | 22,23 | @LOSSES.register_module
class MSELoss(nn.Module):
def __init__(self,
ratio=1,
size_average=None,
reduce=None,
reduction='mean'):
super(MSELoss, self).__init__()
self.ratio = ratio
self.size_average = size_average
se... | @LOSSES.register_module
class MSELoss(nn.Module):
def __init__(self,
ratio=1,
size_average=None,
reduce=None,
reduction='mean'):
super(MSELoss, self).__init__()
self.ratio = ratio
self.size_average = size_average
se... | return self.ratio * F.mse_loss(input, target, reduction=self.reduction)
| return self.ratio * F.mse_loss(input, target, reduction=self.reduction)
| 6 | 139 | 26 | 165 | import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class MSELoss(nn.Module):
def __init__(self,
ratio=1,
size_average=None,
reduce=None,
reduction='mean'):
super(MSELoss, self).__... | import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class MSELoss(nn.Module):
def __init__(self,
ratio=1,
size_average=None,
reduce=None,
reduction='mean'):
super(MSELoss, self).__... |
38,963 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/losses/triplet_loss.py | 25,26 | 7,54 | forward | TripletLoss | 26,54 | 26,54 | @LOSSES.register_module
class TripletLoss(nn.Module):
def __init__(self,
method='cosine',
ratio=1,
margin=0.2,
use_sigmoid=False,
reduction='mean',
size_average=True):
super(TripletLoss, self).__init__()
... | @LOSSES.register_module
class TripletLoss(nn.Module):
def __init__(self,
method='cosine',
ratio=1,
margin=0.2,
use_sigmoid=False,
reduction='mean',
size_average=True):
super(TripletLoss, self).__init__()
... | if self.use_sigmoid:
anchor, pos, neg = F.sigmoid(anchor), F.sigmoid(pos), F.sigmoid(
neg)
if self.method == 'cosine': # cosine similarity loss
loss_pos = F.cosine_embedding_loss(
anchor,
pos,
triplet_pos_label,
... | if self.use_sigmoid:
anchor, pos, neg = F.sigmoid(anchor), F.sigmoid(pos), F.sigmoid(
neg)
if self.method == 'cosine': # cosine similarity loss
loss_pos = F.cosine_embedding_loss(
anchor,
pos,
triplet_pos_label,
... | 73 | 190 | 309 | 499 | import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class TripletLoss(nn.Module):
def __init__(self,
method='cosine',
ratio=1,
margin=0.2,
use_sigmoid=False,
reduction='me... | import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
@LOSSES.register_module
class TripletLoss(nn.Module):
def __init__(self,
method='cosine',
ratio=1,
margin=0.2,
use_sigmoid=False,
reduction='me... |
38,964 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/losses/vgg_loss.py | 53,54 | 42,64 | forward | VGGLoss | 54,64 | 54,64 | @LOSSES.register_module
class VGGLoss(nn.Module):
def __init__(self, layerids=None):
super(VGGLoss, self).__init__()
self.vgg = Vgg19()
self.vgg.cuda()
self.criterion = nn.L1Loss()
self.weights = [1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0]
self.layerids = layerids
... | @LOSSES.register_module
class VGGLoss(nn.Module):
def __init__(self, layerids=None):
super(VGGLoss, self).__init__()
self.vgg = Vgg19()
self.vgg.cuda()
self.criterion = nn.L1Loss()
self.weights = [1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0]
self.layerids = layerids
... | input_vgg = self.vgg(input)
target_vgg = self.vgg(target)
if self.layerids is None:
self.layerids = list(range(len(input_vgg)))
loss = 0.
for i in self.layerids:
loss += self.weights[i] * self.criterion(input_vgg[i],
... | input_vgg = self.vgg(input)
target_vgg = self.vgg(target)
if self.layerids is None:
self.layerids = list(range(len(input_vgg)))
loss = 0.
for i in self.layerids:
loss += self.weights[i] * self.criterion(input_vgg[i],
... | 28 | 164 | 125 | 289 | import torch.nn as nn
import torchvision
from ..registry import LOSSES
class Vgg19(nn.Module):
def __init__(self, requires_grad=False):
super(Vgg19, self).__init__()
vgg_pretrained_features = torchvision.models.vgg19(
pretrained=True).features
self.slice1 = nn.Sequential()
... | import torch.nn as nn
import torchvision
from ..registry import LOSSES
class Vgg19(nn.Module):
def __init__(self, requires_grad=False):
super(Vgg19, self).__init__()
vgg_pretrained_features = torchvision.models.vgg19(
pretrained=True).features
self.slice1 = nn.Sequential()
... |
38,965 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/losses/vgg_loss.py | 32,33 | 7,42 | forward | Vgg19 | 33,42 | 33,42 | class Vgg19(nn.Module):
def __init__(self, requires_grad=False):
super(Vgg19, self).__init__()
vgg_pretrained_features = torchvision.models.vgg19(
pretrained=True).features
self.slice1 = nn.Sequential()
self.slice2 = nn.Sequential()
self.slice3 = nn.Sequential()
... | class Vgg19(nn.Module):
def __init__(self, requires_grad=False):
super(Vgg19, self).__init__()
vgg_pretrained_features = torchvision.models.vgg19(
pretrained=True).features
self.slice1 = nn.Sequential()
self.slice2 = nn.Sequential()
self.slice3 = nn.Sequential()
... | h_relu1 = self.slice1(X)
h_relu2 = self.slice2(h_relu1)
h_relu3 = self.slice3(h_relu2)
h_relu4 = self.slice4(h_relu3)
h_relu5 = self.slice5(h_relu4)
out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5]
return out
| h_relu1 = self.slice1(X)
h_relu2 = self.slice2(h_relu1)
h_relu3 = self.slice3(h_relu2)
h_relu4 = self.slice4(h_relu3)
h_relu5 = self.slice5(h_relu4)
out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5]
return out
| 24 | 374 | 141 | 515 | import torch.nn as nn
import torchvision
from ..registry import LOSSES
class Vgg19(nn.Module):
def __init__(self, requires_grad=False):
super(Vgg19, self).__init__()
vgg_pretrained_features = torchvision.models.vgg19(
pretrained=True).features
self.slice1 = nn.Sequential()
... | import torch.nn as nn
import torchvision
from ..registry import LOSSES
class Vgg19(nn.Module):
def __init__(self, requires_grad=False):
super(Vgg19, self).__init__()
vgg_pretrained_features = torchvision.models.vgg19(
pretrained=True).features
self.slice1 = nn.Sequential()
... |
38,966 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/predictor/base.py | 26,27 | 7,52 | forward_test | BasePredictor | 27,33 | 27,33 | class BasePredictor(nn.Module):
''' Base class for attribute predictors'''
__metaclass__ = ABCMeta
def __init__(self):
super(BasePredictor, self).__init__()
@property
def with_roi_pool(self):
return hasattr(self, 'roi_pool') and self.roi_pool is not None
@abstractmethod
de... | class BasePredictor(nn.Module):
''' Base class for attribute predictors'''
__metaclass__ = ABCMeta
def __init__(self):
super(BasePredictor, self).__init__()
@property
def with_roi_pool(self):
return hasattr(self, 'roi_pool') and self.roi_pool is not None
@abstractmethod
de... | num_augs = len(img)
if num_augs == 1: # single image test
return self.simple_test(img[0], landmark[0])
else:
return self.aug_test(img, landmark)
| num_augs = len(img)
if num_augs == 1: # single image test
return self.simple_test(img[0], landmark[0])
else:
return self.aug_test(img, landmark)
| 18 | 336 | 69 | 405 | import logging
from abc import ABCMeta, abstractmethod
import torch.nn as nn
class BasePredictor(nn.Module):
''' Base class for attribute predictors'''
__metaclass__ = ABCMeta
def __init__(self):
super(BasePredictor, self).__init__()
@property
def with_roi_pool(self):
return has... | import logging
from abc import ABCMeta, abstractmethod
import torch.nn as nn
class BasePredictor(nn.Module):
''' Base class for attribute predictors'''
__metaclass__ = ABCMeta
def __init__(self):
super(BasePredictor, self).__init__()
@property
def with_roi_pool(self):
return has... |
38,967 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/predictor/roi_attr_cate_predictor.py | 59,60 | 6,78 | aug_test | RoIAttrCatePredictor | 61,71 | 60,71 | @PREDICTOR.register_module
class RoIAttrCatePredictor(BasePredictor):
def __init__(self,
backbone,
global_pool,
roi_pool,
concat,
attr_predictor,
cate_predictor,
pretrained=None):
super(Ro... | @PREDICTOR.register_module
class RoIAttrCatePredictor(BasePredictor):
def __init__(self,
backbone,
global_pool,
roi_pool,
concat,
attr_predictor,
cate_predictor,
pretrained=None):
super(Ro... | x = self.backbone(x)
global_x = self.global_pool(x)
global_x = global_x.view(global_x.size(0), -1)
local_x = self.roi_pool(x, landmark)
feat = self.concat(global_x, local_x)
attr_pred = self.attr_predictor(feat)
cate_pred = self.cate_predictor(feat)
retur... | """Test batch of images"""
x = self.backbone(x)
global_x = self.global_pool(x)
global_x = global_x.view(global_x.size(0), -1)
local_x = self.roi_pool(x, landmark)
feat = self.concat(global_x, local_x)
attr_pred = self.attr_predictor(feat)
cate_pred = self... | 27 | 694 | 139 | 833 | from .. import builder
from ..registry import PREDICTOR
from .base import BasePredictor
@PREDICTOR.register_module
class RoIAttrCatePredictor(BasePredictor):
def __init__(self,
backbone,
global_pool,
roi_pool,
concat,
attr_predi... | from .. import builder
from ..registry import PREDICTOR
from .base import BasePredictor
@PREDICTOR.register_module
class RoIAttrCatePredictor(BasePredictor):
def __init__(self,
backbone,
global_pool,
roi_pool,
concat,
attr_predi... |
38,968 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/predictor/roi_predictor.py | 28,29 | 6,72 | forward_train | RoIPredictor | 29,48 | 29,48 | @PREDICTOR.register_module
class RoIPredictor(BasePredictor):
def __init__(self,
backbone,
global_pool,
concat,
attr_predictor,
cate_predictor=None,
roi_pool=None,
pretrained=None):
super(... | @PREDICTOR.register_module
class RoIPredictor(BasePredictor):
def __init__(self,
backbone,
global_pool,
concat,
attr_predictor,
cate_predictor=None,
roi_pool=None,
pretrained=None):
super(... | # 1. conv layers extract global features
x = self.backbone(x)
# 2. global pooling
global_x = self.global_pool(x)
global_x = global_x.view(global_x.size(0), -1)
# 3. roi pooling
local_x = self.roi_pool(x, landmark)
# 4. concat
feat = self.concat(... | # 1. conv layers extract global features
x = self.backbone(x)
# 2. global pooling
global_x = self.global_pool(x)
global_x = global_x.view(global_x.size(0), -1)
# 3. roi pooling
local_x = self.roi_pool(x, landmark)
# 4. concat
feat = self.concat(... | 50 | 533 | 190 | 723 | from .. import builder
from ..registry import PREDICTOR
from .base import BasePredictor
@PREDICTOR.register_module
class RoIPredictor(BasePredictor):
def __init__(self,
backbone,
global_pool,
concat,
attr_predictor,
cate_predict... | from .. import builder
from ..registry import PREDICTOR
from .base import BasePredictor
@PREDICTOR.register_module
class RoIPredictor(BasePredictor):
def __init__(self,
backbone,
global_pool,
concat,
attr_predictor,
cate_predict... |
38,969 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/retriever/base.py | 38,50 | 7,61 | forward | BaseRetriever | 50,57 | 50,57 | class BaseRetriever(nn.Module):
''' Base class for fashion retriever'''
__metaclass__ = ABCMeta
def __init__(self):
super(BaseRetriever, self).__init__()
@property
def with_roi_pool(self):
return hasattr(self, 'roi_pool') and self.roi_pool is not None
@abstractmethod
def s... | class BaseRetriever(nn.Module):
''' Base class for fashion retriever'''
__metaclass__ = ABCMeta
def __init__(self):
super(BaseRetriever, self).__init__()
@property
def with_roi_pool(self):
return hasattr(self, 'roi_pool') and self.roi_pool is not None
@abstractmethod
def s... | if return_loss:
return self.forward_train(img, id, attr, pos, neg, landmark,
pos_lm, neg_lm, triplet_pos_label,
triplet_neg_label)
else:
return self.forward_test(img, landmark)
| if return_loss:
return self.forward_train(img, id, attr, pos, neg, landmark,
pos_lm, neg_lm, triplet_pos_label,
triplet_neg_label)
else:
return self.forward_test(img, landmark)
| 17 | 432 | 81 | 513 | import logging
from abc import ABCMeta, abstractmethod
import torch.nn as nn
class BaseRetriever(nn.Module):
''' Base class for fashion retriever'''
__metaclass__ = ABCMeta
def __init__(self):
super(BaseRetriever, self).__init__()
@property
def with_roi_pool(self):
return hasatt... | import logging
from abc import ABCMeta, abstractmethod
import torch.nn as nn
class BaseRetriever(nn.Module):
''' Base class for fashion retriever'''
__metaclass__ = ABCMeta
def __init__(self):
super(BaseRetriever, self).__init__()
@property
def with_roi_pool(self):
return hasatt... |
38,970 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/retriever/global_retriever.py | 33,44 | 6,93 | forward_train | GlobalRetriever | 44,73 | 44,73 | @RETRIEVER.register_module
class GlobalRetriever(BaseRetriever):
def __init__(self,
backbone,
global_pool,
embed_extractor,
attr_predictor=None,
pretrained=None):
super(GlobalRetriever, self).__init__()
self.backb... | @RETRIEVER.register_module
class GlobalRetriever(BaseRetriever):
def __init__(self,
backbone,
global_pool,
embed_extractor,
attr_predictor=None,
pretrained=None):
super(GlobalRetriever, self).__init__()
self.backb... |
losses = dict()
# extract features
anchor_feat = self.extract_feat(anchor)
if pos is not None:
pos_feat = self.extract_feat(pos)
neg_feat = self.extract_feat(neg)
losses['loss_id'] = self.embed_extractor(
anchor_feat,
... |
losses = dict()
# extract features
anchor_feat = self.extract_feat(anchor)
if pos is not None:
pos_feat = self.extract_feat(pos)
neg_feat = self.extract_feat(neg)
losses['loss_id'] = self.embed_extractor(
anchor_feat,
... | 51 | 573 | 283 | 856 | from .. import builder
from ..registry import RETRIEVER
from .base import BaseRetriever
@RETRIEVER.register_module
class GlobalRetriever(BaseRetriever):
def __init__(self,
backbone,
global_pool,
embed_extractor,
attr_predictor=None,
... | from .. import builder
from ..registry import RETRIEVER
from .base import BaseRetriever
@RETRIEVER.register_module
class GlobalRetriever(BaseRetriever):
def __init__(self,
backbone,
global_pool,
embed_extractor,
attr_predictor=None,
... |
38,971 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/retriever/roi_retriever.py | 50,61 | 6,117 | forward_train | RoIRetriever | 61,90 | 61,90 | @RETRIEVER.register_module
class RoIRetriever(BaseRetriever):
def __init__(self,
backbone,
global_pool,
roi_pool,
concat,
embed_extractor,
attr_predictor=None,
pretrained=None):
super(RoIR... | @RETRIEVER.register_module
class RoIRetriever(BaseRetriever):
def __init__(self,
backbone,
global_pool,
roi_pool,
concat,
embed_extractor,
attr_predictor=None,
pretrained=None):
super(RoIR... |
losses = dict()
# extract features
anchor_feat = self.extract_feat(anchor, anchor_lm)
if pos is not None:
pos_feat = self.extract_feat(pos, pos_lm)
neg_feat = self.extract_feat(neg, neg_lm)
losses['loss_id'] = self.embed_extractor(
... |
losses = dict()
# extract features
anchor_feat = self.extract_feat(anchor, anchor_lm)
if pos is not None:
pos_feat = self.extract_feat(pos, pos_lm)
neg_feat = self.extract_feat(neg, neg_lm)
losses['loss_id'] = self.embed_extractor(
... | 54 | 806 | 295 | 1,101 | from .. import builder
from ..registry import RETRIEVER
from .base import BaseRetriever
@RETRIEVER.register_module
class RoIRetriever(BaseRetriever):
def __init__(self,
backbone,
global_pool,
roi_pool,
concat,
embed_extractor,
... | from .. import builder
from ..registry import RETRIEVER
from .base import BaseRetriever
@RETRIEVER.register_module
class RoIRetriever(BaseRetriever):
def __init__(self,
backbone,
global_pool,
roi_pool,
concat,
embed_extractor,
... |
38,972 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/roi_pool/roi_pooling.py | 39,40 | 10,93 | forward | RoIPooling | 47,80 | 40,80 | @ROIPOOLING.register_module
class RoIPooling(nn.Module):
def __init__(self,
pool_plane,
inter_channels,
outchannels,
crop_size=7,
img_size=(224, 224),
num_lms=8,
roi_size=2):
super(RoIPool... | @ROIPOOLING.register_module
class RoIPooling(nn.Module):
def __init__(self,
pool_plane,
inter_channels,
outchannels,
crop_size=7,
img_size=(224, 224),
num_lms=8,
roi_size=2):
super(RoIPool... | batch_size = features.size(0)
# transfer landmark coordinates from original image to feature map
landmarks = landmarks / self.img_size * self.crop_size
landmarks = landmarks.view(batch_size, self.num_lms, 2)
ab = [np.array([[self.a, 0], [0, self.b]]) for _ in range(batch_size)]... | """batch-wise RoI pooling.
Args:
features(tensor): the feature maps to be pooled.
landmarks(tensor): crop the region of interest based on the
landmarks(bs, self.num_lms).
"""
batch_size = features.size(0)
# transfer landmark coordinates f... | 115 | 609 | 496 | 1,105 | from __future__ import division
import numpy as np
import torch
import torch.nn as nn
from ..registry import ROIPOOLING
@ROIPOOLING.register_module
class RoIPooling(nn.Module):
def __init__(self,
pool_plane,
inter_channels,
outchannels,
crop_s... | from __future__ import division
import numpy as np
import torch
import torch.nn as nn
from ..registry import ROIPOOLING
@ROIPOOLING.register_module
class RoIPooling(nn.Module):
def __init__(self,
pool_plane,
inter_channels,
outchannels,
crop_s... |
38,973 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/triplet_net/triplet_net.py | 23,24 | 12,43 | forward | EmbedBranch | 24,43 | 24,43 | class EmbedBranch(nn.Module):
def __init__(self, feat_dim, embedding_dim):
super(EmbedBranch, self).__init__()
self.fc1 = nn.Sequential(
nn.Linear(feat_dim, embedding_dim),
nn.BatchNorm1d(embedding_dim, eps=0.001, momentum=0.01),
nn.ReLU(inplace=True))
s... | class EmbedBranch(nn.Module):
def __init__(self, feat_dim, embedding_dim):
super(EmbedBranch, self).__init__()
self.fc1 = nn.Sequential(
nn.Linear(feat_dim, embedding_dim),
nn.BatchNorm1d(embedding_dim, eps=0.001, momentum=0.01),
nn.ReLU(inplace=True))
s... | x = self.fc1(x)
x = self.fc2(x)
# L2 normalize each feature vector
norm = torch.norm(x, p=2, dim=1) + 1e-10
norm.unsqueeze_(1)
x = x / norm.expand_as(x)
return x
# def init_weights(self):
# for m in self.fc1:
# if type(m) == nn.Linear:
... | x = self.fc1(x)
x = self.fc2(x)
# L2 normalize each feature vector
norm = torch.norm(x, p=2, dim=1) + 1e-10
norm.unsqueeze_(1)
x = x / norm.expand_as(x)
return x
# def init_weights(self):
# for m in self.fc1:
# if type(m) == nn.Linear:
... | 60 | 161 | 253 | 414 | from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from ..builder import build_loss
from ..registry import TRIPLETNET
class EmbedBranch(nn.Module):
def __init__(self, feat_dim, embedding_dim):
super(EmbedBranch, self)._... | from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from ..builder import build_loss
from ..registry import TRIPLETNET
class EmbedBranch(nn.Module):
def __init__(self, feat_dim, embedding_dim):
super(EmbedBranch, self)._... |
38,975 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/unet/unet_skip_connection_block.py | 82,83 | 7,87 | forward | UnetSkipConnectionBlock | 83,87 | 83,87 | @UNETSKIPCONNECTIONBLOCK.register_module
class UnetSkipConnectionBlock(nn.Module):
def __init__(self,
outer_nc,
inner_nc,
input_nc=None,
submodule=None,
outermost=False,
innermost=False,
norm_laye... | @UNETSKIPCONNECTIONBLOCK.register_module
class UnetSkipConnectionBlock(nn.Module):
def __init__(self,
outer_nc,
inner_nc,
input_nc=None,
submodule=None,
outermost=False,
innermost=False,
norm_laye... | if self.outermost:
return self.unet(x)
else:
return torch.cat([x, self.unet(x)], 1)
| if self.outermost:
return self.unet(x)
else:
return torch.cat([x, self.unet(x)], 1)
| 9 | 746 | 47 | 793 | import torch
import torch.nn as nn
from ..registry import UNETSKIPCONNECTIONBLOCK
@UNETSKIPCONNECTIONBLOCK.register_module
class UnetSkipConnectionBlock(nn.Module):
def __init__(self,
outer_nc,
inner_nc,
input_nc=None,
submodule=None,
... | import torch
import torch.nn as nn
from ..registry import UNETSKIPCONNECTIONBLOCK
@UNETSKIPCONNECTIONBLOCK.register_module
class UnetSkipConnectionBlock(nn.Module):
def __init__(self,
outer_nc,
inner_nc,
input_nc=None,
submodule=None,
... |
38,976 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/virtual_tryon/geometric_matching.py | 39,40 | 8,83 | forward_feature | GeometricMatching | 40,50 | 40,50 | @GEOMETRICMATCHING.register_module
class GeometricMatching(nn.Module):
def __init__(self,
feature_extractor_a,
feature_extractor_b,
feature_norm,
feature_correlation,
feature_regression,
tps_warp,
... | @GEOMETRICMATCHING.register_module
class GeometricMatching(nn.Module):
def __init__(self,
feature_extractor_a,
feature_extractor_b,
feature_norm,
feature_correlation,
feature_regression,
tps_warp,
... | feat_a = self.feature_extractora_a(a)
feat_b = self.feature_extractora_b(b)
feat_a = self.feature_norm(feat_a)
feat_b = self.feature_norm(feat_b)
correlation = self.feature_correlation(feat_a, feat_b)
theta = self.feature_regression(correlation)
grid = self.tps_w... | feat_a = self.feature_extractora_a(a)
feat_b = self.feature_extractora_b(b)
feat_a = self.feature_norm(feat_a)
feat_b = self.feature_norm(feat_b)
correlation = self.feature_correlation(feat_a, feat_b)
theta = self.feature_regression(correlation)
grid = self.tps_w... | 25 | 715 | 138 | 853 | import torch.nn as nn
import torch.nn.functional as F
from .. import builder
from ..registry import GEOMETRICMATCHING
@GEOMETRICMATCHING.register_module
class GeometricMatching(nn.Module):
def __init__(self,
feature_extractor_a,
feature_extractor_b,
feature_nor... | import torch.nn as nn
import torch.nn.functional as F
from .. import builder
from ..registry import GEOMETRICMATCHING
@GEOMETRICMATCHING.register_module
class GeometricMatching(nn.Module):
def __init__(self,
feature_extractor_a,
feature_extractor_b,
feature_nor... |
38,977 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/virtual_tryon/tryon.py | 117,118 | 8,120 | init_weights | Tryon | 118,120 | 118,120 | @TRYON.register_module
class Tryon(nn.Module):
def __init__(self,
ngf,
num_downs,
in_channels,
out_channels,
down_channels=(8, 8),
inter_channels=(8, 8),
up_channels=[[4, 8], [2, 4], [1, 2]],
... | @TRYON.register_module
class Tryon(nn.Module):
def __init__(self,
ngf,
num_downs,
in_channels,
out_channels,
down_channels=(8, 8),
inter_channels=(8, 8),
up_channels=[[4, 8], [2, 4], [1, 2]],
... | if pretrained is not None:
self.unet.load_state_dict(torch.load(pretrained))
| if pretrained is not None:
self.unet.load_state_dict(torch.load(pretrained))
| 6 | 1,200 | 32 | 1,232 | import torch
import torch.nn as nn
from .. import builder
from ..registry import TRYON
@TRYON.register_module
class Tryon(nn.Module):
def __init__(self,
ngf,
num_downs,
in_channels,
out_channels,
down_channels=(8, 8),
... | import torch
import torch.nn as nn
from .. import builder
from ..registry import TRYON
@TRYON.register_module
class Tryon(nn.Module):
def __init__(self,
ngf,
num_downs,
in_channels,
out_channels,
down_channels=(8, 8),
... |
38,978 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/models/visibility_classifier/visibility_classifier.py | 48,49 | 9,68 | forward_test | VisibilityClassifier | 49,58 | 49,58 | @VISIBILITYCLASSIFIER.register_module
class VisibilityClassifier(nn.Module):
def __init__(self,
inchannels,
outchannels,
landmark_num,
loss_vis=dict(
type='BCEWithLogitsLoss', ratio=1, reduction='none')):
super(Visibil... | @VISIBILITYCLASSIFIER.register_module
class VisibilityClassifier(nn.Module):
def __init__(self,
inchannels,
outchannels,
landmark_num,
loss_vis=dict(
type='BCEWithLogitsLoss', ratio=1, reduction='none')):
super(Visibil... | vis_pred_list = []
for i in range(self.landmark_num):
lm_feat = x[:, i, :]
vis_pred = F.sigmoid(
self.linear(lm_feat)) # landmark visibility (bs, 2)
vis_pred_list.append(vis_pred)
vis_pred_list = torch.stack(vis_pred_list).transpose(1, 0)[:, :... | vis_pred_list = []
for i in range(self.landmark_num):
lm_feat = x[:, i, :]
vis_pred = F.sigmoid(
self.linear(lm_feat)) # landmark visibility (bs, 2)
vis_pred_list.append(vis_pred)
vis_pred_list = torch.stack(vis_pred_list).transpose(1, 0)[:, :... | 30 | 620 | 138 | 758 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .. import builder
from ..registry import VISIBILITYCLASSIFIER
@VISIBILITYCLASSIFIER.register_module
class VisibilityClassifier(nn.Module):
def __init__(self,
inchannels,
outchannels,
landma... | import torch
import torch.nn as nn
import torch.nn.functional as F
from .. import builder
from ..registry import VISIBILITYCLASSIFIER
@VISIBILITYCLASSIFIER.register_module
class VisibilityClassifier(nn.Module):
def __init__(self,
inchannels,
outchannels,
landma... |
38,979 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/mmfashion/utils/checkpoint.py | 53,54 | 1,102 | load_state_dict | 67,102 | 54,102 | from __future__ import division
import os
from collections import OrderedDict
import torch
def save_checkpoint(cfg, epoch, model, optimizer):
if not os.path.exists(cfg.work_dir):
os.makedirs(cfg.work_dir)
ckpt_path = os.path.join(
cfg.work_dir, '%s_%s_epoch%d.pth.tar' % (cfg.arch, cfg.pooling... | from __future__ import division
import os
from collections import OrderedDict
import torch
def save_checkpoint(cfg, epoch, model, optimizer):
if not os.path.exists(cfg.work_dir):
os.makedirs(cfg.work_dir)
ckpt_path = os.path.join(
cfg.work_dir, '%s_%s_epoch%d.pth.tar' % (cfg.arch, cfg.pooling... | unexpected_keys = []
own_state = module.state_dict()
for name, param in state_dict.items():
if name not in own_state:
unexpected_keys.append(name)
continue
if isinstance(param, torch.nn.Parameter):
# backwards compatibility for serialized parameters
... | """Load state_dict to a module.
This method is modified from :meth:`torch.nn.Module.load_state_dict`.
Default value for ``strict`` is set to ``False`` and the message for
param mismatch will be shown even if strict is False.
Args:
module (Module): Module that receives the state_dict.
... | 107 | 756 | 382 | 1,138 | from __future__ import division
import os
from collections import OrderedDict
import torch
def save_checkpoint(cfg, epoch, model, optimizer):
if not os.path.exists(cfg.work_dir):
os.makedirs(cfg.work_dir)
ckpt_path = os.path.join(
cfg.work_dir, '%s_%s_epoch%d.pth.tar' % (cfg.arch, cfg.pooling... | from __future__ import division
import os
from collections import OrderedDict
import torch
def save_checkpoint(cfg, epoch, model, optimizer):
if not os.path.exists(cfg.work_dir):
os.makedirs(cfg.work_dir)
ckpt_path = os.path.join(
cfg.work_dir, '%s_%s_epoch%d.pth.tar' % (cfg.arch, cfg.pooling... | |
38,980 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmfashion/mmfashion/setup.py | 35,36 | 1,140 | parse_requirements | 49,109 | 36,109 | """Setup script.
"""
import os
import re
import sys
from setuptools import find_packages, setup
def readme():
"""Get readme.
Returns:
str: readme content string.
"""
with open('README.md') as fid:
content = fid.read()
return content
def get_version(version_file='mmfashion/versi... | """Setup script.
"""
import os
import re
import sys
from setuptools import find_packages, setup
def readme():
"""Get readme.
Returns:
str: readme content string.
"""
with open('README.md') as fid:
content = fid.read()
return content
def get_version(version_file='mmfashion/versi... | require_fpath = fname
def parse_line(line):
"""Parse information from a line in a requirements text file.
"""
if line.startswith('-r '):
# Allow specifying requirements in other files
target = line.split(' ')[1]
for info in parse_require_file(target):... | """Parse the package dependencies listed in a requirements file but strips
specific versioning information.
Args:
fname (str): path to requirements file.
with_version (bool, default=False): if True include version specs.
Returns:
List[str]: list of requirements items.
... | 191 | 694 | 662 | 1,356 | """Setup script.
"""
import os
import re
import sys
from setuptools import find_packages, setup
def readme():
"""Get readme.
Returns:
str: readme content string.
"""
with open('README.md') as fid:
content = fid.read()
return content
def get_version(version_file='mmfashion/versi... | """Setup script.
"""
import os
import re
import sys
from setuptools import find_packages, setup
def readme():
"""Get readme.
Returns:
str: readme content string.
"""
with open('README.md') as fid:
content = fid.read()
return content
def get_version(version_file='mmfashion/versi... | |
38,981 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/docs/en/stat.py | 24,25 | 1,116 | build_collections | 25,36 | 25,36 | #!/usr/bin/env python
import re
from collections import defaultdict
from pathlib import Path
from modelindex.load_model_index import load
MMSELFSUP_ROOT = Path(__file__).absolute().parents[2]
PAPERS_ROOT = Path('papers') # Path to save generated paper pages.
GITHUB_PREFIX = 'https://github.com/open-mmlab/mmselfsup/b... | #!/usr/bin/env python
import re
from collections import defaultdict
from pathlib import Path
from modelindex.load_model_index import load
MMSELFSUP_ROOT = Path(__file__).absolute().parents[2]
PAPERS_ROOT = Path('papers') # Path to save generated paper pages.
GITHUB_PREFIX = 'https://github.com/open-mmlab/mmselfsup/b... | col_by_name = {}
for col in model_index.collections:
setattr(col, 'models', [])
col_by_name[col.name] = col
for model in model_index.models:
col = col_by_name[model.in_collection]
col.models.append(model)
setattr(model, 'collection', col)
| col_by_name = {}
for col in model_index.collections:
setattr(col, 'models', [])
col_by_name[col.name] = col
for model in model_index.models:
col = col_by_name[model.in_collection]
col.models.append(model)
setattr(model, 'collection', col)
| 24 | 1,089 | 110 | 1,199 | #!/usr/bin/env python
import re
from collections import defaultdict
from pathlib import Path
from modelindex.load_model_index import load
MMSELFSUP_ROOT = Path(__file__).absolute().parents[2]
PAPERS_ROOT = Path('papers') # Path to save generated paper pages.
GITHUB_PREFIX = 'https://github.com/open-mmlab/mmselfsup/b... | #!/usr/bin/env python
import re
from collections import defaultdict
from pathlib import Path
from modelindex.load_model_index import load
MMSELFSUP_ROOT = Path(__file__).absolute().parents[2]
PAPERS_ROOT = Path('papers') # Path to save generated paper pages.
GITHUB_PREFIX = 'https://github.com/open-mmlab/mmselfsup/b... | |
38,982 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/docs/zh_cn/stat.py | 39,40 | 1,116 | count_papers | 40,85 | 40,85 | #!/usr/bin/env python
import re
from collections import defaultdict
from pathlib import Path
from modelindex.load_model_index import load
MMSELFSUP_ROOT = Path(__file__).absolute().parents[2]
PAPERS_ROOT = Path('papers') # Path to save generated paper pages.
GITHUB_PREFIX = 'https://github.com/open-mmlab/mmselfsup/b... | #!/usr/bin/env python
import re
from collections import defaultdict
from pathlib import Path
from modelindex.load_model_index import load
MMSELFSUP_ROOT = Path(__file__).absolute().parents[2]
PAPERS_ROOT = Path('papers') # Path to save generated paper pages.
GITHUB_PREFIX = 'https://github.com/open-mmlab/mmselfsup/b... | ckpt_dict = dict()
type_count = defaultdict(int)
paper_msgs = []
for model in model_index.models:
if model.collection.name in ckpt_dict.keys():
if model.weights:
ckpt_dict[model.collection.name] += 1
else:
ckpt_dict[model.collection.name] = 1
... | ckpt_dict = dict()
type_count = defaultdict(int)
paper_msgs = []
for model in model_index.models:
if model.collection.name in ckpt_dict.keys():
if model.weights:
ckpt_dict[model.collection.name] += 1
else:
ckpt_dict[model.collection.name] = 1
... | 107 | 688 | 547 | 1,235 | #!/usr/bin/env python
import re
from collections import defaultdict
from pathlib import Path
from modelindex.load_model_index import load
MMSELFSUP_ROOT = Path(__file__).absolute().parents[2]
PAPERS_ROOT = Path('papers') # Path to save generated paper pages.
GITHUB_PREFIX = 'https://github.com/open-mmlab/mmselfsup/b... | #!/usr/bin/env python
import re
from collections import defaultdict
from pathlib import Path
from modelindex.load_model_index import load
MMSELFSUP_ROOT = Path(__file__).absolute().parents[2]
PAPERS_ROOT = Path('papers') # Path to save generated paper pages.
GITHUB_PREFIX = 'https://github.com/open-mmlab/mmselfsup/b... | |
38,983 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/mmselfsup/datasets/builder.py | 5,6 | 1,8 | build_dataset | 7,8 | 6,8 | # Copyright (c) OpenMMLab. All rights reserved.
from mmselfsup.registry import DATASETS
def build_dataset(cfg):
FILL_FUNC_BODY | # Copyright (c) OpenMMLab. All rights reserved.
from mmselfsup.registry import DATASETS
def build_dataset(cfg):
"""Build dataset."""
FILL_FUNC_BODY | return DATASETS.build(cfg)
| """Build dataset."""
return DATASETS.build(cfg)
| 2 | 54 | 13 | 67 | # Copyright (c) OpenMMLab. All rights reserved.
from mmselfsup.registry import DATASETS
def build_dataset(cfg):
FILL_FUNC_BODY | # Copyright (c) OpenMMLab. All rights reserved.
from mmselfsup.registry import DATASETS
def build_dataset(cfg):
"""Build dataset."""
FILL_FUNC_BODY | |
38,984 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/mmselfsup/datasets/deepcluster_dataset.py | 45,46 | 9,71 | assign_labels | DeepClusterImageNet | 54,59 | 46,59 | @DATASETS.register_module()
class DeepClusterImageNet(ImageNet):
"""`ImageNet <http://www.image-net.org>`_ Dataset.
The dataset inherit ImageNet dataset from MMClassification as the
DeepCluster and Online Deep Clustering algorithm need to initialize
clustering labels and assign them during training.
... | @DATASETS.register_module()
class DeepClusterImageNet(ImageNet):
"""`ImageNet <http://www.image-net.org>`_ Dataset.
The dataset inherit ImageNet dataset from MMClassification as the
DeepCluster and Online Deep Clustering algorithm need to initialize
clustering labels and assign them during training.
... | assert len(self.clustering_labels) == len(labels), (
f'Inconsistent length of assigned labels, '
f'{len(self.clustering_labels)} vs {len(labels)}')
self.clustering_labels = labels[:]
| """Assign new labels to `self.clustering_labels`.
Args:
labels (list): The new labels.
Returns:
None
"""
assert len(self.clustering_labels) == len(labels), (
f'Inconsistent length of assigned labels, '
f'{len(self.clustering_label... | 17 | 589 | 72 | 661 | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Any, Optional, Union
from mmcls.datasets import ImageNet
from mmselfsup.registry import DATASETS
@DATASETS.register_module()
class DeepClusterImageNet(ImageNet):
"""`ImageNet <http://www.image-net.org>`_ Dataset.
The dataset inherit ImageNe... | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Any, Optional, Union
from mmcls.datasets import ImageNet
from mmselfsup.registry import DATASETS
@DATASETS.register_module()
class DeepClusterImageNet(ImageNet):
"""`ImageNet <http://www.image-net.org>`_ Dataset.
The dataset inherit ImageNe... |
38,985 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/mmselfsup/models/builder.py | 17,18 | 1,40 | build_backbone | 19,22 | 18,22 | # Copyright (c) OpenMMLab. All rights reserved.
from mmselfsup.registry import MODELS
ALGORITHMS = MODELS
BACKBONES = MODELS
NECKS = MODELS
HEADS = MODELS
LOSSES = MODELS
MEMORIES = MODELS
def build_algorithm(cfg):
"""Build algorithm."""
return ALGORITHMS.build(cfg)
def build_backbone(cfg):
FILL_FUNC_BODYd... | # Copyright (c) OpenMMLab. All rights reserved.
from mmselfsup.registry import MODELS
ALGORITHMS = MODELS
BACKBONES = MODELS
NECKS = MODELS
HEADS = MODELS
LOSSES = MODELS
MEMORIES = MODELS
def build_algorithm(cfg):
"""Build algorithm."""
return ALGORITHMS.build(cfg)
def build_backbone(cfg):
"""Build ba... | return BACKBONES.build(cfg)
| """Build backbone."""
return BACKBONES.build(cfg)
| 2 | 245 | 18 | 263 | # Copyright (c) OpenMMLab. All rights reserved.
from mmselfsup.registry import MODELS
ALGORITHMS = MODELS
BACKBONES = MODELS
NECKS = MODELS
HEADS = MODELS
LOSSES = MODELS
MEMORIES = MODELS
def build_algorithm(cfg):
"""Build algorithm."""
return ALGORITHMS.build(cfg)
def build_backbone(cfg):
FILL_FUNC_BODYd... | # Copyright (c) OpenMMLab. All rights reserved.
from mmselfsup.registry import MODELS
ALGORITHMS = MODELS
BACKBONES = MODELS
NECKS = MODELS
HEADS = MODELS
LOSSES = MODELS
MEMORIES = MODELS
def build_algorithm(cfg):
"""Build algorithm."""
return ALGORITHMS.build(cfg)
def build_backbone(cfg):
"""Build ba... | |
38,986 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/mmselfsup/version.py | 6,7 | 1,30 | parse_version_info | 16,27 | 7,27 | # Copyright (c) Open-MMLab. All rights reserved.
__version__ = '1.0.0'
def parse_version_info(version_str):
FILL_FUNC_BODYversion_info = parse_version_info(__version__)
__all__ = ['__version__', 'version_info', 'parse_version_info']
| # Copyright (c) Open-MMLab. All rights reserved.
__version__ = '1.0.0'
def parse_version_info(version_str):
"""Parse a version string into a tuple.
Args:
version_str (str): The version string.
Returns:
tuple[int | str]: The version info, e.g., "1.3.0" is parsed into
(1, 3, 0... | version_info = []
for x in version_str.split('.'):
if x.isdigit():
version_info.append(int(x))
elif x.find('rc') != -1:
patch_version = x.split('rc')
version_info.append(int(patch_version[0]))
version_info.append(f'rc{patch_version[1]}')
return... | """Parse a version string into a tuple.
Args:
version_str (str): The version string.
Returns:
tuple[int | str]: The version info, e.g., "1.3.0" is parsed into
(1, 3, 0), and "2.0.0rc1" is parsed into (2, 0, 0, 'rc1').
"""
version_info = []
for x in version_str.split... | 21 | 189 | 124 | 313 | # Copyright (c) Open-MMLab. All rights reserved.
__version__ = '1.0.0'
def parse_version_info(version_str):
FILL_FUNC_BODYversion_info = parse_version_info(__version__)
__all__ = ['__version__', 'version_info', 'parse_version_info']
| # Copyright (c) Open-MMLab. All rights reserved.
__version__ = '1.0.0'
def parse_version_info(version_str):
"""Parse a version string into a tuple.
Args:
version_str (str): The version string.
Returns:
tuple[int | str]: The version info, e.g., "1.3.0" is parsed into
(1, 3, 0... | |
38,987 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/setup.py | 100,101 | 1,192 | add_mim_extension | 107,160 | 101,160 | #!/usr/bin/env python
# Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
import shutil
import sys
import warnings
from setuptools import find_packages, setup
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content
def get_version():... | #!/usr/bin/env python
# Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
import shutil
import sys
import warnings
from setuptools import find_packages, setup
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content
def get_version():... |
# parse installment mode
if 'develop' in sys.argv:
# installed by `pip install -e .`
mode = 'symlink'
elif 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
# installed by `pip install .`
# or create source distribution by `python setup.py sdist`
mode = 'copy'
el... | """Add extra files that are required to support MIM into the package.
These files will be added by creating a symlink to the originals if the
package is installed in `editable` mode (e.g. pip install -e .), or by
copying from the originals otherwise.
"""
# parse installment mode
if 'develo... | 168 | 1,393 | 627 | 2,020 | #!/usr/bin/env python
# Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
import shutil
import sys
import warnings
from setuptools import find_packages, setup
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content
def get_version():... | #!/usr/bin/env python
# Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
import shutil
import sys
import warnings
from setuptools import find_packages, setup
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content
def get_version():... | |
38,988 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/tools/benchmarks/classification/svm_voc07/tools/aggregate_low_shot_svm_stats.py | 29,30 | 1,117 | aggregate_stats | 36,90 | 30,90 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
from __future__ import (absolute_import, d... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
from __future__ import (absolute_import, d... | k_values = [int(val) for val in opts.k_values.split(',')]
sample_inds = [int(val) for val in opts.sample_inds.split(',')]
output_mean, output_max, output_min, output_std = [], [], [], []
for k_idx in range(len(k_values)):
k_low = k_values[k_idx]
k_val_output = []
for inds in ran... | """Aggregate the stats over various independent samples for low-shot svm
training.
Stats computed: mean, max, min, std. Relevant transfer tasks: Low-shot
Image Classification VOC07 and Places205 low shot samples.
"""
k_values = [int(val) for val in opts.k_values.split(',')]
sample_inds = [i... | 172 | 558 | 985 | 1,543 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
from __future__ import (absolute_import, d... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
from __future__ import (absolute_import, d... | |
38,990 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/tools/benchmarks/classification/svm_voc07/tools/test_svm.py | 52,53 | 1,152 | test_svm | 54,110 | 53,110 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""SVM test for image classification.
Rel... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""SVM test for image classification.
Rel... | assert osp.exists(opts.data_file), 'Data file not found. Abort!'
json_predictions, img_ids, cls_names = {}, [], []
if opts.generate_json:
img_ids, cls_names = svm_helper.load_json(opts.json_targets)
features, targets = svm_helper.load_input_data(opts.data_file,
... | """Test SVM model."""
assert osp.exists(opts.data_file), 'Data file not found. Abort!'
json_predictions, img_ids, cls_names = {}, [], []
if opts.generate_json:
img_ids, cls_names = svm_helper.load_json(opts.json_targets)
features, targets = svm_helper.load_input_data(opts.data_file,
... | 217 | 945 | 883 | 1,828 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""SVM test for image classification.
Rel... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""SVM test for image classification.
Rel... | |
38,992 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/tools/benchmarks/classification/svm_voc07/tools/train_svm_kfold.py | 101,102 | 1,144 | main | 102,142 | 102,142 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""SVM training using 3-fold cross-validat... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""SVM training using 3-fold cross-validat... | parser = argparse.ArgumentParser(description='SVM model training')
parser.add_argument(
'--data_file',
type=str,
default=None,
help='Numpy file containing image features')
parser.add_argument(
'--targets_data_file',
type=str,
default=None,
help... | parser = argparse.ArgumentParser(description='SVM model training')
parser.add_argument(
'--data_file',
type=str,
default=None,
help='Numpy file containing image features')
parser.add_argument(
'--targets_data_file',
type=str,
default=None,
help... | 78 | 1,104 | 376 | 1,480 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""SVM training using 3-fold cross-validat... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""SVM training using 3-fold cross-validat... | |
38,993 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/tools/benchmarks/classification/svm_voc07/tools/train_svm_kfold_parallel.py | 29,30 | 1,148 | task | 31,59 | 30,59 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""SVM training using 3-fold cross-validat... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""SVM training using 3-fold cross-validat... | out_file, ap_out_file = svm_helper.get_svm_train_output_files(
cls, cost, opts.output_path)
if not (osp.exists(out_file) and osp.exists(ap_out_file)):
clf = LinearSVC(
C=cost,
class_weight={
1: 2,
-1: 1
},
intercept_... | """The task function to train the model."""
out_file, ap_out_file = svm_helper.get_svm_train_output_files(
cls, cost, opts.output_path)
if not (osp.exists(out_file) and osp.exists(ap_out_file)):
clf = LinearSVC(
C=cost,
class_weight={
1: 2,
... | 61 | 1,069 | 368 | 1,437 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""SVM training using 3-fold cross-validat... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""SVM training using 3-fold cross-validat... | |
38,994 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/tools/benchmarks/classification/svm_voc07/tools/train_svm_low_shot.py | 33,34 | 1,124 | train_svm_low_shot | 35,85 | 34,85 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""Low Shot SVM training.
Relevant transf... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""Low Shot SVM training.
Relevant transf... | assert osp.exists(opts.data_file), 'Data file not found. Abort!'
if not osp.exists(opts.output_path):
os.makedirs(opts.output_path)
features, targets = svm_helper.load_input_data(opts.data_file,
opts.targets_data_file)
# normalize the features:... | """Train the svm low-shot model."""
assert osp.exists(opts.data_file), 'Data file not found. Abort!'
if not osp.exists(opts.output_path):
os.makedirs(opts.output_path)
features, targets = svm_helper.load_input_data(opts.data_file,
opts.targets_... | 121 | 639 | 615 | 1,254 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""Low Shot SVM training.
Relevant transf... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""Low Shot SVM training.
Relevant transf... | |
38,995 | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup | /home/hieuvd/dung_repo/raw/stars_02/open-mmlab_mmselfsup/mmselfsup/tools/benchmarks/classification/svm_voc07/tools/train_svm_low_shot_parallel.py | 61,62 | 1,139 | train_svm_low_shot | 63,100 | 62,100 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""Low Shot SVM training.
Relevant transf... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""Low Shot SVM training.
Relevant transf... | assert osp.exists(opts.data_file), 'Data file not found. Abort!'
if not osp.exists(opts.output_path):
os.makedirs(opts.output_path)
features, targets = svm_helper.load_input_data(opts.data_file,
opts.targets_data_file)
# normalize the features:... | """Train the svm low-shot model."""
assert osp.exists(opts.data_file), 'Data file not found. Abort!'
if not osp.exists(opts.output_path):
os.makedirs(opts.output_path)
features, targets = svm_helper.load_input_data(opts.data_file,
opts.targets_... | 108 | 899 | 446 | 1,345 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""Low Shot SVM training.
Relevant transf... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
###############################################################################
"""Low Shot SVM training.
Relevant transf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.