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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
31,020 | /home/hieuvd/dung_repo/raw/stars_02/Rayhane-mamah_Tacotron-2/Tacotron-2 | /home/hieuvd/dung_repo/raw/stars_02/Rayhane-mamah_Tacotron-2/Tacotron-2/tacotron/utils/text.py | 57,58 | 1,76 | _clean_text | 58,66 | 58,66 | import re
from . import cleaners
from .symbols import symbols
# Mappings from symbol to numeric ID and vice versa:
_symbol_to_id = {s: i for i, s in enumerate(symbols)}
_id_to_symbol = {i: s for i, s in enumerate(symbols)}
# Regular expression matching text enclosed in curly braces:
_curly_re = re.compile(r'(.*?)\{(... | import re
from . import cleaners
from .symbols import symbols
# Mappings from symbol to numeric ID and vice versa:
_symbol_to_id = {s: i for i, s in enumerate(symbols)}
_id_to_symbol = {i: s for i, s in enumerate(symbols)}
# Regular expression matching text enclosed in curly braces:
_curly_re = re.compile(r'(.*?)\{(... | for name in cleaner_names:
cleaner = getattr(cleaners, name)
if not cleaner:
raise Exception('Unknown cleaner: %s' % name)
text = cleaner(text)
return text
| for name in cleaner_names:
cleaner = getattr(cleaners, name)
if not cleaner:
raise Exception('Unknown cleaner: %s' % name)
text = cleaner(text)
return text
| 22 | 693 | 63 | 756 | import re
from . import cleaners
from .symbols import symbols
# Mappings from symbol to numeric ID and vice versa:
_symbol_to_id = {s: i for i, s in enumerate(symbols)}
_id_to_symbol = {i: s for i, s in enumerate(symbols)}
# Regular expression matching text enclosed in curly braces:
_curly_re = re.compile(r'(.*?)\{(... | import re
from . import cleaners
from .symbols import symbols
# Mappings from symbol to numeric ID and vice versa:
_symbol_to_id = {s: i for i, s in enumerate(symbols)}
_id_to_symbol = {i: s for i, s in enumerate(symbols)}
# Regular expression matching text enclosed in curly braces:
_curly_re = re.compile(r'(.*?)\{(... | |
31,024 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/pysot/datasets/anchor_target.py | 32,33 | 15,92 | select | AnchorTarget | 33,41 | 33,41 | class AnchorTarget:
def __init__(self,):
self.anchors = Anchors(cfg.ANCHOR.STRIDE,
cfg.ANCHOR.RATIOS,
cfg.ANCHOR.SCALES)
self.anchors.generate_all_anchors(im_c=cfg.TRAIN.SEARCH_SIZE//2,
size=cfg.... | class AnchorTarget:
def __init__(self,):
self.anchors = Anchors(cfg.ANCHOR.STRIDE,
cfg.ANCHOR.RATIOS,
cfg.ANCHOR.SCALES)
self.anchors.generate_all_anchors(im_c=cfg.TRAIN.SEARCH_SIZE//2,
size=cfg.... | num = position[0].shape[0]
if num <= keep_num:
return position, num
slt = np.arange(num)
np.random.shuffle(slt)
slt = slt[:keep_num]
return tuple(p[slt] for p in position), keep_num
| num = position[0].shape[0]
if num <= keep_num:
return position, num
slt = np.arange(num)
np.random.shuffle(slt)
slt = slt[:keep_num]
return tuple(p[slt] for p in position), keep_num
| 24 | 965 | 90 | 1,055 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from pysot.core.config import cfg
from pysot.utils.bbox import IoU, corner2center
from pysot.utils.an... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from pysot.core.config import cfg
from pysot.utils.bbox import IoU, corner2center
from pysot.utils.an... |
31,025 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/pysot/datasets/augmentation.py | 70,71 | 15,140 | _shift_scale_aug | Augmentation | 71,110 | 71,110 | class Augmentation:
def __init__(self, shift, scale, blur, flip, color):
self.shift = shift
self.scale = scale
self.blur = blur
self.flip = flip
self.color = color
self.rgbVar = np.array(
[[-0.55919361, 0.98062831, - 0.41940627],
[1.72091413,... | class Augmentation:
def __init__(self, shift, scale, blur, flip, color):
self.shift = shift
self.scale = scale
self.blur = blur
self.flip = flip
self.color = color
self.rgbVar = np.array(
[[-0.55919361, 0.98062831, - 0.41940627],
[1.72091413,... | im_h, im_w = image.shape[:2]
# adjust crop bounding box
crop_bbox_center = corner2center(crop_bbox)
if self.scale:
scale_x = (1.0 + Augmentation.random() * self.scale)
scale_y = (1.0 + Augmentation.random() * self.scale)
h, w = crop_bbox_center.h, cro... | im_h, im_w = image.shape[:2]
# adjust crop bounding box
crop_bbox_center = corner2center(crop_bbox)
if self.scale:
scale_x = (1.0 + Augmentation.random() * self.scale)
scale_y = (1.0 + Augmentation.random() * self.scale)
h, w = crop_bbox_center.h, cro... | 156 | 1,113 | 585 | 1,698 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import cv2
from pysot.utils.bbox import corner2center, \
Center, center2corner, Corner
clas... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import cv2
from pysot.utils.bbox import corner2center, \
Center, center2corner, Corner
clas... |
31,026 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/pysot/tracker/siamrpnlt_tracker.py | 19,20 | 14,111 | track | SiamRPNLTTracker | 26,111 | 20,111 | class SiamRPNLTTracker(SiamRPNTracker):
def __init__(self, model):
super(SiamRPNLTTracker, self).__init__(model)
self.longterm_state = False
def track(self, img):
FILL_FUNC_BODY | class SiamRPNLTTracker(SiamRPNTracker):
def __init__(self, model):
super(SiamRPNLTTracker, self).__init__(model)
self.longterm_state = False
def track(self, img):
"""
args:
img(np.ndarray): BGR image
return:
bbox(list):[x, y, width, height]
... | w_z = self.size[0] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)
h_z = self.size[1] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)
s_z = np.sqrt(w_z * h_z)
scale_z = cfg.TRACK.EXEMPLAR_SIZE / s_z
if self.longterm_state:
instance_size = cfg.TRACK.LOST_INSTANCE_SIZE
... | """
args:
img(np.ndarray): BGR image
return:
bbox(list):[x, y, width, height]
"""
w_z = self.size[0] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)
h_z = self.size[1] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)
s_z = np.sqrt(w_z * h_z)
... | 302 | 118 | 1,217 | 1,335 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from pysot.core.config import cfg
from pysot.tracker.siamrpn_tracker import SiamRPNTracker
class Si... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from pysot.core.config import cfg
from pysot.tracker.siamrpn_tracker import SiamRPNTracker
class Si... |
31,027 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/pysot/tracker/tracker_builder.py | 20,21 | 1,22 | build_tracker | 21,22 | 21,22 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from pysot.core.config import cfg
from pysot.tracker.siamrpn_tracker import SiamRPNTracker
from pysot.tracker.siammask_tr... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from pysot.core.config import cfg
from pysot.tracker.siamrpn_tracker import SiamRPNTracker
from pysot.tracker.siammask_tr... | return TRACKS[cfg.TRACK.TYPE](model)
| return TRACKS[cfg.TRACK.TYPE](model)
| 2 | 215 | 17 | 232 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from pysot.core.config import cfg
from pysot.tracker.siamrpn_tracker import SiamRPNTracker
from pysot.tracker.siammask_tr... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from pysot.core.config import cfg
from pysot.tracker.siamrpn_tracker import SiamRPNTracker
from pysot.tracker.siammask_tr... | |
31,028 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/pysot/utils/anchor.py | 32,33 | 15,86 | generate_anchors | Anchors | 36,49 | 33,49 | class Anchors:
"""
This class generate anchors.
"""
def __init__(self, stride, ratios, scales, image_center=0, size=0):
self.stride = stride
self.ratios = ratios
self.scales = scales
self.image_center = image_center
self.size = size
self.anchor_num = len(... | class Anchors:
"""
This class generate anchors.
"""
def __init__(self, stride, ratios, scales, image_center=0, size=0):
self.stride = stride
self.ratios = ratios
self.scales = scales
self.image_center = image_center
self.size = size
self.anchor_num = len(... | self.anchors = np.zeros((self.anchor_num, 4), dtype=np.float32)
size = self.stride * self.stride
count = 0
for r in self.ratios:
ws = int(math.sqrt(size*1. / r))
hs = int(ws * r)
for s in self.scales:
w = ws * s
h = hs ... | """
generate anchors based on predefined configuration
"""
self.anchors = np.zeros((self.anchor_num, 4), dtype=np.float32)
size = self.stride * self.stride
count = 0
for r in self.ratios:
ws = int(math.sqrt(size*1. / r))
hs = int(ws * r)
... | 50 | 686 | 171 | 857 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import math
import numpy as np
from pysot.utils.bbox import corner2center, center2corner
class Anchors:
"""
T... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import math
import numpy as np
from pysot.utils.bbox import corner2center, center2corner
class Anchors:
"""
T... |
31,029 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/pysot/utils/bbox.py | 57,58 | 1,158 | IoU | 65,84 | 58,84 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import namedtuple
import numpy as np
Corner = namedtuple('Corner', 'x1 y1 x2 y2')
# alias
BBox = Corn... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import namedtuple
import numpy as np
Corner = namedtuple('Corner', 'x1 y1 x2 y2')
# alias
BBox = Corn... | # overlap
x1, y1, x2, y2 = rect1[0], rect1[1], rect1[2], rect1[3]
tx1, ty1, tx2, ty2 = rect2[0], rect2[1], rect2[2], rect2[3]
xx1 = np.maximum(tx1, x1)
yy1 = np.maximum(ty1, y1)
xx2 = np.minimum(tx2, x2)
yy2 = np.minimum(ty2, y2)
ww = np.maximum(0, xx2 - xx1)
hh = np.maximum(0, yy2... | """ caculate interection over union
Args:
rect1: (x1, y1, x2, y2)
rect2: (x1, y1, x2, y2)
Returns:
iou
"""
# overlap
x1, y1, x2, y2 = rect1[0], rect1[1], rect1[2], rect1[3]
tx1, ty1, tx2, ty2 = rect2[0], rect2[1], rect2[2], rect2[3]
xx1 = np.maximum(tx1, x1)
... | 76 | 1,606 | 268 | 1,874 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import namedtuple
import numpy as np
Corner = namedtuple('Corner', 'x1 y1 x2 y2')
# alias
BBox = Corn... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import namedtuple
import numpy as np
Corner = namedtuple('Corner', 'x1 y1 x2 y2')
# alias
BBox = Corn... | |
31,030 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/pysot/utils/log_helper.py | 155,156 | 1,174 | main | 156,170 | 156,170 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import logging
import math
import sys
if hasattr(sys, 'frozen'): # support for py2exe
_srcfile = "loggin... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import logging
import math
import sys
if hasattr(sys, 'frozen'): # support for py2exe
_srcfile = "loggin... | for i, lvl in enumerate([logging.DEBUG, logging.INFO,
logging.WARNING, logging.ERROR,
logging.CRITICAL]):
log_name = str(lvl)
init_log(log_name, lvl)
logger = logging.getLogger(log_name)
print('****cur lvl:{}'.format(lvl))
... | for i, lvl in enumerate([logging.DEBUG, logging.INFO,
logging.WARNING, logging.ERROR,
logging.CRITICAL]):
log_name = str(lvl)
init_log(log_name, lvl)
logger = logging.getLogger(log_name)
print('****cur lvl:{}'.format(lvl))
... | 24 | 1,465 | 153 | 1,618 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import logging
import math
import sys
if hasattr(sys, 'frozen'): # support for py2exe
_srcfile = "loggin... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import logging
import math
import sys
if hasattr(sys, 'frozen'): # support for py2exe
_srcfile = "loggin... | |
31,031 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/pysot/utils/log_helper.py | 38,38 | 33,42 | dummy | Dummy | 38,39 | 38,39 | class Dummy:
def __init__(self, *arg, **kwargs):
pass
def __getattr__(self, arg):
FILL_FUNC_BODY return dummy
| class Dummy:
def __init__(self, *arg, **kwargs):
pass
def __getattr__(self, arg):
FILL_FUNC_BODY return dummy
| def dummy(*args, **kwargs): pass
| def dummy(*args, **kwargs): pass
| 4 | 51 | 13 | 64 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import logging
import math
import sys
if hasattr(sys, 'frozen'): # support for py2exe
_srcfile = "loggin... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import logging
import math
import sys
if hasattr(sys, 'frozen'): # support for py2exe
_srcfile = "loggin... |
31,032 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/pysot/utils/log_helper.py | 29,30 | 25,33 | filter | Filter | 30,33 | 30,33 | class Filter:
def __init__(self, flag):
self.flag = flag
def filter(self, x):
FILL_FUNC_BODY | class Filter:
def __init__(self, flag):
self.flag = flag
def filter(self, x):
FILL_FUNC_BODY | return self.flag
| return self.flag
| 2 | 41 | 11 | 52 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import logging
import math
import sys
if hasattr(sys, 'frozen'): # support for py2exe
_srcfile = "loggin... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import logging
import math
import sys
if hasattr(sys, 'frozen'): # support for py2exe
_srcfile = "loggin... |
31,033 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/pysot/utils/log_helper.py | 137,138 | 132,148 | log | LogOnce | 138,148 | 138,148 | class LogOnce:
def __init__(self):
self.logged = set()
self.logger = init_log('log_once', format_func=get_format_custom)
def log(self, strings):
FILL_FUNC_BODY | class LogOnce:
def __init__(self):
self.logged = set()
self.logger = init_log('log_once', format_func=get_format_custom)
def log(self, strings):
FILL_FUNC_BODY | fn, lineno, caller = find_caller()
key = (fn, lineno, caller, strings)
if key in self.logged:
return
self.logged.add(key)
message = "{filename:s}<{caller}>#{lineno:3d}] {strings}".format(
filename=fn, lineno=lineno, strings=strings, caller=caller)
... | fn, lineno, caller = find_caller()
key = (fn, lineno, caller, strings)
if key in self.logged:
return
self.logged.add(key)
message = "{filename:s}<{caller}>#{lineno:3d}] {strings}".format(
filename=fn, lineno=lineno, strings=strings, caller=caller)
... | 26 | 66 | 128 | 194 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import logging
import math
import sys
if hasattr(sys, 'frozen'): # support for py2exe
_srcfile = "loggin... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import logging
import math
import sys
if hasattr(sys, 'frozen'): # support for py2exe
_srcfile = "loggin... |
31,034 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/pysot/utils/misc.py | 51,52 | 1,68 | commit | 52,60 | 52,60 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
from colorama import Fore, Style
__all__ = ['commit', 'describe']
def _exec(cmd):
f = os.popen(cmd, 'r... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
from colorama import Fore, Style
__all__ = ['commit', 'describe']
def _exec(cmd):
f = os.popen(cmd, 'r... | root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../'))
cmd = "cd {}; git log | head -n1 | awk '{{print $2}}'".format(root)
commit = _exec(cmd)
cmd = "cd {}; git log --oneline | head -n1".format(root)
commit_log = _exec(cmd)
return "commit : {}\n log : {}".format(commit, comm... | root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../'))
cmd = "cd {}; git log | head -n1 | awk '{{print $2}}'".format(root)
commit = _exec(cmd)
cmd = "cd {}; git log --oneline | head -n1".format(root)
commit_log = _exec(cmd)
return "commit : {}\n log : {}".format(commit, comm... | 41 | 461 | 134 | 595 | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
from colorama import Fore, Style
__all__ = ['commit', 'describe']
def _exec(cmd):
f = os.popen(cmd, 'r... | # Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
from colorama import Fore, Style
__all__ = ['commit', 'describe']
def _exec(cmd):
f = os.popen(cmd, 'r... | |
31,035 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/toolkit/datasets/lasot.py | 28,29 | 11,57 | load_tracker | LaSOTVideo | 34,57 | 29,57 | class LaSOTVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect: init rectangle
img_names: image names
gt_rect: groundtruth rectangle
attr: attribute of video
"""
def __init__(self, name, root, video_dir,... | class LaSOTVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect: init rectangle
img_names: image names
gt_rect: groundtruth rectangle
attr: attribute of video
"""
def __init__(self, name, root, video_dir,... | if not tracker_names:
tracker_names = [x.split('/')[-1] for x in glob(path)
if os.path.isdir(x)]
if isinstance(tracker_names, str):
tracker_names = [tracker_names]
for name in tracker_names:
traj_file = os.path.join(path, name, self.name+'.... | """
Args:
path(str): path to result
tracker_name(list): name of tracker
"""
if not tracker_names:
tracker_names = [x.split('/')[-1] for x in glob(path)
if os.path.isdir(x)]
if isinstance(tracker_names, str):
trac... | 67 | 243 | 298 | 541 | import os
import json
import numpy as np
from tqdm import tqdm
from glob import glob
from .dataset import Dataset
from .video import Video
class LaSOTVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect: init rectangle
img_na... | import os
import json
import numpy as np
from tqdm import tqdm
from glob import glob
from .dataset import Dataset
from .video import Video
class LaSOTVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect: init rectangle
img_na... |
31,036 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/toolkit/datasets/otb.py | 29,30 | 13,78 | load_tracker | OTBVideo | 35,78 | 30,78 | class OTBVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect: init rectangle
img_names: image names
gt_rect: groundtruth rectangle
attr: attribute of video
"""
def __init__(self, name, root, video_dir, i... | class OTBVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect: init rectangle
img_names: image names
gt_rect: groundtruth rectangle
attr: attribute of video
"""
def __init__(self, name, root, video_dir, i... | if not tracker_names:
tracker_names = [x.split('/')[-1] for x in glob(path)
if os.path.isdir(x)]
if isinstance(tracker_names, str):
tracker_names = [tracker_names]
for name in tracker_names:
traj_file = os.path.join(path, name, self.name+'.... | """
Args:
path(str): path to result
tracker_name(list): name of tracker
"""
if not tracker_names:
tracker_names = [x.split('/')[-1] for x in glob(path)
if os.path.isdir(x)]
if isinstance(tracker_names, str):
trac... | 132 | 220 | 611 | 831 | import json
import os
import numpy as np
from PIL import Image
from tqdm import tqdm
from glob import glob
from .dataset import Dataset
from .video import Video
class OTBVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect: init rec... | import json
import os
import numpy as np
from PIL import Image
from tqdm import tqdm
from glob import glob
from .dataset import Dataset
from .video import Video
class OTBVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect: init rec... |
31,037 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/toolkit/datasets/vot.py | 148,149 | 125,176 | load_tracker | VOTLTVideo | 154,176 | 149,176 | class VOTLTVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect: init rectangle
img_names: image names
gt_rect: groundtruth rectangle
"""
def __init__(self, name, root, video_dir, init_rect, img_names,
... | class VOTLTVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect: init rectangle
img_names: image names
gt_rect: groundtruth rectangle
"""
def __init__(self, name, root, video_dir, init_rect, img_names,
... | if not tracker_names:
tracker_names = [x.split('/')[-1] for x in glob(path)
if os.path.isdir(x)]
if isinstance(tracker_names, str):
tracker_names = [tracker_names]
for name in tracker_names:
traj_file = os.path.join(path, name, 'longterm',
... | """
Args:
path(str): path to result
tracker_name(list): name of tracker
"""
if not tracker_names:
tracker_names = [x.split('/')[-1] for x in glob(path)
if os.path.isdir(x)]
if isinstance(tracker_names, str):
trac... | 76 | 337 | 321 | 658 | import os
import cv2
import json
import numpy as np
from glob import glob
from tqdm import tqdm
from PIL import Image
from .dataset import Dataset
from .video import Video
class VOTVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect... | import os
import cv2
import json
import numpy as np
from glob import glob
from tqdm import tqdm
from PIL import Image
from .dataset import Dataset
from .video import Video
class VOTVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect... |
31,038 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/toolkit/datasets/vot.py | 63,64 | 13,91 | load_tracker | VOTVideo | 69,91 | 64,91 | class VOTVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect: init rectangle
img_names: image names
gt_rect: groundtruth rectangle
camera_motion: camera motion tag
illum_change: illum change tag
... | class VOTVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect: init rectangle
img_names: image names
gt_rect: groundtruth rectangle
camera_motion: camera motion tag
illum_change: illum change tag
... | if not tracker_names:
tracker_names = [x.split('/')[-1] for x in glob(path)
if os.path.isdir(x)]
if isinstance(tracker_names, str):
tracker_names = [tracker_names]
for name in tracker_names:
traj_files = glob(os.path.join(path, name, 'basel... | """
Args:
path(str): path to result
tracker_name(list): name of tracker
"""
if not tracker_names:
tracker_names = [x.split('/')[-1] for x in glob(path)
if os.path.isdir(x)]
if isinstance(tracker_names, str):
trac... | 69 | 764 | 293 | 1,057 | import os
import cv2
import json
import numpy as np
from glob import glob
from tqdm import tqdm
from PIL import Image
from .dataset import Dataset
from .video import Video
class VOTVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect... | import os
import cv2
import json
import numpy as np
from glob import glob
from tqdm import tqdm
from PIL import Image
from .dataset import Dataset
from .video import Video
class VOTVideo(Video):
"""
Args:
name: video name
root: dataset root
video_dir: video directory
init_rect... |
31,039 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/toolkit/evaluation/ar_benchmark.py | 42,43 | 12,142 | show_result | AccuracyRobustnessBenchmark | 47,118 | 43,118 | class AccuracyRobustnessBenchmark:
"""
Args:
dataset:
burnin:
"""
def __init__(self, dataset, burnin=10):
self.dataset = dataset
self.burnin = burnin
def eval(self, eval_trackers=None):
"""
Args:
eval_tags: list of tag
eval_tra... | class AccuracyRobustnessBenchmark:
"""
Args:
dataset:
burnin:
"""
def __init__(self, dataset, burnin=10):
self.dataset = dataset
self.burnin = burnin
def eval(self, eval_trackers=None):
"""
Args:
eval_tags: list of tag
eval_tra... | tracker_name_len = max((max([len(x) for x in result.keys()])+2), 12)
if eao_result is not None:
header = "|{:^"+str(tracker_name_len)+"}|{:^10}|{:^12}|{:^13}|{:^7}|"
header = header.format('Tracker Name',
'Accuracy', 'Robustness', 'Lost Number', 'EAO')
... | """pretty print result
Args:
result: returned dict from function eval
"""
tracker_name_len = max((max([len(x) for x in result.keys()])+2), 12)
if eao_result is not None:
header = "|{:^"+str(tracker_name_len)+"}|{:^10}|{:^12}|{:^13}|{:^7}|"
head... | 214 | 673 | 1,222 | 1,895 | """
@author
"""
import warnings
import itertools
import numpy as np
from colorama import Style, Fore
from ..utils import calculate_failures, calculate_accuracy
class AccuracyRobustnessBenchmark:
"""
Args:
dataset:
burnin:
"""
def __init__(self, dataset, burnin=10):
self.da... | """
@author
"""
import warnings
import itertools
import numpy as np
from colorama import Style, Fore
from ..utils import calculate_failures, calculate_accuracy
class AccuracyRobustnessBenchmark:
"""
Args:
dataset:
burnin:
"""
def __init__(self, dataset, burnin=10):
self.da... |
31,041 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/toolkit/evaluation/f1_benchmark.py | 40,41 | 10,148 | _cal_precision_reall | F1Benchmark | 41,70 | 41,70 | class F1Benchmark:
def __init__(self, dataset):
"""
Args:
result_path:
"""
self.dataset = dataset
def eval(self, eval_trackers=None):
"""
Args:
eval_tags: list of tag
eval_trackers: list of tracker name
Returns:
... | class F1Benchmark:
def __init__(self, dataset):
"""
Args:
result_path:
"""
self.dataset = dataset
def eval(self, eval_trackers=None):
"""
Args:
eval_tags: list of tag
eval_trackers: list of tracker name
Returns:
... | score = []
# for i in range(len(self.dataset)):
# video = self.dataset[i]
for video in self.dataset:
if tracker_name not in video.confidence:
score += video.load_tracker(self.dataset.tracker_path, tracker_name, False)[1]
else:
s... | score = []
# for i in range(len(self.dataset)):
# video = self.dataset[i]
for video in self.dataset:
if tracker_name not in video.confidence:
score += video.load_tracker(self.dataset.tracker_path, tracker_name, False)[1]
else:
s... | 103 | 1,494 | 424 | 1,918 | import os
import numpy as np
from glob import glob
from tqdm import tqdm
from colorama import Style, Fore
from ..utils import determine_thresholds, calculate_accuracy, calculate_f1
class F1Benchmark:
def __init__(self, dataset):
"""
Args:
result_path:
"""
self.dataset ... | import os
import numpy as np
from glob import glob
from tqdm import tqdm
from colorama import Style, Fore
from ..utils import determine_thresholds, calculate_accuracy, calculate_f1
class F1Benchmark:
def __init__(self, dataset):
"""
Args:
result_path:
"""
self.dataset ... |
31,043 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/toolkit/utils/misc.py | 6,7 | 1,31 | determine_thresholds | 16,31 | 7,31 | """
@author fangyi.zhang@vipl.ict.ac.cn
"""
import numpy as np
def determine_thresholds(confidence, resolution=100):
FILL_FUNC_BODY | """
@author fangyi.zhang@vipl.ict.ac.cn
"""
import numpy as np
def determine_thresholds(confidence, resolution=100):
"""choose threshold according to confidence
Args:
confidence: list or numpy array or numpy array
reolution: number of threshold to choose
Restures:
threshold: n... | if isinstance(confidence, list):
confidence = np.array(confidence)
confidence = confidence.flatten()
confidence = confidence[~np.isnan(confidence)]
confidence.sort()
assert len(confidence) > resolution and resolution > 2
thresholds = np.ones((resolution))
thresholds[0] = - np.inf
... | """choose threshold according to confidence
Args:
confidence: list or numpy array or numpy array
reolution: number of threshold to choose
Restures:
threshold: numpy array
"""
if isinstance(confidence, list):
confidence = np.array(confidence)
confidence = confide... | 49 | 111 | 194 | 305 | """
@author fangyi.zhang@vipl.ict.ac.cn
"""
import numpy as np
def determine_thresholds(confidence, resolution=100):
FILL_FUNC_BODY | """
@author fangyi.zhang@vipl.ict.ac.cn
"""
import numpy as np
def determine_thresholds(confidence, resolution=100):
"""choose threshold according to confidence
Args:
confidence: list or numpy array or numpy array
reolution: number of threshold to choose
Restures:
threshold: n... | |
31,045 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/toolkit/visualization/draw_eao.py | 11,12 | 1,50 | draw_eao | 12,47 | 12,47 | import matplotlib.pyplot as plt
import numpy as np
import pickle
from matplotlib import rc
from .draw_utils import COLOR, MARKER_STYLE
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
def draw_eao(result):
FILL_FUNC_BODYif __name__ == '__main__':
result = pickle.load(open("... | import matplotlib.pyplot as plt
import numpy as np
import pickle
from matplotlib import rc
from .draw_utils import COLOR, MARKER_STYLE
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
def draw_eao(result):
FILL_FUNC_BODYif __name__ == '__main__':
result = pickle.load(open("... | fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
angles = np.linspace(0, 2*np.pi, 8, endpoint=True)
attr2value = []
for i, (tracker_name, ret) in enumerate(result.items()):
value = list(ret.values())
attr2value.append(value)
value.append(value[0])
attr2va... | fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
angles = np.linspace(0, 2*np.pi, 8, endpoint=True)
attr2value = []
for i, (tracker_name, ret) in enumerate(result.items()):
value = list(ret.values())
attr2value.append(value)
value.append(value[0])
attr2va... | 105 | 147 | 560 | 707 | import matplotlib.pyplot as plt
import numpy as np
import pickle
from matplotlib import rc
from .draw_utils import COLOR, MARKER_STYLE
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
def draw_eao(result):
FILL_FUNC_BODYif __name__ == '__main__':
result = pickle.load(open("... | import matplotlib.pyplot as plt
import numpy as np
import pickle
from matplotlib import rc
from .draw_utils import COLOR, MARKER_STYLE
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
def draw_eao(result):
FILL_FUNC_BODYif __name__ == '__main__':
result = pickle.load(open("... | |
31,046 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/toolkit/visualization/draw_f1.py | 10,11 | 1,60 | draw_f1 | 11,58 | 11,58 | import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rc
from .draw_utils import COLOR, LINE_STYLE
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
def draw_f1(result, bold_name=None):
FILL_FUNC_BODYif __name__ == '__main__':
draw_f1(None)
| import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rc
from .draw_utils import COLOR, LINE_STYLE
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
def draw_f1(result, bold_name=None):
FILL_FUNC_BODYif __name__ == '__main__':
draw_f1(None)
| # drawing f1 contour
fig, ax = plt.subplots()
for f1 in np.arange(0.1, 1, 0.1):
recall = np.arange(f1, 1+0.01, 0.01)
precision = f1 * recall / (2 * recall - f1)
ax.plot(recall, precision, color=[0,1,0], linestyle='-', linewidth=0.5)
ax.plot(precision, recall, color=[0,1,0], l... | # drawing f1 contour
fig, ax = plt.subplots()
for f1 in np.arange(0.1, 1, 0.1):
recall = np.arange(f1, 1+0.01, 0.01)
precision = f1 * recall / (2 * recall - f1)
ax.plot(recall, precision, color=[0,1,0], linestyle='-', linewidth=0.5)
ax.plot(precision, recall, color=[0,1,0], l... | 166 | 127 | 796 | 923 | import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rc
from .draw_utils import COLOR, LINE_STYLE
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
def draw_f1(result, bold_name=None):
FILL_FUNC_BODYif __name__ == '__main__':
draw_f1(None)
| import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rc
from .draw_utils import COLOR, LINE_STYLE
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
def draw_f1(result, bold_name=None):
FILL_FUNC_BODYif __name__ == '__main__':
draw_f1(None)
| |
31,047 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/toolkit/visualization/draw_success_precision.py | 6,8 | 1,115 | draw_success_precision | 8,115 | 8,115 | import matplotlib.pyplot as plt
import numpy as np
from .draw_utils import COLOR, LINE_STYLE
def draw_success_precision(success_ret, name, videos, attr, precision_ret=None,
norm_precision_ret=None, bold_name=None, axis=[0, 1]):
FILL_FUNC_BODY | import matplotlib.pyplot as plt
import numpy as np
from .draw_utils import COLOR, LINE_STYLE
def draw_success_precision(success_ret, name, videos, attr, precision_ret=None,
norm_precision_ret=None, bold_name=None, axis=[0, 1]):
FILL_FUNC_BODY | # success plot
fig, ax = plt.subplots()
ax.grid(b=True)
ax.set_aspect(1)
plt.xlabel('Overlap threshold')
plt.ylabel('Success rate')
if attr == 'ALL':
plt.title(r'\textbf{Success plots of OPE on %s}' % (name))
else:
plt.title(r'\textbf{Success plots of OPE - %s}' % (attr))... | # success plot
fig, ax = plt.subplots()
ax.grid(b=True)
ax.set_aspect(1)
plt.xlabel('Overlap threshold')
plt.ylabel('Success rate')
if attr == 'ALL':
plt.title(r'\textbf{Success plots of OPE on %s}' % (name))
else:
plt.title(r'\textbf{Success plots of OPE - %s}' % (attr))... | 432 | 95 | 1,895 | 1,990 | import matplotlib.pyplot as plt
import numpy as np
from .draw_utils import COLOR, LINE_STYLE
def draw_success_precision(success_ret, name, videos, attr, precision_ret=None,
norm_precision_ret=None, bold_name=None, axis=[0, 1]):
FILL_FUNC_BODY | import matplotlib.pyplot as plt
import numpy as np
from .draw_utils import COLOR, LINE_STYLE
def draw_success_precision(success_ret, name, videos, attr, precision_ret=None,
norm_precision_ret=None, bold_name=None, axis=[0, 1]):
FILL_FUNC_BODY | |
31,049 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/training_dataset/coco/par_crop.py | 33,34 | 1,108 | crop_hwc | 34,44 | 34,44 | from pycocotools.coco import COCO
import cv2
import numpy as np
from os.path import join, isdir
from os import mkdir, makedirs
from concurrent import futures
import sys
import time
# Print iterations progress (thanks StackOverflow)
def printProgress(iteration, total, prefix='', suffix='', decimals=1, barLength=100):
... | from pycocotools.coco import COCO
import cv2
import numpy as np
from os.path import join, isdir
from os import mkdir, makedirs
from concurrent import futures
import sys
import time
# Print iterations progress (thanks StackOverflow)
def printProgress(iteration, total, prefix='', suffix='', decimals=1, barLength=100):
... | a = (out_sz-1) / (bbox[2]-bbox[0])
b = (out_sz-1) / (bbox[3]-bbox[1])
c = -a * bbox[0]
d = -b * bbox[1]
mapping = np.array([[a, 0, c],
[0, b, d]]).astype(np.float)
crop = cv2.warpAffine(image, mapping, (out_sz, out_sz), borderMode=cv2.BORDER_CONSTANT, borderValue=padding)... | a = (out_sz-1) / (bbox[2]-bbox[0])
b = (out_sz-1) / (bbox[3]-bbox[1])
c = -a * bbox[0]
d = -b * bbox[1]
mapping = np.array([[a, 0, c],
[0, b, d]]).astype(np.float)
crop = cv2.warpAffine(image, mapping, (out_sz, out_sz), borderMode=cv2.BORDER_CONSTANT, borderValue=padding)... | 38 | 1,614 | 168 | 1,782 | from pycocotools.coco import COCO
import cv2
import numpy as np
from os.path import join, isdir
from os import mkdir, makedirs
from concurrent import futures
import sys
import time
# Print iterations progress (thanks StackOverflow)
def printProgress(iteration, total, prefix='', suffix='', decimals=1, barLength=100):
... | from pycocotools.coco import COCO
import cv2
import numpy as np
from os.path import join, isdir
from os import mkdir, makedirs
from concurrent import futures
import sys
import time
# Print iterations progress (thanks StackOverflow)
def printProgress(iteration, total, prefix='', suffix='', decimals=1, barLength=100):
... | |
31,050 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/training_dataset/det/par_crop.py | 87,88 | 1,114 | main | 88,108 | 88,108 | from os.path import join, isdir
from os import mkdir, makedirs
import cv2
import numpy as np
import glob
import xml.etree.ElementTree as ET
from concurrent import futures
import time
import sys
# Print iterations progress (thanks StackOverflow)
def printProgress(iteration, total, prefix='', suffix='', decimals=1, bar... | from os.path import join, isdir
from os import mkdir, makedirs
import cv2
import numpy as np
import glob
import xml.etree.ElementTree as ET
from concurrent import futures
import time
import sys
# Print iterations progress (thanks StackOverflow)
def printProgress(iteration, total, prefix='', suffix='', decimals=1, bar... | crop_path = './crop{:d}'.format(instanc_size)
if not isdir(crop_path): mkdir(crop_path)
VID_base_path = './ILSVRC'
ann_base_path = join(VID_base_path, 'Annotations/DET/train/')
sub_sets = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i')
for sub_set in sub_sets:
sub_set_base_path = join(ann_... | crop_path = './crop{:d}'.format(instanc_size)
if not isdir(crop_path): mkdir(crop_path)
VID_base_path = './ILSVRC'
ann_base_path = join(VID_base_path, 'Annotations/DET/train/')
sub_sets = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i')
for sub_set in sub_sets:
sub_set_base_path = join(ann_... | 79 | 1,476 | 387 | 1,863 | from os.path import join, isdir
from os import mkdir, makedirs
import cv2
import numpy as np
import glob
import xml.etree.ElementTree as ET
from concurrent import futures
import time
import sys
# Print iterations progress (thanks StackOverflow)
def printProgress(iteration, total, prefix='', suffix='', decimals=1, bar... | from os.path import join, isdir
from os import mkdir, makedirs
import cv2
import numpy as np
import glob
import xml.etree.ElementTree as ET
from concurrent import futures
import time
import sys
# Print iterations progress (thanks StackOverflow)
def printProgress(iteration, total, prefix='', suffix='', decimals=1, bar... | |
31,051 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/training_dataset/vid/par_crop.py | 53,54 | 1,119 | crop_like_SiamFC | 54,69 | 54,69 | from os.path import join, isdir
from os import listdir, mkdir, makedirs
import cv2
import numpy as np
import glob
import xml.etree.ElementTree as ET
from concurrent import futures
import sys
import time
VID_base_path = './ILSVRC2015'
ann_base_path = join(VID_base_path, 'Annotations/VID/train/')
sub_sets = sorted({'a',... | from os.path import join, isdir
from os import listdir, mkdir, makedirs
import cv2
import numpy as np
import glob
import xml.etree.ElementTree as ET
from concurrent import futures
import sys
import time
VID_base_path = './ILSVRC2015'
ann_base_path = join(VID_base_path, 'Annotations/VID/train/')
sub_sets = sorted({'a',... | target_pos = [(bbox[2]+bbox[0])/2., (bbox[3]+bbox[1])/2.]
target_size = [bbox[2]-bbox[0], bbox[3]-bbox[1]]
wc_z = target_size[1] + context_amount * sum(target_size)
hc_z = target_size[0] + context_amount * sum(target_size)
s_z = np.sqrt(wc_z * hc_z)
scale_z = exemplar_size / s_z
d_search = (... | target_pos = [(bbox[2]+bbox[0])/2., (bbox[3]+bbox[1])/2.]
target_size = [bbox[2]-bbox[0], bbox[3]-bbox[1]]
wc_z = target_size[1] + context_amount * sum(target_size)
hc_z = target_size[0] + context_amount * sum(target_size)
s_z = np.sqrt(wc_z * hc_z)
scale_z = exemplar_size / s_z
d_search = (... | 68 | 1,632 | 284 | 1,916 | from os.path import join, isdir
from os import listdir, mkdir, makedirs
import cv2
import numpy as np
import glob
import xml.etree.ElementTree as ET
from concurrent import futures
import sys
import time
VID_base_path = './ILSVRC2015'
ann_base_path = join(VID_base_path, 'Annotations/VID/train/')
sub_sets = sorted({'a',... | from os.path import join, isdir
from os import listdir, mkdir, makedirs
import cv2
import numpy as np
import glob
import xml.etree.ElementTree as ET
from concurrent import futures
import sys
import time
VID_base_path = './ILSVRC2015'
ann_base_path = join(VID_base_path, 'Annotations/VID/train/')
sub_sets = sorted({'a',... | |
31,052 | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot | /home/hieuvd/dung_repo/raw/stars_02/STVIR_pysot/pysot/vot_iter/vot.py | 88,89 | 25,118 | frame | VOT | 95,111 | 89,111 | class VOT(object):
""" Base class for Python VOT integration """
def __init__(self, region_format, channels=None):
""" Constructor
Args:
region_format: Region format options
"""
assert(region_format in [trax.Region.RECTANGLE, trax.Region.POLYGON])
if channel... | class VOT(object):
""" Base class for Python VOT integration """
def __init__(self, region_format, channels=None):
""" Constructor
Args:
region_format: Region format options
"""
assert(region_format in [trax.Region.RECTANGLE, trax.Region.POLYGON])
if channel... | if hasattr(self, "_image"):
image = self._image
del self._image
return image
request = self._trax.wait()
if request.type == 'frame':
image = [x.path() for k, x in request.image.items()]
if len(image) == 1:
return image... | """
Get a frame (image path) from client
Returns:
absolute path of the image
"""
if hasattr(self, "_image"):
image = self._image
del self._image
return image
request = self._trax.wait()
if request.type == 'frame':... | 36 | 670 | 120 | 790 | """
\file vot.py
@brief Python utility functions for VOT integration
@author Luka Cehovin, Alessio Dore
@date 2016
"""
import sys
import copy
import collections
try:
import trax
except ImportError:
raise Exception('TraX support not found. Please add trax module to Python path.')
Rectangle = collections.n... | """
\file vot.py
@brief Python utility functions for VOT integration
@author Luka Cehovin, Alessio Dore
@date 2016
"""
import sys
import copy
import collections
try:
import trax
except ImportError:
raise Exception('TraX support not found. Please add trax module to Python path.')
Rectangle = collections.n... |
31,120 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/examples/zhihu/crawler.py | 54,55 | 17,87 | get | Crawler | 55,87 | 55,87 | class Crawler:
timeout = 10
success_req = TOTAL_SUCCESS_REQUESTS
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
'Host': 'www.zhihu.com'
}
redis_args = {
'host': R... | class Crawler:
timeout = 10
success_req = TOTAL_SUCCESS_REQUESTS
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
'Host': 'www.zhihu.com'
}
redis_args = {
'host': R... | tries = 0
while tries < self.retries:
proxy = {self.scheme: self.fetcher.get_proxy()}
while not proxy.get(self.scheme):
time.sleep(0.5)
proxy = {self.scheme: self.fetcher.get_proxy()}
try:
start = time.time() * 1000
... | tries = 0
while tries < self.retries:
proxy = {self.scheme: self.fetcher.get_proxy()}
while not proxy.get(self.scheme):
time.sleep(0.5)
proxy = {self.scheme: self.fetcher.get_proxy()}
try:
start = time.time() * 1000
... | 117 | 459 | 417 | 876 | import time
import requests
from haipproxy.client import ProxyFetcher
from haipproxy.utils import get_redis_conn
from .configs import (
SCORE_MAPS, TTL_MAPS,
SPEED_MAPS, LONGEST_RESPONSE_TIME,
LOWEST_SCORE, TTL_VALIDATED_RESOURCE,
LOWEST_TOTAL_PROXIES, DATA_ALL,
TOTAL_SUCCESS_REQUESTS, REDIS_HOST,... | import time
import requests
from haipproxy.client import ProxyFetcher
from haipproxy.utils import get_redis_conn
from .configs import (
SCORE_MAPS, TTL_MAPS,
SPEED_MAPS, LONGEST_RESPONSE_TIME,
LOWEST_SCORE, TTL_VALIDATED_RESOURCE,
LOWEST_TOTAL_PROXIES, DATA_ALL,
TOTAL_SUCCESS_REQUESTS, REDIS_HOST,... |
31,121 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/examples/zhihu/exporter.py | 27,28 | 23,36 | collect | CustomCollector | 28,36 | 28,36 | class CustomCollector:
def __init__(self):
self.redis_con = get_redis_conn(**redis_args)
def collect(self):
FILL_FUNC_BODY | class CustomCollector:
def __init__(self):
self.redis_con = get_redis_conn(**redis_args)
def collect(self):
FILL_FUNC_BODY | try:
redis_count = int(self.redis_con.get(TOTAL_SUCCESS_REQUESTS).decode())
except AttributeError:
redis_count = 0
yield CounterMetricFamily('total_success_requests',
'successful requests', value=redis_count)
| try:
redis_count = int(self.redis_con.get(TOTAL_SUCCESS_REQUESTS).decode())
except AttributeError:
redis_count = 0
yield CounterMetricFamily('total_success_requests',
'successful requests', value=redis_count)
| 14 | 54 | 90 | 144 | import time
from prometheus_client import start_http_server
from prometheus_client.core import (
CounterMetricFamily, REGISTRY
)
from haipproxy.utils import get_redis_conn
from examples.zhihu.configs import (
REDIS_HOST, REDIS_PORT,
REDIS_PASS, REDIS_DB,
TOTAL_SUCCESS_REQUESTS
)
redis_args = {
'h... | import time
from prometheus_client import start_http_server
from prometheus_client.core import (
CounterMetricFamily, REGISTRY
)
from haipproxy.utils import get_redis_conn
from examples.zhihu.configs import (
REDIS_HOST, REDIS_PORT,
REDIS_PASS, REDIS_DB,
TOTAL_SUCCESS_REQUESTS
)
redis_args = {
'h... |
31,122 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/client/core.py | 22,23 | 10,40 | get_available_proxies | IPFetcherMixin | 24,40 | 23,40 | class IPFetcherMixin:
def __init__(self, score_queue, ttl_queue, speed_queue,
longest_response_time, lowest_score, ttl_validated_resource,
min_pool_size):
self.score_queue = score_queue
self.ttl_queue = ttl_queue
self.speed_queue = speed_queue
self.l... | class IPFetcherMixin:
def __init__(self, score_queue, ttl_queue, speed_queue,
longest_response_time, lowest_score, ttl_validated_resource,
min_pool_size):
self.score_queue = score_queue
self.ttl_queue = ttl_queue
self.speed_queue = speed_queue
self.l... | start_time = int(time.time()) - self.ttl_validated_resource * 60
pipe = conn.pipeline(False)
pipe.zrevrangebyscore(self.score_queue, '+inf', self.lowest_score)
pipe.zrevrangebyscore(self.ttl_queue, '+inf', start_time)
pipe.zrangebyscore(self.speed_queue, 0, 1000 * self.longest_re... | """core algrithm to get proxies from redis"""
start_time = int(time.time()) - self.ttl_validated_resource * 60
pipe = conn.pipeline(False)
pipe.zrevrangebyscore(self.score_queue, '+inf', self.lowest_score)
pipe.zrevrangebyscore(self.ttl_queue, '+inf', start_time)
pipe.zra... | 73 | 198 | 345 | 543 | """
This module provides core code for picking up proxies
"""
import time
# from logger import client_logger
from ..utils import decode_all
class IPFetcherMixin:
def __init__(self, score_queue, ttl_queue, speed_queue,
longest_response_time, lowest_score, ttl_validated_resource,
... | """
This module provides core code for picking up proxies
"""
import time
# from logger import client_logger
from ..utils import decode_all
class IPFetcherMixin:
def __init__(self, score_queue, ttl_queue, speed_queue,
longest_response_time, lowest_score, ttl_validated_resource,
... |
31,123 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/client/py_cli.py | 77,78 | 68,91 | process_feedback | GreedyStrategy | 78,91 | 78,91 | class GreedyStrategy(Strategy):
def __init__(self):
self.strategy = 'greedy'
def get_proxies_by_stragery(self, pool):
if not pool:
return None
return pool[0]
def process_feedback(self, pool, res, proxy, **kwargs):
FILL_FUNC_BODY | class GreedyStrategy(Strategy):
def __init__(self):
self.strategy = 'greedy'
def get_proxies_by_stragery(self, pool):
if not pool:
return None
return pool[0]
def process_feedback(self, pool, res, proxy, **kwargs):
FILL_FUNC_BODY | if res == 'failure':
if pool[0] == proxy:
with lock:
if pool[0] == proxy:
pool.pop(0)
return
expected_time = kwargs.get('expected')
real_time = kwargs.get('real')
if expected_time * 1000 < real_time:
... | if res == 'failure':
if pool[0] == proxy:
with lock:
if pool[0] == proxy:
pool.pop(0)
return
expected_time = kwargs.get('expected')
real_time = kwargs.get('real')
if expected_time * 1000 < real_time:
... | 30 | 94 | 121 | 215 | """
python client for haipproxy
"""
import time
import threading
from ..utils import get_redis_conn
from ..config.rules import (
SCORE_MAPS, TTL_MAPS,
SPEED_MAPS)
from ..config.settings import (
TTL_VALIDATED_RESOURCE, LONGEST_RESPONSE_TIME,
LOWEST_SCORE, LOWEST_TOTAL_PROXIES,
DATA_ALL)
from .core ... | """
python client for haipproxy
"""
import time
import threading
from ..utils import get_redis_conn
from ..config.rules import (
SCORE_MAPS, TTL_MAPS,
SPEED_MAPS)
from ..config.settings import (
TTL_VALIDATED_RESOURCE, LONGEST_RESPONSE_TIME,
LOWEST_SCORE, LOWEST_TOTAL_PROXIES,
DATA_ALL)
from .core ... |
31,124 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/client/py_cli.py | 147,148 | 91,186 | get_proxies | ProxyFetcher | 148,155 | 148,155 | class ProxyFetcher(IPFetcherMixin):
def __init__(self, usage, strategy='robin', fast_response=5,
score_map=SCORE_MAPS, ttl_map=TTL_MAPS, speed_map=SPEED_MAPS,
longest_response_time=LONGEST_RESPONSE_TIME, lowest_score=LOWEST_SCORE,
ttl_validated_resource=TTL_VALIDAT... | class ProxyFetcher(IPFetcherMixin):
def __init__(self, usage, strategy='robin', fast_response=5,
score_map=SCORE_MAPS, ttl_map=TTL_MAPS, speed_map=SPEED_MAPS,
longest_response_time=LONGEST_RESPONSE_TIME, lowest_score=LOWEST_SCORE,
ttl_validated_resource=TTL_VALIDAT... | # the older proxies will not be dropped
proxies = self.get_available_proxies(self.conn)
# client_logger.info('{} proxies have been fetched'.format(len(proxies)))
print('{} proxies have been fetched'.format(len(proxies)))
self.pool.extend(proxies)
return self.pool
| # the older proxies will not be dropped
proxies = self.get_available_proxies(self.conn)
# client_logger.info('{} proxies have been fetched'.format(len(proxies)))
print('{} proxies have been fetched'.format(len(proxies)))
self.pool.extend(proxies)
return self.pool
| 25 | 1,207 | 105 | 1,312 | """
python client for haipproxy
"""
import time
import threading
from ..utils import get_redis_conn
from ..config.rules import (
SCORE_MAPS, TTL_MAPS,
SPEED_MAPS)
from ..config.settings import (
TTL_VALIDATED_RESOURCE, LONGEST_RESPONSE_TIME,
LOWEST_SCORE, LOWEST_TOTAL_PROXIES,
DATA_ALL)
from .core ... | """
python client for haipproxy
"""
import time
import threading
from ..utils import get_redis_conn
from ..config.rules import (
SCORE_MAPS, TTL_MAPS,
SPEED_MAPS)
from ..config.settings import (
TTL_VALIDATED_RESOURCE, LONGEST_RESPONSE_TIME,
LOWEST_SCORE, LOWEST_TOTAL_PROXIES,
DATA_ALL)
from .core ... |
31,125 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/client/py_cli.py | 51,52 | 46,68 | get_proxies_by_stragery | RobinStrategy | 52,59 | 52,59 | class RobinStrategy(Strategy):
def __init__(self):
super().__init__()
self.strategy = 'robin'
def get_proxies_by_stragery(self, pool):
FILL_FUNC_BODY def process_feedback(self, pool, res, proxy, **kwargs):
if res == 'failure':
if pool[-1] == proxy:
with lo... | class RobinStrategy(Strategy):
def __init__(self):
super().__init__()
self.strategy = 'robin'
def get_proxies_by_stragery(self, pool):
FILL_FUNC_BODY def process_feedback(self, pool, res, proxy, **kwargs):
if res == 'failure':
if pool[-1] == proxy:
with lo... | if not pool:
return None
proxy = pool.pop(0)
pool.append(proxy)
return proxy
| if not pool:
return None
proxy = pool.pop(0)
pool.append(proxy)
return proxy
| 11 | 128 | 41 | 169 | """
python client for haipproxy
"""
import time
import threading
from ..utils import get_redis_conn
from ..config.rules import (
SCORE_MAPS, TTL_MAPS,
SPEED_MAPS)
from ..config.settings import (
TTL_VALIDATED_RESOURCE, LONGEST_RESPONSE_TIME,
LOWEST_SCORE, LOWEST_TOTAL_PROXIES,
DATA_ALL)
from .core ... | """
python client for haipproxy
"""
import time
import threading
from ..utils import get_redis_conn
from ..config.rules import (
SCORE_MAPS, TTL_MAPS,
SPEED_MAPS)
from ..config.settings import (
TTL_VALIDATED_RESOURCE, LONGEST_RESPONSE_TIME,
LOWEST_SCORE, LOWEST_TOTAL_PROXIES,
DATA_ALL)
from .core ... |
31,126 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/client/py_cli.py | 28,29 | 22,46 | get_proxies_by_stragery | Strategy | 33,35 | 29,35 | class Strategy:
strategy = None
def check(self, strategy):
return self.strategy == strategy
def get_proxies_by_stragery(self, pool):
FILL_FUNC_BODY def process_feedback(self, pool, res, proxy, **kwargs):
"""
:param pool: ProxyFetcher's pool
:param res: success or failure... | class Strategy:
strategy = None
def check(self, strategy):
return self.strategy == strategy
def get_proxies_by_stragery(self, pool):
"""
:param pool: pool is a list, which is mutable
:return:
"""
FILL_FUNC_BODY def process_feedback(self, pool, res, proxy, **kwarg... | raise NotImplementedError
| """
:param pool: pool is a list, which is mutable
:return:
"""
raise NotImplementedError
| 2 | 171 | 11 | 182 | """
python client for haipproxy
"""
import time
import threading
from ..utils import get_redis_conn
from ..config.rules import (
SCORE_MAPS, TTL_MAPS,
SPEED_MAPS)
from ..config.settings import (
TTL_VALIDATED_RESOURCE, LONGEST_RESPONSE_TIME,
LOWEST_SCORE, LOWEST_TOTAL_PROXIES,
DATA_ALL)
from .core ... | """
python client for haipproxy
"""
import time
import threading
from ..utils import get_redis_conn
from ..config.rules import (
SCORE_MAPS, TTL_MAPS,
SPEED_MAPS)
from ..config.settings import (
TTL_VALIDATED_RESOURCE, LONGEST_RESPONSE_TIME,
LOWEST_SCORE, LOWEST_TOTAL_PROXIES,
DATA_ALL)
from .core ... |
31,127 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/client/scrapy_middleware.py | 6,7 | 5,11 | process_request | ProxyMiddleware | 7,11 | 7,11 | class ProxyMiddleware:
def process_request(self, request, spider):
FILL_FUNC_BODY | class ProxyMiddleware:
def process_request(self, request, spider):
FILL_FUNC_BODY | if request.meta.get('need_proxy'):
pass # use proxy
| if request.meta.get('need_proxy'):
pass # use proxy
| 6 | 32 | 27 | 59 | from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
class ProxyMiddleware:
def process_request(self, request, spider):
FILL_FUNC_BODYclass ProxyRetryMiddleware(RetryMiddleware):
def delete_proxy(self, proxy):
pass
def process_re... | from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
class ProxyMiddleware:
def process_request(self, request, spider):
FILL_FUNC_BODYclass ProxyRetryMiddleware(RetryMiddleware):
def delete_proxy(self, proxy):
pass
def process_re... |
31,128 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/client/scrapy_middleware.py | 15,16 | 11,32 | process_response | ProxyRetryMiddleware | 16,24 | 16,24 | class ProxyRetryMiddleware(RetryMiddleware):
def delete_proxy(self, proxy):
pass
def process_response(self, request, response, spider):
FILL_FUNC_BODY def process_exception(self, request, exception, spider):
if isinstance(exception, self.EXCEPTIONS_TO_RETRY) \
and not request... | class ProxyRetryMiddleware(RetryMiddleware):
def delete_proxy(self, proxy):
pass
def process_response(self, request, response, spider):
FILL_FUNC_BODY def process_exception(self, request, exception, spider):
if isinstance(exception, self.EXCEPTIONS_TO_RETRY) \
and not request... | if response.status in self.retry_http_codes:
reason = response_status_message(response.status)
# 删除该代理
self.delete_proxy(request.meta.get('proxy', False))
print('返回值异常, 进行重试...')
return self._retry(request, reason, spider) or response
return re... | if response.status in self.retry_http_codes:
reason = response_status_message(response.status)
# 删除该代理
self.delete_proxy(request.meta.get('proxy', False))
print('返回值异常, 进行重试...')
return self._retry(request, reason, spider) or response
return re... | 21 | 165 | 102 | 267 | from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
class ProxyMiddleware:
def process_request(self, request, spider):
if request.meta.get('need_proxy'):
pass # use proxy
class ProxyRetryMiddleware(RetryMiddleware):
de... | from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
class ProxyMiddleware:
def process_request(self, request, spider):
if request.meta.get('need_proxy'):
pass # use proxy
class ProxyRetryMiddleware(RetryMiddleware):
de... |
31,129 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/client/squid.py | 53,54 | 22,76 | update_conf | SquidClient | 54,76 | 54,76 | class SquidClient(IPFetcherMixin):
default_conf_detail = "cache_peer {} parent {} 0 no-query weighted-round-robin weight=1 " \
"connect-fail-limit=2 allow-miss max-conn=5 name=proxy-{}"
other_confs = ['request_header_access Via deny all', 'request_header_access X-Forwarded-For deny all... | class SquidClient(IPFetcherMixin):
default_conf_detail = "cache_peer {} parent {} 0 no-query weighted-round-robin weight=1 " \
"connect-fail-limit=2 allow-miss max-conn=5 name=proxy-{}"
other_confs = ['request_header_access Via deny all', 'request_header_access X-Forwarded-For deny all... | conn = get_redis_conn()
proxies = self.get_available_proxies(conn)
conts = list()
with open(self.template_path, 'r') as fr, open(self.conf_path, 'w') as fw:
original_conf = fr.read()
if not proxies:
fw.write(original_conf)
# client_... | conn = get_redis_conn()
proxies = self.get_available_proxies(conn)
conts = list()
with open(self.template_path, 'r') as fr, open(self.conf_path, 'w') as fw:
original_conf = fr.read()
if not proxies:
fw.write(original_conf)
# client_... | 94 | 544 | 336 | 880 | """
Squid Client for spiders.
"""
import subprocess
# from logger import client_logger
from ..utils import get_redis_conn
from ..config.settings import (
SQUID_BIN_PATH, SQUID_CONF_PATH,
SQUID_TEMPLATE_PATH, TTL_VALIDATED_RESOURCE,
LONGEST_RESPONSE_TIME, LOWEST_SCORE,
LOWEST_TOTAL_PROXIES)
from ..confi... | """
Squid Client for spiders.
"""
import subprocess
# from logger import client_logger
from ..utils import get_redis_conn
from ..config.settings import (
SQUID_BIN_PATH, SQUID_CONF_PATH,
SQUID_TEMPLATE_PATH, TTL_VALIDATED_RESOURCE,
LONGEST_RESPONSE_TIME, LOWEST_SCORE,
LOWEST_TOTAL_PROXIES)
from ..confi... |
31,130 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/extensions.py | 18,19 | 10,29 | spider_error | FailLogger | 19,29 | 19,29 | class FailLogger(object):
@classmethod
def from_crawler(cls, crawler):
ext = cls()
crawler.signals.connect(ext.spider_error, signal=signals.spider_error)
return ext
def spider_error(self, failure, response, spider):
FILL_FUNC_BODY | class FailLogger(object):
@classmethod
def from_crawler(cls, crawler):
ext = cls()
crawler.signals.connect(ext.spider_error, signal=signals.spider_error)
return ext
def spider_error(self, failure, response, spider):
FILL_FUNC_BODY | if USE_SENTRY:
try:
failure.raiseException()
except:
message = 'error occurs when parsing {}'.format(response.url)
client.captureException(message=message)
else:
spider.logger.error("Error on {0}, traceback: {1}".format(... | if USE_SENTRY:
try:
failure.raiseException()
except:
message = 'error occurs when parsing {}'.format(response.url)
client.captureException(message=message)
else:
spider.logger.error("Error on {0}, traceback: {1}".format(... | 21 | 94 | 104 | 198 | from scrapy import signals
from ..config.settings import USE_SENTRY
from ..utils.err_trace import client
# don't know why process_spider_exception in spidermiddleware
# can't be called, so we use extensions to workaround, for more
# information, see: https://github.com/scrapy/scrapy/issues/220
class FailLogger(objec... | from scrapy import signals
from ..config.settings import USE_SENTRY
from ..utils.err_trace import client
# don't know why process_spider_exception in spidermiddleware
# can't be called, so we use extensions to workaround, for more
# information, see: https://github.com/scrapy/scrapy/issues/220
class FailLogger(objec... |
31,131 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/middlewares.py | 71,72 | 60,82 | _faillog | ErrorTraceMiddleware | 72,82 | 72,82 | class ErrorTraceMiddleware(object):
def process_response(self, request, response, spider):
if response.status >= 400:
reason = 'error http code {} for {}'.format(response.status, request.url)
self._faillog(request, HttpError, reason, spider)
return response
def process_e... | class ErrorTraceMiddleware(object):
def process_response(self, request, response, spider):
if response.status >= 400:
reason = 'error http code {} for {}'.format(response.status, request.url)
self._faillog(request, HttpError, reason, spider)
return response
def process_e... | if USE_SENTRY:
try:
raise exc
except Exception:
message = 'error occurs when downloading {}'.format(request.url)
client.captureException(message=message)
else:
print(reason)
| if USE_SENTRY:
try:
raise exc
except Exception:
message = 'error occurs when downloading {}'.format(request.url)
client.captureException(message=message)
else:
print(reason)
| 17 | 149 | 73 | 222 | """
scrapy middlerwares for both downloader and spider
"""
import time
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
from ..exceptions import (
HttpError, DownloadException
)
from ..config.settings import (
GFW_PROXY, USE_SENTRY)
from ... | """
scrapy middlerwares for both downloader and spider
"""
import time
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
from ..exceptions import (
HttpError, DownloadException
)
from ..config.settings import (
GFW_PROXY, USE_SENTRY)
from ... |
31,132 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/middlewares.py | 29,30 | 26,44 | process_request | ProxyMiddleware | 30,44 | 30,44 | class ProxyMiddleware(object):
"""This middleware provides http and https proxy for spiders"""
def process_request(self, request, spider):
FILL_FUNC_BODY | class ProxyMiddleware(object):
"""This middleware provides http and https proxy for spiders"""
def process_request(self, request, spider):
FILL_FUNC_BODY | # TODO: implement the code for spider.proxy_mode == 1, using proxy pools
if not hasattr(spider, 'proxy_mode') or not spider.proxy_mode:
return
if spider.proxy_mode == 1:
pass
if spider.proxy_mode == 2:
if 'splash' in request.meta:
req... | # TODO: implement the code for spider.proxy_mode == 1, using proxy pools
if not hasattr(spider, 'proxy_mode') or not spider.proxy_mode:
return
if spider.proxy_mode == 1:
pass
if spider.proxy_mode == 2:
if 'splash' in request.meta:
req... | 40 | 50 | 142 | 192 | """
scrapy middlerwares for both downloader and spider
"""
import time
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
from ..exceptions import (
HttpError, DownloadException
)
from ..config.settings import (
GFW_PROXY, USE_SENTRY)
from ... | """
scrapy middlerwares for both downloader and spider
"""
import time
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
from ..exceptions import (
HttpError, DownloadException
)
from ..config.settings import (
GFW_PROXY, USE_SENTRY)
from ... |
31,133 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/middlewares.py | 95,96 | 82,103 | process_exception | ProxyRetryMiddleware | 96,103 | 96,103 | class ProxyRetryMiddleware(RetryMiddleware):
def delete_proxy(self, proxy):
pass
def process_response(self, request, response, spider):
if response.status in self.retry_http_codes:
reason = response_status_message(response.status)
# 删除该代理
self.delete_proxy(re... | class ProxyRetryMiddleware(RetryMiddleware):
def delete_proxy(self, proxy):
pass
def process_response(self, request, response, spider):
if response.status in self.retry_http_codes:
reason = response_status_message(response.status)
# 删除该代理
self.delete_proxy(re... | if isinstance(exception, self.EXCEPTIONS_TO_RETRY) \
and not request.meta.get('dont_retry', False):
# 删除该代理
self.delete_proxy(request.meta.get('proxy', False))
print('连接异常, 进行重试...')
return self._retry(request, exception, spider) | if isinstance(exception, self.EXCEPTIONS_TO_RETRY) \
and not request.meta.get('dont_retry', False):
# 删除该代理
self.delete_proxy(request.meta.get('proxy', False))
print('连接异常, 进行重试...')
return self._retry(request, exception, spider) | 18 | 167 | 99 | 266 | """
scrapy middlerwares for both downloader and spider
"""
import time
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
from ..exceptions import (
HttpError, DownloadException
)
from ..config.settings import (
GFW_PROXY, USE_SENTRY)
from ... | """
scrapy middlerwares for both downloader and spider
"""
import time
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
from ..exceptions import (
HttpError, DownloadException
)
from ..config.settings import (
GFW_PROXY, USE_SENTRY)
from ... |
31,134 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/middlewares.py | 54,55 | 51,60 | process_response | RequestEndProfileMiddleware | 55,60 | 55,60 | class RequestEndProfileMiddleware(object):
"""This middleware calculates the ip's speed"""
def process_response(self, request, response, spider):
FILL_FUNC_BODY | class RequestEndProfileMiddleware(object):
"""This middleware calculates the ip's speed"""
def process_response(self, request, response, spider):
FILL_FUNC_BODY | speed = int(time.time() * 1000) - request.meta['start']
request.meta['speed'] = speed
return response
| speed = int(time.time() * 1000) - request.meta['start']
request.meta['speed'] = speed
return response
| 12 | 52 | 45 | 97 | """
scrapy middlerwares for both downloader and spider
"""
import time
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
from ..exceptions import (
HttpError, DownloadException
)
from ..config.settings import (
GFW_PROXY, USE_SENTRY)
from ... | """
scrapy middlerwares for both downloader and spider
"""
import time
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
from ..exceptions import (
HttpError, DownloadException
)
from ..config.settings import (
GFW_PROXY, USE_SENTRY)
from ... |
31,135 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/middlewares.py | 47,48 | 44,51 | process_request | RequestStartProfileMiddleware | 48,51 | 48,51 | class RequestStartProfileMiddleware(object):
"""This middleware calculates the ip's speed"""
def process_request(self, request, spider):
FILL_FUNC_BODY | class RequestStartProfileMiddleware(object):
"""This middleware calculates the ip's speed"""
def process_request(self, request, spider):
FILL_FUNC_BODY | request.meta['start'] = int(time.time() * 1000)
| request.meta['start'] = int(time.time() * 1000)
| 5 | 50 | 27 | 77 | """
scrapy middlerwares for both downloader and spider
"""
import time
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
from ..exceptions import (
HttpError, DownloadException
)
from ..config.settings import (
GFW_PROXY, USE_SENTRY)
from ... | """
scrapy middlerwares for both downloader and spider
"""
import time
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
from ..exceptions import (
HttpError, DownloadException
)
from ..config.settings import (
GFW_PROXY, USE_SENTRY)
from ... |
31,136 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/middlewares.py | 21,22 | 18,26 | process_request | UserAgentMiddleware | 22,26 | 22,26 | class UserAgentMiddleware(object):
"""This middleware changes user agent randomly"""
def process_request(self, request, spider):
FILL_FUNC_BODY | class UserAgentMiddleware(object):
"""This middleware changes user agent randomly"""
def process_request(self, request, spider):
FILL_FUNC_BODY | request.headers['User-Agent'] = FakeChromeUA.get_ua()
request.headers['Accept-Language'] = 'zh-CN,zh;q=0.8,en;q=0.6'
| request.headers['User-Agent'] = FakeChromeUA.get_ua()
request.headers['Accept-Language'] = 'zh-CN,zh;q=0.8,en;q=0.6'
| 6 | 46 | 61 | 107 | """
scrapy middlerwares for both downloader and spider
"""
import time
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
from ..exceptions import (
HttpError, DownloadException
)
from ..config.settings import (
GFW_PROXY, USE_SENTRY)
from ... | """
scrapy middlerwares for both downloader and spider
"""
import time
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
from ..exceptions import (
HttpError, DownloadException
)
from ..config.settings import (
GFW_PROXY, USE_SENTRY)
from ... |
31,137 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/pipelines.py | 18,19 | 17,28 | open_spider | BasePipeline | 19,21 | 19,21 | class BasePipeline:
def open_spider(self, spider):
FILL_FUNC_BODY def process_item(self, item, spider):
return deferToThread(self._process_item, item, spider)
def _process_item(self, item, spider):
raise NotImplementedError
| class BasePipeline:
def open_spider(self, spider):
FILL_FUNC_BODY def process_item(self, item, spider):
return deferToThread(self._process_item, item, spider)
def _process_item(self, item, spider):
raise NotImplementedError
| self.redis_con = get_redis_conn(db=REDIS_DB)
| self.redis_con = get_redis_conn(db=REDIS_DB)
| 3 | 88 | 26 | 114 | """
scrapy pipelines for storing proxy ip infos.
"""
from twisted.internet.threads import deferToThread
from scrapy.exceptions import DropItem
from ..utils import get_redis_conn
from ..config.settings import (
REDIS_DB, DATA_ALL,
INIT_HTTP_QUEUE, INIT_SOCKS4_QUEUE,
INIT_SOCKS5_QUEUE)
from .items import (
... | """
scrapy pipelines for storing proxy ip infos.
"""
from twisted.internet.threads import deferToThread
from scrapy.exceptions import DropItem
from ..utils import get_redis_conn
from ..config.settings import (
REDIS_DB, DATA_ALL,
INIT_HTTP_QUEUE, INIT_SOCKS4_QUEUE,
INIT_SOCKS5_QUEUE)
from .items import (
... |
31,138 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/pipelines.py | 83,84 | 47,88 | _process_speed_item | ProxyCommonPipeline | 84,88 | 84,88 | class ProxyCommonPipeline(BasePipeline):
def _process_item(self, item, spider):
if isinstance(item, ProxyScoreItem):
self._process_score_item(item, spider)
if isinstance(item, ProxyVerifiedTimeItem):
self._process_verified_item(item, spider)
if isinstance(item, ProxyS... | class ProxyCommonPipeline(BasePipeline):
def _process_item(self, item, spider):
if isinstance(item, ProxyScoreItem):
self._process_score_item(item, spider)
if isinstance(item, ProxyVerifiedTimeItem):
self._process_verified_item(item, spider)
if isinstance(item, ProxyS... | if item['incr'] == '-inf' or item['incr'] < 0:
raise DropItem('item verification has failed')
self.redis_con.zadd(item['queue'], item['response_time'], item['url'])
| if item['incr'] == '-inf' or item['incr'] < 0:
raise DropItem('item verification has failed')
self.redis_con.zadd(item['queue'], item['response_time'], item['url'])
| 16 | 530 | 63 | 593 | """
scrapy pipelines for storing proxy ip infos.
"""
from twisted.internet.threads import deferToThread
from scrapy.exceptions import DropItem
from ..utils import get_redis_conn
from ..config.settings import (
REDIS_DB, DATA_ALL,
INIT_HTTP_QUEUE, INIT_SOCKS4_QUEUE,
INIT_SOCKS5_QUEUE)
from .items import (
... | """
scrapy pipelines for storing proxy ip infos.
"""
from twisted.internet.threads import deferToThread
from scrapy.exceptions import DropItem
from ..utils import get_redis_conn
from ..config.settings import (
REDIS_DB, DATA_ALL,
INIT_HTTP_QUEUE, INIT_SOCKS4_QUEUE,
INIT_SOCKS5_QUEUE)
from .items import (
... |
31,139 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/pipelines.py | 29,30 | 28,47 | _process_item | ProxyIPPipeline | 30,47 | 30,47 | class ProxyIPPipeline(BasePipeline):
def _process_item(self, item, spider):
FILL_FUNC_BODY | class ProxyIPPipeline(BasePipeline):
def _process_item(self, item, spider):
FILL_FUNC_BODY | url = item.get('url', None)
if not url:
return item
pipeline = self.redis_con.pipeline()
not_exists = pipeline.sadd(DATA_ALL, url)
if not_exists:
if 'socks4' in url:
pipeline.rpush(INIT_SOCKS4_QUEUE, url)
elif 'socks5' in url:
... | url = item.get('url', None)
if not url:
return item
pipeline = self.redis_con.pipeline()
not_exists = pipeline.sadd(DATA_ALL, url)
if not_exists:
if 'socks4' in url:
pipeline.rpush(INIT_SOCKS4_QUEUE, url)
elif 'socks5' in url:
... | 36 | 37 | 173 | 210 | """
scrapy pipelines for storing proxy ip infos.
"""
from twisted.internet.threads import deferToThread
from scrapy.exceptions import DropItem
from ..utils import get_redis_conn
from ..config.settings import (
REDIS_DB, DATA_ALL,
INIT_HTTP_QUEUE, INIT_SOCKS4_QUEUE,
INIT_SOCKS5_QUEUE)
from .items import (
... | """
scrapy pipelines for storing proxy ip infos.
"""
from twisted.internet.threads import deferToThread
from scrapy.exceptions import DropItem
from ..utils import get_redis_conn
from ..config.settings import (
REDIS_DB, DATA_ALL,
INIT_HTTP_QUEUE, INIT_SOCKS4_QUEUE,
INIT_SOCKS5_QUEUE)
from .items import (
... |
31,140 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/spiders/ajax_gfw_spider.py | 34,35 | 10,51 | parse_free_proxy | AjaxGFWSpider | 35,51 | 35,51 | class AjaxGFWSpider(BaseSpider, RedisAjaxSpider):
name = 'ajax_gfw'
proxy_mode = 2
task_queue = SPIDER_AJAX_GFW_TASK
def __init__(self):
super().__init__()
self.parser_maps.setdefault('cnproxy', self.parse_cnproxy)
self.parser_maps.setdefault('free-proxy', self.parse_free_proxy)... | class AjaxGFWSpider(BaseSpider, RedisAjaxSpider):
name = 'ajax_gfw'
proxy_mode = 2
task_queue = SPIDER_AJAX_GFW_TASK
def __init__(self):
super().__init__()
self.parser_maps.setdefault('cnproxy', self.parse_cnproxy)
self.parser_maps.setdefault('free-proxy', self.parse_free_proxy)... | items = list()
infos = response.xpath('//table[@id="proxy_list"]').css('tr')[1:]
for info in infos:
info_str = info.extract()
ip = info.css('abbr::text').extract_first()
port = info.css('.fport::text').extract_first()
if not ip or not port:
... | items = list()
infos = response.xpath('//table[@id="proxy_list"]').css('tr')[1:]
for info in infos:
info_str = info.extract()
ip = info.css('abbr::text').extract_first()
port = info.css('.fport::text').extract_first()
if not ip or not port:
... | 38 | 302 | 184 | 486 | """
Ajax gfw proxy ip crawler with scrapy-splash
"""
from haipproxy.config.settings import SPIDER_AJAX_GFW_TASK
from ..redis_spiders import RedisAjaxSpider
from ..items import ProxyUrlItem
from .base import BaseSpider
class AjaxGFWSpider(BaseSpider, RedisAjaxSpider):
name = 'ajax_gfw'
proxy_mode = 2
task_... | """
Ajax gfw proxy ip crawler with scrapy-splash
"""
from haipproxy.config.settings import SPIDER_AJAX_GFW_TASK
from ..redis_spiders import RedisAjaxSpider
from ..items import ProxyUrlItem
from .base import BaseSpider
class AjaxGFWSpider(BaseSpider, RedisAjaxSpider):
name = 'ajax_gfw'
proxy_mode = 2
task_... |
31,141 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/spiders/ajax_spider.py | 18,19 | 10,34 | parse_goubanjia | AjaxSpider | 19,34 | 19,34 | class AjaxSpider(BaseSpider, RedisAjaxSpider):
name = 'ajax'
task_queue = SPIDER_AJAX_TASK
def __init__(self):
super().__init__()
self.parser_maps.setdefault('goubanjia', self.parse_goubanjia)
def parse_goubanjia(self, response):
FILL_FUNC_BODY | class AjaxSpider(BaseSpider, RedisAjaxSpider):
name = 'ajax'
task_queue = SPIDER_AJAX_TASK
def __init__(self):
super().__init__()
self.parser_maps.setdefault('goubanjia', self.parse_goubanjia)
def parse_goubanjia(self, response):
FILL_FUNC_BODY | infos = response.xpath('//tr')[1:]
items = list()
for info in infos:
proxy_detail = info.xpath('td[1]//*[name(.)!="p"]/text()').extract()
ip = "".join(proxy_detail[:-1])
port = proxy_detail[-1]
protocols = self.procotol_extractor(info.extract())
... | infos = response.xpath('//tr')[1:]
items = list()
for info in infos:
proxy_detail = info.xpath('td[1]//*[name(.)!="p"]/text()').extract()
ip = "".join(proxy_detail[:-1])
port = proxy_detail[-1]
protocols = self.procotol_extractor(info.extract())
... | 31 | 111 | 163 | 274 | """
Ajax proxy ip crawler with scrapy-splash
"""
from haipproxy.config.settings import SPIDER_AJAX_TASK
from ..redis_spiders import RedisAjaxSpider
from ..items import ProxyUrlItem
from .base import BaseSpider
class AjaxSpider(BaseSpider, RedisAjaxSpider):
name = 'ajax'
task_queue = SPIDER_AJAX_TASK
def ... | """
Ajax proxy ip crawler with scrapy-splash
"""
from haipproxy.config.settings import SPIDER_AJAX_TASK
from ..redis_spiders import RedisAjaxSpider
from ..items import ProxyUrlItem
from .base import BaseSpider
class AjaxSpider(BaseSpider, RedisAjaxSpider):
name = 'ajax'
task_queue = SPIDER_AJAX_TASK
def ... |
31,142 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/spiders/base.py | 164,165 | 11,203 | procotol_extractor | BaseSpider | 166,177 | 165,177 | class BaseSpider:
default_protocols = ['http']
# slow down each spider
custom_settings = {
'CONCURRENT_REQUESTS_PER_DOMAIN': 5,
'DOWNLOAD_DELAY': 3,
'EXTENSIONS': {
'haipproxy.crawler.extensions.FailLogger': 500,
},
'DOWNLOADER_MIDDLEWARES': {
... | class BaseSpider:
default_protocols = ['http']
# slow down each spider
custom_settings = {
'CONCURRENT_REQUESTS_PER_DOMAIN': 5,
'DOWNLOAD_DELAY': 3,
'EXTENSIONS': {
'haipproxy.crawler.extensions.FailLogger': 500,
},
'DOWNLOADER_MIDDLEWARES': {
... | detail = detail.lower()
if 'socks5' in detail:
protocols = ['socks5']
elif 'socks4/5' in detail:
protocols = ['socks4', 'socks5']
elif 'socks4' in detail:
protocols = ['socks4']
else:
protocols = self.default_protocols
retur... | """extract http protocol,default value is http"""
detail = detail.lower()
if 'socks5' in detail:
protocols = ['socks5']
elif 'socks4/5' in detail:
protocols = ['socks4', 'socks5']
elif 'socks4' in detail:
protocols = ['socks4']
else:
... | 31 | 1,821 | 106 | 1,927 | """
Useful base class for all spiders.
"""
import json
import ipaddress
from haipproxy.config.rules import CRAWLER_TASKS
from ..items import ProxyUrlItem
class BaseSpider:
default_protocols = ['http']
# slow down each spider
custom_settings = {
'CONCURRENT_REQUESTS_PER_DOMAIN': 5,
'DOWNLO... | """
Useful base class for all spiders.
"""
import json
import ipaddress
from haipproxy.config.rules import CRAWLER_TASKS
from ..items import ProxyUrlItem
class BaseSpider:
default_protocols = ['http']
# slow down each spider
custom_settings = {
'CONCURRENT_REQUESTS_PER_DOMAIN': 5,
'DOWNLO... |
31,143 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/spiders/common_spider.py | 19,20 | 11,39 | parse_my_proxy | CommonSpider | 20,39 | 20,39 | class CommonSpider(BaseSpider, RedisSpider):
name = 'common'
task_queue = SPIDER_COMMON_TASK
def __init__(self):
super().__init__()
self.parser_maps.setdefault('myproxy', self.parse_my_proxy)
def parse_my_proxy(self, response):
FILL_FUNC_BODY | class CommonSpider(BaseSpider, RedisSpider):
name = 'common'
task_queue = SPIDER_COMMON_TASK
def __init__(self):
super().__init__()
self.parser_maps.setdefault('myproxy', self.parse_my_proxy)
def parse_my_proxy(self, response):
FILL_FUNC_BODY | protocols = None
if self.exists(response.url, 'socks-4'):
protocols = ['socks4']
if self.exists(response.url, 'socks-5'):
protocols = ['socks5']
items = list()
infos = response.css('.list ::text').extract()
for info in infos:
if ':' no... | protocols = None
if self.exists(response.url, 'socks-4'):
protocols = ['socks4']
if self.exists(response.url, 'socks-5'):
protocols = ['socks5']
items = list()
infos = response.css('.list ::text').extract()
for info in infos:
if ':' no... | 63 | 100 | 216 | 316 | """
Basic proxy ip crawler.
"""
from haipproxy.config.settings import SPIDER_COMMON_TASK
from ..redis_spiders import RedisSpider
from ..items import ProxyUrlItem
from .base import BaseSpider
# notice multi inheritance order in python
class CommonSpider(BaseSpider, RedisSpider):
name = 'common'
task_queue = SP... | """
Basic proxy ip crawler.
"""
from haipproxy.config.settings import SPIDER_COMMON_TASK
from ..redis_spiders import RedisSpider
from ..items import ProxyUrlItem
from .base import BaseSpider
# notice multi inheritance order in python
class CommonSpider(BaseSpider, RedisSpider):
name = 'common'
task_queue = SP... |
31,144 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/spiders/gfw_spider.py | 35,36 | 12,56 | parse_xroxy | GFWSpider | 36,56 | 36,56 | class GFWSpider(CommonSpider):
name = 'gfw'
proxy_mode = 2
task_queue = SPIDER_GFW_TASK
def __init__(self):
super().__init__()
self.parser_maps.setdefault('xroxy', self.parse_xroxy)
self.parser_maps.setdefault('gather_proxy', self.parse_gather_proxy)
def parse_gather_proxy(... | class GFWSpider(CommonSpider):
name = 'gfw'
proxy_mode = 2
task_queue = SPIDER_GFW_TASK
def __init__(self):
super().__init__()
self.parser_maps.setdefault('xroxy', self.parse_xroxy)
self.parser_maps.setdefault('gather_proxy', self.parse_gather_proxy)
def parse_gather_proxy(... | items = list()
ip_extract_pattern = '">(.*)\\n'
infos = response.xpath('//tr').css('.row1') + response.xpath('//tr').css('.row0')
for info in infos:
m = re.search(ip_extract_pattern, info.css('a')[1].extract())
if m:
ip = m.group(1)
... | items = list()
ip_extract_pattern = '">(.*)\\n'
infos = response.xpath('//tr').css('.row1') + response.xpath('//tr').css('.row0')
for info in infos:
m = re.search(ip_extract_pattern, info.css('a')[1].extract())
if m:
ip = m.group(1)
... | 59 | 279 | 310 | 589 | """
Proxy spider for the websites blocked by gfw.
"""
import re
import json
from haipproxy.config.settings import SPIDER_GFW_TASK
from ..items import ProxyUrlItem
from .common_spider import CommonSpider
class GFWSpider(CommonSpider):
name = 'gfw'
proxy_mode = 2
task_queue = SPIDER_GFW_TASK
def __ini... | """
Proxy spider for the websites blocked by gfw.
"""
import re
import json
from haipproxy.config.settings import SPIDER_GFW_TASK
from ..items import ProxyUrlItem
from .common_spider import CommonSpider
class GFWSpider(CommonSpider):
name = 'gfw'
proxy_mode = 2
task_queue = SPIDER_GFW_TASK
def __ini... |
31,145 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/user_agents.py | 24,26 | 14,32 | get_ua | FakeChromeUA | 27,32 | 26,32 | class FakeChromeUA:
"""Fake UA Factory"""
os_type = [
'(Windows NT 6.1; WOW64)', '(Windows NT 10.0; WOW64)',
'(X11; Linux x86_64)',
'(Macintosh; Intel Mac OS X 10_12_6)'
]
chrome_version = 'Chrome/{}.0.{}.{}'.format(FIRST_NUM, THIRD_NUM, FOURTH_NUM)
@classmethod
def get... | class FakeChromeUA:
"""Fake UA Factory"""
os_type = [
'(Windows NT 6.1; WOW64)', '(Windows NT 10.0; WOW64)',
'(X11; Linux x86_64)',
'(Macintosh; Intel Mac OS X 10_12_6)'
]
chrome_version = 'Chrome/{}.0.{}.{}'.format(FIRST_NUM, THIRD_NUM, FOURTH_NUM)
@classmethod
def get... | return ' '.join(
['Mozilla/5.0', random.choice(cls.os_type),
'AppleWebKit/537.36',
'(KHTML, like Gecko)',
cls.chrome_version, 'Safari/537.36'])
| """return fack ua"""
return ' '.join(
['Mozilla/5.0', random.choice(cls.os_type),
'AppleWebKit/537.36',
'(KHTML, like Gecko)',
cls.chrome_version, 'Safari/537.36'])
| 11 | 169 | 81 | 250 | """
This module provides fake ua for all spiders.
"""
import random
__all__ = ['FakeChromeUA']
FIRST_NUM = random.randint(55, 62)
THIRD_NUM = random.randint(0, 3200)
FOURTH_NUM = random.randint(0, 140)
class FakeChromeUA:
"""Fake UA Factory"""
os_type = [
'(Windows NT 6.1; WOW64)', '(Windows NT 10.... | """
This module provides fake ua for all spiders.
"""
import random
__all__ = ['FakeChromeUA']
FIRST_NUM = random.randint(55, 62)
THIRD_NUM = random.randint(0, 3200)
FOURTH_NUM = random.randint(0, 140)
class FakeChromeUA:
"""Fake UA Factory"""
os_type = [
'(Windows NT 6.1; WOW64)', '(Windows NT 10.... |
31,146 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/validators/base.py | 58,59 | 15,84 | parse_error | BaseValidator | 59,72 | 59,72 | class BaseValidator:
"""base validator for all the validators"""
name = 'base'
init_score = 5
# slow down each spider
custom_settings = {
'CONCURRENT_REQUESTS': 50,
'CONCURRENT_REQUESTS_PER_DOMAIN': 50,
'RETRY_ENABLED': False,
'DOWNLOADER_MIDDLEWARES': {
'... | class BaseValidator:
"""base validator for all the validators"""
name = 'base'
init_score = 5
# slow down each spider
custom_settings = {
'CONCURRENT_REQUESTS': 50,
'CONCURRENT_REQUESTS_PER_DOMAIN': 50,
'RETRY_ENABLED': False,
'DOWNLOADER_MIDDLEWARES': {
'... | request = failure.request
proxy = request.meta.get('proxy')
# crawler_logger.error('proxy {} has failed, {} is raised'.format(proxy, failure))
print('proxy {} has been failed,{} is raised'.format(proxy, failure))
if failure.check(TimeoutError, TCPTimedOutError):
decr ... | request = failure.request
proxy = request.meta.get('proxy')
# crawler_logger.error('proxy {} has failed, {} is raised'.format(proxy, failure))
print('proxy {} has been failed,{} is raised'.format(proxy, failure))
if failure.check(TimeoutError, TCPTimedOutError):
decr ... | 45 | 635 | 152 | 787 | """
Useful base class for all the validators.
"""
import time
from twisted.internet.error import (
TimeoutError, TCPTimedOutError)
# from logger import crawler_logger
from ..items import (
ProxyScoreItem, ProxyVerifiedTimeItem,
ProxySpeedItem)
class BaseValidator:
"""base validator for all the valid... | """
Useful base class for all the validators.
"""
import time
from twisted.internet.error import (
TimeoutError, TCPTimedOutError)
# from logger import crawler_logger
from ..items import (
ProxyScoreItem, ProxyVerifiedTimeItem,
ProxySpeedItem)
class BaseValidator:
"""base validator for all the valid... |
31,147 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/crawler/validators/httpbin.py | 53,54 | 28,83 | is_transparent | HttpBinInitValidator | 55,66 | 54,66 | class HttpBinInitValidator(BaseValidator, ValidatorRedisSpider):
"""This validator does initial work for ip resources.
It will filter transparent ip and store proxies in http_task
and https_tasks
"""
name = 'init'
urls = [
'http://httpbin.org/ip',
'https://httpbin.org/ip',
... | class HttpBinInitValidator(BaseValidator, ValidatorRedisSpider):
"""This validator does initial work for ip resources.
It will filter transparent ip and store proxies in http_task
and https_tasks
"""
name = 'init'
urls = [
'http://httpbin.org/ip',
'https://httpbin.org/ip',
... | if not response.body_as_unicode():
return True
try:
ip = json.loads(response.body_as_unicode()).get('origin')
if self.origin_ip in ip:
return True
except (AttributeError, JSONDecodeError):
return True
return False
| """filter transparent ip resources"""
if not response.body_as_unicode():
return True
try:
ip = json.loads(response.body_as_unicode()).get('origin')
if self.origin_ip in ip:
return True
except (AttributeError, JSONDecodeError):
... | 22 | 539 | 91 | 630 | """
We use this validator to filter transparent ips, and give the ip resources an
initial score.
"""
import time
import json
from json.decoder import JSONDecodeError
import requests
from haipproxy.config.rules import (
SPEED_MAPS, TTL_MAPS,
SCORE_MAPS, HTTP_TASKS,
HTTPS_TASKS)
from haipproxy.config.settin... | """
We use this validator to filter transparent ips, and give the ip resources an
initial score.
"""
import time
import json
from json.decoder import JSONDecodeError
import requests
from haipproxy.config.rules import (
SPEED_MAPS, TTL_MAPS,
SCORE_MAPS, HTTP_TASKS,
HTTPS_TASKS)
from haipproxy.config.settin... |
31,148 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/monitor/exporter.py | 55,56 | 1,64 | exporter_start | 56,64 | 56,64 | import time
from prometheus_client import start_http_server
from prometheus_client.core import (
CounterMetricFamily, GaugeMetricFamily,
REGISTRY
)
from haipproxy.config.settings import (
DATA_ALL, INIT_HTTP_QUEUE,
SPIDER_COMMON_TASK, SPIDER_AJAX_TASK,
SPIDER_GFW_TASK, SPIDER_AJAX_GFW_TASK,
TE... | import time
from prometheus_client import start_http_server
from prometheus_client.core import (
CounterMetricFamily, GaugeMetricFamily,
REGISTRY
)
from haipproxy.config.settings import (
DATA_ALL, INIT_HTTP_QUEUE,
SPIDER_COMMON_TASK, SPIDER_AJAX_TASK,
SPIDER_GFW_TASK, SPIDER_AJAX_GFW_TASK,
TE... | print('starting server http://{}:{}/metrics'.format(
EXPORTER_LISTEN_HOST, EXPORTER_LISTEN_PORT))
REGISTRY.register(CustomCollector())
start_http_server(EXPORTER_LISTEN_PORT, addr=EXPORTER_LISTEN_HOST)
while True:
time.sleep(5)
| print('starting server http://{}:{}/metrics'.format(
EXPORTER_LISTEN_HOST, EXPORTER_LISTEN_PORT))
REGISTRY.register(CustomCollector())
start_http_server(EXPORTER_LISTEN_PORT, addr=EXPORTER_LISTEN_HOST)
while True:
time.sleep(5)
| 11 | 904 | 109 | 1,013 | import time
from prometheus_client import start_http_server
from prometheus_client.core import (
CounterMetricFamily, GaugeMetricFamily,
REGISTRY
)
from haipproxy.config.settings import (
DATA_ALL, INIT_HTTP_QUEUE,
SPIDER_COMMON_TASK, SPIDER_AJAX_TASK,
SPIDER_GFW_TASK, SPIDER_AJAX_GFW_TASK,
TE... | import time
from prometheus_client import start_http_server
from prometheus_client.core import (
CounterMetricFamily, GaugeMetricFamily,
REGISTRY
)
from haipproxy.config.settings import (
DATA_ALL, INIT_HTTP_QUEUE,
SPIDER_COMMON_TASK, SPIDER_AJAX_TASK,
SPIDER_GFW_TASK, SPIDER_AJAX_GFW_TASK,
TE... | |
31,149 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/monitor/exporter.py | 25,26 | 21,55 | collect | CustomCollector | 26,55 | 26,55 | class CustomCollector:
def __init__(self):
self.conn = get_redis_conn()
def collect(self):
FILL_FUNC_BODY | class CustomCollector:
def __init__(self):
self.conn = get_redis_conn()
def collect(self):
FILL_FUNC_BODY | start_time = int(time.time()) - TTL_VALIDATED_RESOURCE * 60
pipe = self.conn.pipeline(False)
pipe.scard(DATA_ALL)
pipe.llen(INIT_HTTP_QUEUE)
pipe.scard(TEMP_ZHIHU_QUEUE)
pipe.zrevrangebyscore(VALIDATED_ZHIHU_QUEUE, '+inf', LOWEST_SCORE)
pipe.zrevrangebyscore(TTL_... | start_time = int(time.time()) - TTL_VALIDATED_RESOURCE * 60
pipe = self.conn.pipeline(False)
pipe.scard(DATA_ALL)
pipe.llen(INIT_HTTP_QUEUE)
pipe.scard(TEMP_ZHIHU_QUEUE)
pipe.zrevrangebyscore(VALIDATED_ZHIHU_QUEUE, '+inf', LOWEST_SCORE)
pipe.zrevrangebyscore(TTL_... | 104 | 45 | 631 | 676 | import time
from prometheus_client import start_http_server
from prometheus_client.core import (
CounterMetricFamily, GaugeMetricFamily,
REGISTRY
)
from haipproxy.config.settings import (
DATA_ALL, INIT_HTTP_QUEUE,
SPIDER_COMMON_TASK, SPIDER_AJAX_TASK,
SPIDER_GFW_TASK, SPIDER_AJAX_GFW_TASK,
TE... | import time
from prometheus_client import start_http_server
from prometheus_client.core import (
CounterMetricFamily, GaugeMetricFamily,
REGISTRY
)
from haipproxy.config.settings import (
DATA_ALL, INIT_HTTP_QUEUE,
SPIDER_COMMON_TASK, SPIDER_AJAX_TASK,
SPIDER_GFW_TASK, SPIDER_AJAX_GFW_TASK,
TE... |
31,150 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/utils/functools.py | 6,7 | 1,9 | decode_all | 8,9 | 7,9 | """
This module provides useful functions.
"""
def decode_all(res):
FILL_FUNC_BODY | """
This module provides useful functions.
"""
def decode_all(res):
"""decode all results fetched from redis"""
FILL_FUNC_BODY | return list(map(bytes.decode, res)) | """decode all results fetched from redis"""
return list(map(bytes.decode, res)) | 3 | 44 | 13 | 57 | """
This module provides useful functions.
"""
def decode_all(res):
FILL_FUNC_BODY | """
This module provides useful functions.
"""
def decode_all(res):
"""decode all results fetched from redis"""
FILL_FUNC_BODY | |
31,151 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/haipproxy/utils/redis_util.py | 19,20 | 1,54 | acquire_lock | 21,35 | 20,35 | import uuid
import time
import redis
from haipproxy.config.settings import (
REDIS_HOST, REDIS_PORT, REDIS_DB,
REDIS_PASSWORD, LOCKER_PREFIX)
def get_redis_conn(**kwargs):
host = kwargs.get('host', REDIS_HOST)
port = kwargs.get('port', REDIS_PORT)
db = kwargs.get('db', REDIS_DB)
password = k... | import uuid
import time
import redis
from haipproxy.config.settings import (
REDIS_HOST, REDIS_PORT, REDIS_DB,
REDIS_PASSWORD, LOCKER_PREFIX)
def get_redis_conn(**kwargs):
host = kwargs.get('host', REDIS_HOST)
port = kwargs.get('port', REDIS_PORT)
db = kwargs.get('db', REDIS_DB)
password = k... | identifier = str(uuid.uuid4())
lock_name = LOCKER_PREFIX + lock_name
end = time.time() + acquire_timeout
while time.time() < end:
if conn.set(lock_name, identifier, lock_timeout, nx=True):
return identifier
elif not conn.ttl(lock_name) or conn.ttl(lock_name) == -1:
... | """inspired by the book 'redis in action' """
identifier = str(uuid.uuid4())
lock_name = LOCKER_PREFIX + lock_name
end = time.time() + acquire_timeout
while time.time() < end:
if conn.set(lock_name, identifier, lock_timeout, nx=True):
return identifier
elif not conn.ttl(... | 36 | 363 | 149 | 512 | import uuid
import time
import redis
from haipproxy.config.settings import (
REDIS_HOST, REDIS_PORT, REDIS_DB,
REDIS_PASSWORD, LOCKER_PREFIX)
def get_redis_conn(**kwargs):
host = kwargs.get('host', REDIS_HOST)
port = kwargs.get('port', REDIS_PORT)
db = kwargs.get('db', REDIS_DB)
password = k... | import uuid
import time
import redis
from haipproxy.config.settings import (
REDIS_HOST, REDIS_PORT, REDIS_DB,
REDIS_PASSWORD, LOCKER_PREFIX)
def get_redis_conn(**kwargs):
host = kwargs.get('host', REDIS_HOST)
port = kwargs.get('port', REDIS_PORT)
db = kwargs.get('db', REDIS_DB)
password = k... | |
31,152 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_haipproxy/haipproxy/setup.py | 16,17 | 1,50 | read_requirements | 17,21 | 17,21 | from os import path as os_path
from setuptools import setup
import haipproxy
this_directory = os_path.abspath(os_path.dirname(__file__))
def read_file(filename):
with open(os_path.join(this_directory, filename), encoding='utf-8') as f:
long_description = f.read()
return long_description
def read_... | from os import path as os_path
from setuptools import setup
import haipproxy
this_directory = os_path.abspath(os_path.dirname(__file__))
def read_file(filename):
with open(os_path.join(this_directory, filename), encoding='utf-8') as f:
long_description = f.read()
return long_description
def read_... | return [line.strip() for line in read_file(filename).splitlines()
if not line.startswith('#')]
| return [line.strip() for line in read_file(filename).splitlines()
if not line.startswith('#')]
| 9 | 432 | 38 | 470 | from os import path as os_path
from setuptools import setup
import haipproxy
this_directory = os_path.abspath(os_path.dirname(__file__))
def read_file(filename):
with open(os_path.join(this_directory, filename), encoding='utf-8') as f:
long_description = f.read()
return long_description
def read_... | from os import path as os_path
from setuptools import setup
import haipproxy
this_directory = os_path.abspath(os_path.dirname(__file__))
def read_file(filename):
with open(os_path.join(this_directory, filename), encoding='utf-8') as f:
long_description = f.read()
return long_description
def read_... | |
31,153 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/admin/weibo_admin/view.py | 4,5 | 1,9 | index | 5,9 | 5,9 | from django.shortcuts import redirect
def index(request):
FILL_FUNC_BODY | from django.shortcuts import redirect
def index(request):
FILL_FUNC_BODY | if not request.user.is_authenticated():
return redirect('/admin/login/?next=%s' % request.path)
else:
return redirect('/admin/') | if not request.user.is_authenticated():
return redirect('/admin/login/?next=%s' % request.path)
else:
return redirect('/admin/') | 10 | 27 | 49 | 76 | from django.shortcuts import redirect
def index(request):
FILL_FUNC_BODY | from django.shortcuts import redirect
def index(request):
FILL_FUNC_BODY | |
31,154 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/admin/weibo_data/admin.py | 12,13 | 6,24 | has_add_permission | ReadOnlyModelAdmin | 13,15 | 13,15 | class ReadOnlyModelAdmin(admin.ModelAdmin):
actions = None
def get_readonly_fields(self, request, obj=None):
return self.fields or [f.name for f in self.model._meta.fields]
def has_add_permission(self, request):
FILL_FUNC_BODY def has_change_permission(self, request, obj=None):
if reque... | class ReadOnlyModelAdmin(admin.ModelAdmin):
actions = None
def get_readonly_fields(self, request, obj=None):
return self.fields or [f.name for f in self.model._meta.fields]
def has_add_permission(self, request):
FILL_FUNC_BODY def has_change_permission(self, request, obj=None):
if reque... | return False
| return False
| 2 | 157 | 7 | 164 | from django.contrib import admin
from .models import WbUser, WeiboData
class ReadOnlyModelAdmin(admin.ModelAdmin):
actions = None
def get_readonly_fields(self, request, obj=None):
return self.fields or [f.name for f in self.model._meta.fields]
def has_add_permission(self, request):
FILL_FUNC_BO... | from django.contrib import admin
from .models import WbUser, WeiboData
class ReadOnlyModelAdmin(admin.ModelAdmin):
actions = None
def get_readonly_fields(self, request, obj=None):
return self.fields or [f.name for f in self.model._meta.fields]
def has_add_permission(self, request):
FILL_FUNC_BO... |
31,155 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/config/conf.py | 60,61 | 1,130 | get_broker_and_backend | 61,78 | 61,78 | import os
import random
from pathlib import Path
from yaml import load
config_path = os.path.join(os.path.dirname(__file__), 'spider.yaml')
with open(config_path, encoding='utf-8') as f:
cont = f.read()
cf = load(cont)
def get_db_args():
return cf.get('db')
def get_redis_args():
return cf.get('redis... | import os
import random
from pathlib import Path
from yaml import load
config_path = os.path.join(os.path.dirname(__file__), 'spider.yaml')
with open(config_path, encoding='utf-8') as f:
cont = f.read()
cf = load(cont)
def get_db_args():
return cf.get('db')
def get_redis_args():
return cf.get('redis... | redis_info = cf.get('redis')
password = redis_info.get('password')
sentinel_args = redis_info.get('sentinel', '')
db = redis_info.get('broker', 5)
if sentinel_args:
broker_url = ";".join('sentinel://:{}@{}:{}/{}'.format(password, sentinel['host'], sentinel['port'], db) for
... | redis_info = cf.get('redis')
password = redis_info.get('password')
sentinel_args = redis_info.get('sentinel', '')
db = redis_info.get('broker', 5)
if sentinel_args:
broker_url = ";".join('sentinel://:{}@{}:{}/{}'.format(password, sentinel['host'], sentinel['port'], db) for
... | 54 | 760 | 272 | 1,032 | import os
import random
from pathlib import Path
from yaml import load
config_path = os.path.join(os.path.dirname(__file__), 'spider.yaml')
with open(config_path, encoding='utf-8') as f:
cont = f.read()
cf = load(cont)
def get_db_args():
return cf.get('db')
def get_redis_args():
return cf.get('redis... | import os
import random
from pathlib import Path
from yaml import load
config_path = os.path.join(os.path.dirname(__file__), 'spider.yaml')
with open(config_path, encoding='utf-8') as f:
cont = f.read()
cf = load(cont)
def get_db_args():
return cf.get('db')
def get_redis_args():
return cf.get('redis... | |
31,156 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/config/create_all.py | 11,12 | 1,17 | create_all_table | 12,15 | 12,15 | import sys
# to work well inside config module or outsize config module
sys.path.append('..')
sys.path.append('.')
from db.tables import *
from db.basic import metadata
def create_all_table():
FILL_FUNC_BODYif __name__ == "__main__":
create_all_table()
| import sys
# to work well inside config module or outsize config module
sys.path.append('..')
sys.path.append('.')
from db.tables import *
from db.basic import metadata
def create_all_table():
FILL_FUNC_BODYif __name__ == "__main__":
create_all_table()
| metadata.create_all()
| metadata.create_all()
| 1 | 88 | 13 | 101 | import sys
# to work well inside config module or outsize config module
sys.path.append('..')
sys.path.append('.')
from db.tables import *
from db.basic import metadata
def create_all_table():
FILL_FUNC_BODYif __name__ == "__main__":
create_all_table()
| import sys
# to work well inside config module or outsize config module
sys.path.append('..')
sys.path.append('.')
from db.tables import *
from db.basic import metadata
def create_all_table():
FILL_FUNC_BODYif __name__ == "__main__":
create_all_table()
| |
31,157 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/config/headers.py | 16,18 | 8,23 | get_ua | FakeChromeUA | 18,23 | 18,23 | class FakeChromeUA:
os_type = [
'(Windows NT 6.1; WOW64)', '(Windows NT 10.0; WOW64)', '(X11; Linux x86_64)',
'(Macintosh; Intel Mac OS X 10_12_6)'
]
chrome_version = 'Chrome/{}.0.{}.{}'.format(first_num, third_num, fourth_num)
@classmethod
def get_ua(cls... | class FakeChromeUA:
os_type = [
'(Windows NT 6.1; WOW64)', '(Windows NT 10.0; WOW64)', '(X11; Linux x86_64)',
'(Macintosh; Intel Mac OS X 10_12_6)'
]
chrome_version = 'Chrome/{}.0.{}.{}'.format(first_num, third_num, fourth_num)
@classmethod
def get_ua(cls... | return ' '.join(['Mozilla/5.0', random.choice(cls.os_type), 'AppleWebKit/537.36',
'(KHTML, like Gecko)', cls.chrome_version, 'Safari/537.36']
)
| return ' '.join(['Mozilla/5.0', random.choice(cls.os_type), 'AppleWebKit/537.36',
'(KHTML, like Gecko)', cls.chrome_version, 'Safari/537.36']
)
| 11 | 144 | 79 | 223 | import random
first_num = random.randint(55, 62)
third_num = random.randint(0, 3200)
fourth_num = random.randint(0, 140)
class FakeChromeUA:
os_type = [
'(Windows NT 6.1; WOW64)', '(Windows NT 10.0; WOW64)', '(X11; Linux x86_64)',
'(Macintosh; Intel Mac OS X 10_12_6)'
... | import random
first_num = random.randint(55, 62)
third_num = random.randint(0, 3200)
fourth_num = random.randint(0, 140)
class FakeChromeUA:
os_type = [
'(Windows NT 6.1; WOW64)', '(Windows NT 10.0; WOW64)', '(X11; Linux x86_64)',
'(Macintosh; Intel Mac OS X 10_12_6)'
... |
31,158 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/db/basic.py | 11,12 | 1,28 | get_engine | 12,20 | 12,20 | import os
from sqlalchemy import (
create_engine, MetaData)
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from config import get_db_args
def get_engine():
FILL_FUNC_BODYeng = get_engine()
Base = declarative_base()
Session = sessionmaker(bind=eng)
db_session = Se... | import os
from sqlalchemy import (
create_engine, MetaData)
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from config import get_db_args
def get_engine():
FILL_FUNC_BODYeng = get_engine()
Base = declarative_base()
Session = sessionmaker(bind=eng)
db_session = Se... | args = get_db_args()
password = os.getenv('DB_PASS', args['password'])
connect_str = "{}+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4".format(args['db_type'], args['user'], password,
args['host'], args['port'], args['db_name'])
engine = create_eng... | args = get_db_args()
password = os.getenv('DB_PASS', args['password'])
connect_str = "{}+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4".format(args['db_type'], args['user'], password,
args['host'], args['port'], args['db_name'])
engine = create_eng... | 21 | 142 | 123 | 265 | import os
from sqlalchemy import (
create_engine, MetaData)
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from config import get_db_args
def get_engine():
FILL_FUNC_BODYeng = get_engine()
Base = declarative_base()
Session = sessionmaker(bind=eng)
db_session = Se... | import os
from sqlalchemy import (
create_engine, MetaData)
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from config import get_db_args
def get_engine():
FILL_FUNC_BODYeng = get_engine()
Base = declarative_base()
Session = sessionmaker(bind=eng)
db_session = Se... | |
31,159 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/db/redis_db.py | 76,78 | 50,171 | fetch_cookies_of_normal | Cookies | 78,96 | 78,96 | class Cookies(object):
@classmethod
def store_cookies(cls, name, cookies, proxy):
pickled_cookies = json.dumps(
{'cookies': cookies, 'loginTime': datetime.datetime.now().timestamp(), 'proxy': proxy})
cookies_con.hset('account', name, pickled_cookies)
cls.push_in_queue(name)
... | class Cookies(object):
@classmethod
def store_cookies(cls, name, cookies, proxy):
pickled_cookies = json.dumps(
{'cookies': cookies, 'loginTime': datetime.datetime.now().timestamp(), 'proxy': proxy})
cookies_con.hset('account', name, pickled_cookies)
cls.push_in_queue(name)
... | # look for available accounts
for i in range(cookies_con.llen('account_queue')):
name = cookies_con.lpop('account_queue').decode('utf-8')
# during the crawling, some cookies can be banned
# some account fetched from account_queue can be unavailable
j_accou... | # look for available accounts
for i in range(cookies_con.llen('account_queue')):
name = cookies_con.lpop('account_queue').decode('utf-8')
# during the crawling, some cookies can be banned
# some account fetched from account_queue can be unavailable
j_accou... | 58 | 1,112 | 223 | 1,335 | import json
import socket
import datetime
import redis
from redis.sentinel import Sentinel
from logger import crawler
from config import (
get_redis_args,
get_share_host_count,
get_running_mode,
get_cookie_expire_time
)
MODE = get_running_mode()
SHARE_HOST_COUNT = get_share_host_count()
REDIS_ARGS =... | import json
import socket
import datetime
import redis
from redis.sentinel import Sentinel
from logger import crawler
from config import (
get_redis_args,
get_share_host_count,
get_running_mode,
get_cookie_expire_time
)
MODE = get_running_mode()
SHARE_HOST_COUNT = get_share_host_count()
REDIS_ARGS =... |
31,160 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/db/redis_db.py | 187,189 | 178,194 | fetch_uid_by_name | IdNames | 189,194 | 189,194 | class IdNames(object):
@classmethod
def store_id_name(cls, user_name, user_id):
id_name_con.set(user_name, user_id)
@classmethod
def delele_id_name(cls, user_name):
id_name_con.delete(user_name)
@classmethod
def fetch_uid_by_name(cls, user_name):
FILL_FUNC_BODY | class IdNames(object):
@classmethod
def store_id_name(cls, user_name, user_id):
id_name_con.set(user_name, user_id)
@classmethod
def delele_id_name(cls, user_name):
id_name_con.delete(user_name)
@classmethod
def fetch_uid_by_name(cls, user_name):
FILL_FUNC_BODY | user_id = id_name_con.get(user_name)
cls.delele_id_name(user_name)
if user_id:
return user_id.decode('utf-8')
return ''
| user_id = id_name_con.get(user_name)
cls.delele_id_name(user_name)
if user_id:
return user_id.decode('utf-8')
return ''
| 10 | 119 | 64 | 183 | import json
import socket
import datetime
import redis
from redis.sentinel import Sentinel
from logger import crawler
from config import (
get_redis_args,
get_share_host_count,
get_running_mode,
get_cookie_expire_time
)
MODE = get_running_mode()
SHARE_HOST_COUNT = get_share_host_count()
REDIS_ARGS =... | import json
import socket
import datetime
import redis
from redis.sentinel import Sentinel
from logger import crawler
from config import (
get_redis_args,
get_share_host_count,
get_running_mode,
get_cookie_expire_time
)
MODE = get_running_mode()
SHARE_HOST_COUNT = get_share_host_count()
REDIS_ARGS =... |
31,161 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/db/redis_db.py | 172,174 | 171,178 | store_crawl_url | Urls | 174,178 | 174,178 | class Urls(object):
@classmethod
def store_crawl_url(cls, url, result):
FILL_FUNC_BODY | class Urls(object):
@classmethod
def store_crawl_url(cls, url, result):
FILL_FUNC_BODY | urls_con.set(url, result)
urls_con.expire(url, data_expire_time)
| urls_con.set(url, result)
urls_con.expire(url, data_expire_time)
| 4 | 39 | 38 | 77 | import json
import socket
import datetime
import redis
from redis.sentinel import Sentinel
from logger import crawler
from config import (
get_redis_args,
get_share_host_count,
get_running_mode,
get_cookie_expire_time
)
MODE = get_running_mode()
SHARE_HOST_COUNT = get_share_host_count()
REDIS_ARGS =... | import json
import socket
import datetime
import redis
from redis.sentinel import Sentinel
from logger import crawler
from config import (
get_redis_args,
get_share_host_count,
get_running_mode,
get_cookie_expire_time
)
MODE = get_running_mode()
SHARE_HOST_COUNT = get_share_host_count()
REDIS_ARGS =... |
31,162 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/login/cookies_gen.py | 38,39 | 1,99 | get_tid_and_c | 43,75 | 39,75 | import re
import json
import time
import random
from urllib import parse
import requests
from config import FakeChromeUA
from decorators import retry
from exceptions import CookieGenException
PASSPORT_URL = 'https://passport.weibo.com/visitor/visitor?entry=miniblog&a=enter&url={}&domain=.wei' \
'bo.co... | import re
import json
import time
import random
from urllib import parse
import requests
from config import FakeChromeUA
from decorators import retry
from exceptions import CookieGenException
PASSPORT_URL = 'https://passport.weibo.com/visitor/visitor?entry=miniblog&a=enter&url={}&domain=.wei' \
'bo.co... | fp = '{' + \
'"os":"1","browser":"{browser}","fonts":"undefined","screenInfo":"1436*752*24","plugins":"Portable ' \
'Document Format::internal-pdf-viewer::Chrome PDF Plugin|::mhjfbmdgcfjbbpaeojofohoefgiehjai::Chrome PDF Viewer' \
'|::internal-nacl-plugin::Native Client|Enables Widevine li... | """
get all args including tid、c and w
:return: tuple(tid, c, w)
"""
fp = '{' + \
'"os":"1","browser":"{browser}","fonts":"undefined","screenInfo":"1436*752*24","plugins":"Portable ' \
'Document Format::internal-pdf-viewer::Chrome PDF Plugin|::mhjfbmdgcfjbbpaeojofohoefgiehjai::Chro... | 104 | 875 | 468 | 1,343 | import re
import json
import time
import random
from urllib import parse
import requests
from config import FakeChromeUA
from decorators import retry
from exceptions import CookieGenException
PASSPORT_URL = 'https://passport.weibo.com/visitor/visitor?entry=miniblog&a=enter&url={}&domain=.wei' \
'bo.co... | import re
import json
import time
import random
from urllib import parse
import requests
from config import FakeChromeUA
from decorators import retry
from exceptions import CookieGenException
PASSPORT_URL = 'https://passport.weibo.com/visitor/visitor?entry=miniblog&a=enter&url={}&domain=.wei' \
'bo.co... | |
31,164 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/page_get/basic.py | 40,43 | 1,114 | get_page | 50,114 | 43,114 | import os
import time
import signal
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from config import headers
from logger import crawler
from login import get_cookies
from db.dao import LoginInfoOper
from utils import (send_email, getip)
from db.redis_db import (
Urls, Coo... | import os
import time
import signal
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from config import headers
from logger import crawler
from login import get_cookies
from db.dao import LoginInfoOper
from utils import (send_email, getip)
from db.redis_db import (
Urls, Coo... | crawler.info('the crawling url is {url}'.format(url=url))
count = 0
while count < MAX_RETRIES:
if auth_level == 2:
name_cookies = Cookies.fetch_cookies()
if name_cookies is None:
crawler.warning('No cookie in cookies pool. Maybe all accounts are banned, or a... | """
:param url: url to crawl
:param auth_level: 0 stands for need nothing,1 stands for no login but need cookies,2 stands for need login.
:param is_ajax: whether the request is ajax
:param need_proxy: whether the request need a http/https proxy
:return: response text, when a exception is raised,... | 215 | 461 | 820 | 1,281 | import os
import time
import signal
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from config import headers
from logger import crawler
from login import get_cookies
from db.dao import LoginInfoOper
from utils import (send_email, getip)
from db.redis_db import (
Urls, Coo... | import os
import time
import signal
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from config import headers
from logger import crawler
from login import get_cookies
from db.dao import LoginInfoOper
from utils import (send_email, getip)
from db.redis_db import (
Urls, Coo... | |
31,165 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/page_get/status.py | 10,11 | 1,28 | get_cont_of_weibo | 15,28 | 11,28 | import json
from utils import text_filter
from .basic import get_page
BASE_URL = 'https://weibo.com/p/aj/mblog/getlongtext?mid={}'
def get_cont_of_weibo(mid):
FILL_FUNC_BODY | import json
from utils import text_filter
from .basic import get_page
BASE_URL = 'https://weibo.com/p/aj/mblog/getlongtext?mid={}'
def get_cont_of_weibo(mid):
"""
:param mid: weibo's mid
:return: all cont of the weibo
"""
FILL_FUNC_BODY | url = BASE_URL.format(mid)
html = get_page(url, auth_level=2, is_ajax=True) # 这个接口需要先登录
if html:
try:
html = json.loads(html, encoding='utf-8').get('data').get('html')
cont = text_filter(html)
except AttributeError:
cont = ''
return cont
el... | """
:param mid: weibo's mid
:return: all cont of the weibo
"""
url = BASE_URL.format(mid)
html = get_page(url, auth_level=2, is_ajax=True) # 这个接口需要先登录
if html:
try:
html = json.loads(html, encoding='utf-8').get('data').get('html')
cont = text_filter(html)
... | 30 | 107 | 129 | 236 | import json
from utils import text_filter
from .basic import get_page
BASE_URL = 'https://weibo.com/p/aj/mblog/getlongtext?mid={}'
def get_cont_of_weibo(mid):
FILL_FUNC_BODY | import json
from utils import text_filter
from .basic import get_page
BASE_URL = 'https://weibo.com/p/aj/mblog/getlongtext?mid={}'
def get_cont_of_weibo(mid):
"""
:param mid: weibo's mid
:return: all cont of the weibo
"""
FILL_FUNC_BODY | |
31,166 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/page_parse/basic.py | 26,28 | 1,53 | is_403 | 28,49 | 28,49 | from bs4 import BeautifulSoup
from decorators import parse_decorator
@parse_decorator(False)
def is_404(html):
soup = BeautifulSoup(html, 'html.parser')
try:
# request is redirected by js code
if "http://weibo.com/sorry?pagenotfound" in html:
return True
elif soup.title.te... | from bs4 import BeautifulSoup
from decorators import parse_decorator
@parse_decorator(False)
def is_404(html):
soup = BeautifulSoup(html, 'html.parser')
try:
# request is redirected by js code
if "http://weibo.com/sorry?pagenotfound" in html:
return True
elif soup.title.te... | if "['uid']" not in html and "['nick']" not in html and "['islogin']='1'" in html:
return True
if 'Sina Visitor System' in html:
return True
# verify code for search page
# todo solve the problem of verify_code when searching
if 'yzm_img' in html and 'yzm_input' in html:
r... | if "['uid']" not in html and "['nick']" not in html and "['islogin']='1'" in html:
return True
if 'Sina Visitor System' in html:
return True
# verify code for search page
# todo solve the problem of verify_code when searching
if 'yzm_img' in html and 'yzm_input' in html:
r... | 71 | 234 | 200 | 434 | from bs4 import BeautifulSoup
from decorators import parse_decorator
@parse_decorator(False)
def is_404(html):
soup = BeautifulSoup(html, 'html.parser')
try:
# request is redirected by js code
if "http://weibo.com/sorry?pagenotfound" in html:
return True
elif soup.title.te... | from bs4 import BeautifulSoup
from decorators import parse_decorator
@parse_decorator(False)
def is_404(html):
soup = BeautifulSoup(html, 'html.parser')
try:
# request is redirected by js code
if "http://weibo.com/sorry?pagenotfound" in html:
return True
elif soup.title.te... | |
31,167 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/page_parse/comment.py | 56,58 | 1,160 | get_comment_list | 64,160 | 58,160 | import json
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboComment
from decorators import parse_decorator
from utils import parse_emoji
from page_get import get_profile
import datetime
import re
@parse_decorator('')
def get_html_cont(html):
cont = ''
data = json.loads(html,... | import json
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboComment
from decorators import parse_decorator
from utils import parse_emoji
from page_get import get_profile
import datetime
import re
@parse_decorator('')
def get_html_cont(html):
cont = ''
data = json.loads(html,... | cont = get_html_cont(html)
if not cont:
return list()
soup = BeautifulSoup(cont, 'html5lib')
comment_list = list()
comments = soup.find(attrs={'node-type': 'comment_list'}).find_all(attrs={'class': 'list_li S_line1 clearfix'})
for comment in comments:
wb_comment = WeiboComment(... | """
获取评论列表
:param html:
:param wb_id:
:return:
"""
cont = get_html_cont(html)
if not cont:
return list()
soup = BeautifulSoup(cont, 'html5lib')
comment_list = list()
comments = soup.find(attrs={'node-type': 'comment_list'}).find_all(attrs={'class': 'list_li S_line... | 267 | 526 | 1,448 | 1,974 | import json
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboComment
from decorators import parse_decorator
from utils import parse_emoji
from page_get import get_profile
import datetime
import re
@parse_decorator('')
def get_html_cont(html):
cont = ''
data = json.loads(html,... | import json
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboComment
from decorators import parse_decorator
from utils import parse_emoji
from page_get import get_profile
import datetime
import re
@parse_decorator('')
def get_html_cont(html):
cont = ''
data = json.loads(html,... | |
31,168 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/page_parse/dialogue.py | 11,13 | 1,65 | get_comment_id | 19,38 | 13,38 | import json
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboDialogue
from decorators import parse_decorator
from .comment import get_html_cont
@parse_decorator([])
def get_comment_id(html, wb_id):
FILL_FUNC_BODYdef get_dialogue(html, wb_id, cid):
"""
获取对话列表
:param html... | import json
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboDialogue
from decorators import parse_decorator
from .comment import get_html_cont
@parse_decorator([])
def get_comment_id(html, wb_id):
"""
获取评论列表
:param html:
:param wb_id:
:return:
"""
FILL_FUNC... | cont = get_html_cont(html)
if not cont:
return list()
soup = BeautifulSoup(cont, 'lxml')
comment_ids = list()
comments = soup.find(attrs={'node-type': 'comment_list'}).find_all(attrs={'class': 'list_li S_line1 clearfix'})
for comment in comments:
try:
comment_cont =... | """
获取评论列表
:param html:
:param wb_id:
:return:
"""
cont = get_html_cont(html)
if not cont:
return list()
soup = BeautifulSoup(cont, 'lxml')
comment_ids = list()
comments = soup.find(attrs={'node-type': 'comment_list'}).find_all(attrs={'class': 'list_li S_line1 clearf... | 43 | 454 | 212 | 666 | import json
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboDialogue
from decorators import parse_decorator
from .comment import get_html_cont
@parse_decorator([])
def get_comment_id(html, wb_id):
FILL_FUNC_BODYdef get_dialogue(html, wb_id, cid):
"""
获取对话列表
:param html... | import json
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboDialogue
from decorators import parse_decorator
from .comment import get_html_cont
@parse_decorator([])
def get_comment_id(html, wb_id):
"""
获取评论列表
:param html:
:param wb_id:
:return:
"""
FILL_FUNC... | |
31,170 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/page_parse/praise.py | 20,21 | 1,76 | get_total_page | 21,30 | 21,30 | import json
import html as htmllib
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboPraise
from decorators import parse_decorator
@parse_decorator('')
def get_html_cont(html):
cont = ''
data = json.loads(html, encoding='utf-8').get('data', '')
if data:
cont = da... | import json
import html as htmllib
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboPraise
from decorators import parse_decorator
@parse_decorator('')
def get_html_cont(html):
cont = ''
data = json.loads(html, encoding='utf-8').get('data', '')
if data:
cont = da... | try:
page_count = json.loads(html, encoding='utf-8').get('data', '').get('page', '').get('totalpage', 1)
except Exception as e:
parser.error('Get total page error, the reason is {}'.format(e))
page_count = 1
return page_count
| try:
page_count = json.loads(html, encoding='utf-8').get('data', '').get('page', '').get('totalpage', 1)
except Exception as e:
parser.error('Get total page error, the reason is {}'.format(e))
page_count = 1
return page_count
| 25 | 640 | 96 | 736 | import json
import html as htmllib
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboPraise
from decorators import parse_decorator
@parse_decorator('')
def get_html_cont(html):
cont = ''
data = json.loads(html, encoding='utf-8').get('data', '')
if data:
cont = da... | import json
import html as htmllib
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboPraise
from decorators import parse_decorator
@parse_decorator('')
def get_html_cont(html):
cont = ''
data = json.loads(html, encoding='utf-8').get('data', '')
if data:
cont = da... | |
31,171 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/page_parse/repost.py | 34,36 | 1,90 | get_repost_list | 42,90 | 36,90 | import json
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboRepost
from db.redis_db import IdNames
from decorators import parse_decorator
REPOST_URL = 'http://weibo.com{}'
@parse_decorator('')
def get_html_cont(html):
cont = ''
data = json.loads(html, encoding='utf-8').g... | import json
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboRepost
from db.redis_db import IdNames
from decorators import parse_decorator
REPOST_URL = 'http://weibo.com{}'
@parse_decorator('')
def get_html_cont(html):
cont = ''
data = json.loads(html, encoding='utf-8').g... | cont = get_html_cont(html)
if not cont:
return list()
soup = BeautifulSoup(cont, 'html.parser')
repost_list = list()
reposts = soup.find_all(attrs={'action-type': 'feed_list_item'})
for repost in reposts:
wb_repost = WeiboRepost()
try:
repost_cont = repost.f... | """
Get repost details
:param html: page source
:param mid: weibo mid
:return: list of repost infos
"""
cont = get_html_cont(html)
if not cont:
return list()
soup = BeautifulSoup(cont, 'html.parser')
repost_list = list()
reposts = soup.find_all(attrs={... | 162 | 318 | 822 | 1,140 | import json
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboRepost
from db.redis_db import IdNames
from decorators import parse_decorator
REPOST_URL = 'http://weibo.com{}'
@parse_decorator('')
def get_html_cont(html):
cont = ''
data = json.loads(html, encoding='utf-8').g... | import json
from bs4 import BeautifulSoup
from logger import parser
from db.models import WeiboRepost
from db.redis_db import IdNames
from decorators import parse_decorator
REPOST_URL = 'http://weibo.com{}'
@parse_decorator('')
def get_html_cont(html):
cont = ''
data = json.loads(html, encoding='utf-8').g... | |
31,174 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/page_parse/user/enterprise.py | 32,34 | 1,53 | get_description | 34,53 | 34,53 | import re
import json
from bs4 import BeautifulSoup
from page_parse.user import public
from decorators import parse_decorator
# 以下是通过认证企业主页进行解析
@parse_decorator(0)
def get_friends(html):
cont = public.get_left(html)
soup = BeautifulSoup(cont, 'html.parser')
return int(soup.find_all('strong')[0].get_text... | import re
import json
from bs4 import BeautifulSoup
from page_parse.user import public
from decorators import parse_decorator
# 以下是通过认证企业主页进行解析
@parse_decorator(0)
def get_friends(html):
cont = public.get_left(html)
soup = BeautifulSoup(cont, 'html.parser')
return int(soup.find_all('strong')[0].get_text... | soup = BeautifulSoup(html, "html.parser")
scripts = soup.find_all('script')
pattern = re.compile(r'FM.view\((.*)\)')
cont = ''
description = ''
for script in scripts:
m = pattern.search(script.string)
if m and 'pl.content.homeFeed.index' in script.string and '简介' in script.string... | soup = BeautifulSoup(html, "html.parser")
scripts = soup.find_all('script')
pattern = re.compile(r'FM.view\((.*)\)')
cont = ''
description = ''
for script in scripts:
m = pattern.search(script.string)
if m and 'pl.content.homeFeed.index' in script.string and '简介' in script.string... | 68 | 285 | 279 | 564 | import re
import json
from bs4 import BeautifulSoup
from page_parse.user import public
from decorators import parse_decorator
# 以下是通过认证企业主页进行解析
@parse_decorator(0)
def get_friends(html):
cont = public.get_left(html)
soup = BeautifulSoup(cont, 'html.parser')
return int(soup.find_all('strong')[0].get_text... | import re
import json
from bs4 import BeautifulSoup
from page_parse.user import public
from decorators import parse_decorator
# 以下是通过认证企业主页进行解析
@parse_decorator(0)
def get_friends(html):
cont = public.get_left(html)
soup = BeautifulSoup(cont, 'html.parser')
return int(soup.find_all('strong')[0].get_text... | |
31,177 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/tasks/comment.py | 14,16 | 1,57 | crawl_comment_by_page | 16,35 | 16,35 | from .workers import app
from page_parse import comment
from config import conf
from page_get import get_page
from db.dao import (
WbDataOper, CommentOper)
from logger import crawler
from celery.exceptions import SoftTimeLimitExceeded
import time
BASE_URL = 'http://weibo.com/aj/v6/comment/big?ajwvr=6&id={}&page={}... | from .workers import app
from page_parse import comment
from config import conf
from page_get import get_page
from db.dao import (
WbDataOper, CommentOper)
from logger import crawler
from celery.exceptions import SoftTimeLimitExceeded
import time
BASE_URL = 'http://weibo.com/aj/v6/comment/big?ajwvr=6&id={}&page={}... | try:
cur_url = BASE_URL.format(mid, page_num)
html = get_page(cur_url, auth_level=1, is_ajax=True)
comment_datas = comment.get_comment_list(html, mid)
except SoftTimeLimitExceeded:
crawler.error(
"comment SoftTimeLimitExceeded mid={mid} page_num={page_num}".
... | try:
cur_url = BASE_URL.format(mid, page_num)
html = get_page(cur_url, auth_level=1, is_ajax=True)
comment_datas = comment.get_comment_list(html, mid)
except SoftTimeLimitExceeded:
crawler.error(
"comment SoftTimeLimitExceeded mid={mid} page_num={page_num}".
... | 38 | 459 | 262 | 721 | from .workers import app
from page_parse import comment
from config import conf
from page_get import get_page
from db.dao import (
WbDataOper, CommentOper)
from logger import crawler
from celery.exceptions import SoftTimeLimitExceeded
import time
BASE_URL = 'http://weibo.com/aj/v6/comment/big?ajwvr=6&id={}&page={}... | from .workers import app
from page_parse import comment
from config import conf
from page_get import get_page
from db.dao import (
WbDataOper, CommentOper)
from logger import crawler
from celery.exceptions import SoftTimeLimitExceeded
import time
BASE_URL = 'http://weibo.com/aj/v6/comment/big?ajwvr=6&id={}&page={}... | |
31,178 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/tasks/dialogue.py | 45,47 | 1,72 | crawl_dialogue | 47,63 | 47,63 | from .workers import app
from page_parse import comment, dialogue
from config import conf
from page_get import get_page
from db.dao import (WbDataOper, CommonOper)
import time
AJAX_URL = 'https://weibo.com/aj/v6/comment/conversation?ajwvr=6&cid={}&type=small&ouid=&cuid=&is_more=1&__rnd={}'
COMMENT_URL = 'http://weibo.... | from .workers import app
from page_parse import comment, dialogue
from config import conf
from page_get import get_page
from db.dao import (WbDataOper, CommonOper)
import time
AJAX_URL = 'https://weibo.com/aj/v6/comment/conversation?ajwvr=6&cid={}&type=small&ouid=&cuid=&is_more=1&__rnd={}'
COMMENT_URL = 'http://weibo.... | limit = conf.get_max_dialogue_page() + 1
first_page = crawl_dialogue_by_comment_page(mid, 1)
total_page = comment.get_total_page(first_page)
if total_page < limit:
limit = total_page + 1
for page_num in range(2, limit):
# crawl_dialogue_by_comment_page(mid, page_num)
app.s... | limit = conf.get_max_dialogue_page() + 1
first_page = crawl_dialogue_by_comment_page(mid, 1)
total_page = comment.get_total_page(first_page)
if total_page < limit:
limit = total_page + 1
for page_num in range(2, limit):
# crawl_dialogue_by_comment_page(mid, page_num)
app.s... | 34 | 732 | 194 | 926 | from .workers import app
from page_parse import comment, dialogue
from config import conf
from page_get import get_page
from db.dao import (WbDataOper, CommonOper)
import time
AJAX_URL = 'https://weibo.com/aj/v6/comment/conversation?ajwvr=6&cid={}&type=small&ouid=&cuid=&is_more=1&__rnd={}'
COMMENT_URL = 'http://weibo.... | from .workers import app
from page_parse import comment, dialogue
from config import conf
from page_get import get_page
from db.dao import (WbDataOper, CommonOper)
import time
AJAX_URL = 'https://weibo.com/aj/v6/comment/conversation?ajwvr=6&cid={}&type=small&ouid=&cuid=&is_more=1&__rnd={}'
COMMENT_URL = 'http://weibo.... | |
31,179 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/tasks/downloader.py | 16,18 | 1,35 | download_img_task | 18,35 | 18,35 | # this task is used to download large files, such as images
import os
import shutil
import requests
from .workers import app
from logger import crawler
from config import (
get_images_path, get_images_type)
IMG_PATH = get_images_path()
IMG_TYPE = get_images_type()
@app.task(ignore_result=True)
def download_img... | # this task is used to download large files, such as images
import os
import shutil
import requests
from .workers import app
from logger import crawler
from config import (
get_images_path, get_images_type)
IMG_PATH = get_images_path()
IMG_TYPE = get_images_type()
@app.task(ignore_result=True)
def download_img... | count = 0
for img_url in urls:
if IMG_TYPE == 'large':
img_url = img_url.replace('thumbnail', 'large').replace('square', 'large')
suffix = img_url[img_url.rfind('.') + 1:]
# skip gif images, which is used to show loading process
if suffix != 'gif':
count +... | count = 0
for img_url in urls:
if IMG_TYPE == 'large':
img_url = img_url.replace('thumbnail', 'large').replace('square', 'large')
suffix = img_url[img_url.rfind('.') + 1:]
# skip gif images, which is used to show loading process
if suffix != 'gif':
count +... | 68 | 120 | 234 | 354 | # this task is used to download large files, such as images
import os
import shutil
import requests
from .workers import app
from logger import crawler
from config import (
get_images_path, get_images_type)
IMG_PATH = get_images_path()
IMG_TYPE = get_images_type()
@app.task(ignore_result=True)
def download_img... | # this task is used to download large files, such as images
import os
import shutil
import requests
from .workers import app
from logger import crawler
from config import (
get_images_path, get_images_type)
IMG_PATH = get_images_path()
IMG_TYPE = get_images_type()
@app.task(ignore_result=True)
def download_img... | |
31,180 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/tasks/home.py | 117,119 | 1,125 | execute_home_task | 119,125 | 119,125 | import time
from logger import crawler
from .workers import app
from page_parse.user import public
from page_get import get_page
from config import (get_max_home_page, get_time_after)
from db.dao import (
WbDataOper, SeedidsOper)
from page_parse.home import (
get_data, get_ajax_data, get_total_page)
# only c... | import time
from logger import crawler
from .workers import app
from page_parse.user import public
from page_get import get_page
from config import (get_max_home_page, get_time_after)
from db.dao import (
WbDataOper, SeedidsOper)
from page_parse.home import (
get_data, get_ajax_data, get_total_page)
# only c... | # you can have many strategies to crawl user's home page, here we choose table seed_ids's uid
# whose home_crawl is 0
id_objs = SeedidsOper.get_home_ids()
for id_obj in id_objs:
app.send_task('tasks.home.crawl_weibo_datas', args=(id_obj.uid,), queue='home_crawler',
routing_... | # you can have many strategies to crawl user's home page, here we choose table seed_ids's uid
# whose home_crawl is 0
id_objs = SeedidsOper.get_home_ids()
for id_obj in id_objs:
app.send_task('tasks.home.crawl_weibo_datas', args=(id_obj.uid,), queue='home_crawler',
routing_... | 33 | 1,384 | 130 | 1,514 | import time
from logger import crawler
from .workers import app
from page_parse.user import public
from page_get import get_page
from config import (get_max_home_page, get_time_after)
from db.dao import (
WbDataOper, SeedidsOper)
from page_parse.home import (
get_data, get_ajax_data, get_total_page)
# only c... | import time
from logger import crawler
from .workers import app
from page_parse.user import public
from page_get import get_page
from config import (get_max_home_page, get_time_after)
from db.dao import (
WbDataOper, SeedidsOper)
from page_parse.home import (
get_data, get_ajax_data, get_total_page)
# only c... | |
31,181 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/tasks/login.py | 10,12 | 1,28 | login_task | 12,17 | 12,17 | import time
from db.redis_db import Cookies
from logger import crawler
from login import get_session
from db.dao import LoginInfoOper
from .workers import app
@app.task(ignore_result=True)
def login_task(name, password):
FILL_FUNC_BODY@app.task(ignore_result=True)
def execute_login_task():
infos = LoginInfoOper.... | import time
from db.redis_db import Cookies
from logger import crawler
from login import get_session
from db.dao import LoginInfoOper
from .workers import app
@app.task(ignore_result=True)
def login_task(name, password):
FILL_FUNC_BODY@app.task(ignore_result=True)
def execute_login_task():
infos = LoginInfoOper.... | get_session(name, password)
# There should be login interval, if too many accounts login at the same time from the same ip, all the
# accounts can be banned by weibo's anti-cheating system
| get_session(name, password)
# There should be login interval, if too many accounts login at the same time from the same ip, all the
# accounts can be banned by weibo's anti-cheating system
| 32 | 217 | 59 | 276 | import time
from db.redis_db import Cookies
from logger import crawler
from login import get_session
from db.dao import LoginInfoOper
from .workers import app
@app.task(ignore_result=True)
def login_task(name, password):
FILL_FUNC_BODY@app.task(ignore_result=True)
def execute_login_task():
infos = LoginInfoOper.... | import time
from db.redis_db import Cookies
from logger import crawler
from login import get_session
from db.dao import LoginInfoOper
from .workers import app
@app.task(ignore_result=True)
def login_task(name, password):
FILL_FUNC_BODY@app.task(ignore_result=True)
def execute_login_task():
infos = LoginInfoOper.... | |
31,182 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/tasks/praise.py | 26,28 | 1,59 | crawl_praise_page | 28,53 | 28,53 | import time
from .workers import app
from page_parse import praise
from logger import crawler
from config import conf
from page_get import get_page
from db.dao import (WbDataOper, PraiseOper)
# Please note that m.weibo.cn can return more data than PC side
BASE_URL = 'https://weibo.com/aj/v6/like/likelist?ajwvr=6&mid... | import time
from .workers import app
from page_parse import praise
from logger import crawler
from config import conf
from page_get import get_page
from db.dao import (WbDataOper, PraiseOper)
# Please note that m.weibo.cn can return more data than PC side
BASE_URL = 'https://weibo.com/aj/v6/like/likelist?ajwvr=6&mid... | # 这里为了马上拿到返回结果,采用本地调用的方式
cur_time = int(time.time() * 1000)
cur_url = BASE_URL.format(mid, cur_time)
html = get_page(cur_url, auth_level=2, is_ajax=True)
praise_data, ext_param = praise.get_praise_list(html, mid)
PraiseOper.add_all(praise_data)
WbDataOper.set_weibo_praise_crawled(mid)
... | # 这里为了马上拿到返回结果,采用本地调用的方式
cur_time = int(time.time() * 1000)
cur_url = BASE_URL.format(mid, cur_time)
html = get_page(cur_url, auth_level=2, is_ajax=True)
praise_data, ext_param = praise.get_praise_list(html, mid)
PraiseOper.add_all(praise_data)
WbDataOper.set_weibo_praise_crawled(mid)
... | 107 | 486 | 344 | 830 | import time
from .workers import app
from page_parse import praise
from logger import crawler
from config import conf
from page_get import get_page
from db.dao import (WbDataOper, PraiseOper)
# Please note that m.weibo.cn can return more data than PC side
BASE_URL = 'https://weibo.com/aj/v6/like/likelist?ajwvr=6&mid... | import time
from .workers import app
from page_parse import praise
from logger import crawler
from config import conf
from page_get import get_page
from db.dao import (WbDataOper, PraiseOper)
# Please note that m.weibo.cn can return more data than PC side
BASE_URL = 'https://weibo.com/aj/v6/like/likelist?ajwvr=6&mid... | |
31,183 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/tasks/repost.py | 25,27 | 1,67 | crawl_repost_page | 27,58 | 27,58 | from .workers import app
from page_parse import repost
from logger import crawler
from db.redis_db import IdNames
from db.dao import (
WbDataOper, RepostOper)
from page_get import (
get_page, get_profile)
from config import get_max_repost_page
BASE_URL = 'http://weibo.com/aj/v6/mblog/info/big?ajwvr=6&id={}&&p... | from .workers import app
from page_parse import repost
from logger import crawler
from db.redis_db import IdNames
from db.dao import (
WbDataOper, RepostOper)
from page_get import (
get_page, get_profile)
from config import get_max_repost_page
BASE_URL = 'http://weibo.com/aj/v6/mblog/info/big?ajwvr=6&id={}&&p... | limit = get_max_repost_page() + 1
first_repost_data = crawl_repost_by_page(mid, 1)
total_page = repost.get_total_page(first_repost_data[0])
repost_datas = first_repost_data[1]
if not repost_datas:
return
root_user, _ = get_profile(uid)
if total_page < limit:
limit = total_... | limit = get_max_repost_page() + 1
first_repost_data = crawl_repost_by_page(mid, 1)
total_page = repost.get_total_page(first_repost_data[0])
repost_datas = first_repost_data[1]
if not repost_datas:
return
root_user, _ = get_profile(uid)
if total_page < limit:
limit = total_... | 80 | 481 | 393 | 874 | from .workers import app
from page_parse import repost
from logger import crawler
from db.redis_db import IdNames
from db.dao import (
WbDataOper, RepostOper)
from page_get import (
get_page, get_profile)
from config import get_max_repost_page
BASE_URL = 'http://weibo.com/aj/v6/mblog/info/big?ajwvr=6&id={}&&p... | from .workers import app
from page_parse import repost
from logger import crawler
from db.redis_db import IdNames
from db.dao import (
WbDataOper, RepostOper)
from page_get import (
get_page, get_profile)
from config import get_max_repost_page
BASE_URL = 'http://weibo.com/aj/v6/mblog/info/big?ajwvr=6&id={}&&p... | |
31,184 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/tasks/search.py | 21,23 | 1,65 | search_keyword | 23,59 | 23,59 | from urllib import parse as url_parse
from logger import crawler
from .workers import app
from page_get import get_page
from config import get_max_search_page
from page_parse import search as parse_search
from db.dao import (
KeywordsOper, KeywordsDataOper, WbDataOper)
# This url is just for original weibos.
# I... | from urllib import parse as url_parse
from logger import crawler
from .workers import app
from page_get import get_page
from config import get_max_search_page
from page_parse import search as parse_search
from db.dao import (
KeywordsOper, KeywordsDataOper, WbDataOper)
# This url is just for original weibos.
# I... | crawler.info('We are searching keyword "{}"'.format(keyword))
cur_page = 1
encode_keyword = url_parse.quote(keyword)
while cur_page < LIMIT:
cur_url = URL.format(encode_keyword, cur_page)
# current only for login, maybe later crawling page one without login
search_page = get_page... | crawler.info('We are searching keyword "{}"'.format(keyword))
cur_page = 1
encode_keyword = url_parse.quote(keyword)
while cur_page < LIMIT:
cur_url = URL.format(encode_keyword, cur_page)
# current only for login, maybe later crawling page one without login
search_page = get_page... | 149 | 344 | 518 | 862 | from urllib import parse as url_parse
from logger import crawler
from .workers import app
from page_get import get_page
from config import get_max_search_page
from page_parse import search as parse_search
from db.dao import (
KeywordsOper, KeywordsDataOper, WbDataOper)
# This url is just for original weibos.
# I... | from urllib import parse as url_parse
from logger import crawler
from .workers import app
from page_get import get_page
from config import get_max_search_page
from page_parse import search as parse_search
from db.dao import (
KeywordsOper, KeywordsDataOper, WbDataOper)
# This url is just for original weibos.
# I... | |
31,185 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/tasks/user.py | 9,11 | 1,82 | crawl_follower_fans | 11,22 | 11,22 | from .workers import app
from db.dao import SeedidsOper
from page_get import (get_fans_or_followers_ids, get_profile, get_user_profile,
get_newcard_by_name)
from logger import crawler
from celery.exceptions import SoftTimeLimitExceeded
@app.task(ignore_result=True)
def crawl_follower_fans(uid):
... | from .workers import app
from db.dao import SeedidsOper
from page_get import (get_fans_or_followers_ids, get_profile, get_user_profile,
get_newcard_by_name)
from logger import crawler
from celery.exceptions import SoftTimeLimitExceeded
@app.task(ignore_result=True)
def crawl_follower_fans(uid):
... | seed = SeedidsOper.get_seed_by_id(uid)
if seed.other_crawled == 0:
rs = get_fans_or_followers_ids(uid, 1, 1)
rs.extend(get_fans_or_followers_ids(uid, 2, 1))
datas = set(rs)
# If data already exits, just skip it
if datas:
SeedidsOper.insert_seeds(datas)
... | seed = SeedidsOper.get_seed_by_id(uid)
if seed.other_crawled == 0:
rs = get_fans_or_followers_ids(uid, 1, 1)
rs.extend(get_fans_or_followers_ids(uid, 2, 1))
datas = set(rs)
# If data already exits, just skip it
if datas:
SeedidsOper.insert_seeds(datas)
... | 30 | 764 | 156 | 920 | from .workers import app
from db.dao import SeedidsOper
from page_get import (get_fans_or_followers_ids, get_profile, get_user_profile,
get_newcard_by_name)
from logger import crawler
from celery.exceptions import SoftTimeLimitExceeded
@app.task(ignore_result=True)
def crawl_follower_fans(uid):
... | from .workers import app
from db.dao import SeedidsOper
from page_get import (get_fans_or_followers_ids, get_profile, get_user_profile,
get_newcard_by_name)
from logger import crawler
from celery.exceptions import SoftTimeLimitExceeded
@app.task(ignore_result=True)
def crawl_follower_fans(uid):
... | |
31,186 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/utils/code_verification.py | 113,115 | 1,138 | code_verificate | 126,138 | 115,138 | import json
import time
import requests
from logger import other
class YDMHttp:
apiurl = 'http://api.yundama.com/api.php'
username = ''
password = ''
appid = ''
appkey = ''
def __init__(self, name, passwd, app_id, app_key):
self.username = name
self.password = passwd
... | import json
import time
import requests
from logger import other
class YDMHttp:
apiurl = 'http://api.yundama.com/api.php'
username = ''
password = ''
appid = ''
appkey = ''
def __init__(self, name, passwd, app_id, app_key):
self.username = name
self.password = passwd
... | yundama_obj = YDMHttp(name, passwd, app_id, app_key)
yundama_obj.login()
rest = yundama_obj.balance()
if rest <= 0:
raise Exception('云打码已经欠费了,请及时充值')
if rest <= 100:
other.warning('云打码余额已不多,请注意及时充值')
# 开始识别,图片路径,验证码类型ID,超时时间(秒),识别结果
cid, result = yundama_obj.decode(file_nam... | """
:param name: 云打码注册用户名,这是普通用户注册,而非开发者用户注册名
:param passwd: 用户密码
:param file_name: 需要识别的图片名
:param app_id: 软件ID,这里默认是填的我的,如果需要,可以自行注册一个开发者账号,填自己的。
软件开发者会有少额提成,希望大家支持weibospider的发展(提成的20%会给celery项目以支持其发展)
:param app_key: 软件key,这里默认是填的我的,如果需要,可以自行注册一个开发者账号,填自己的
:param code_type: 1005表示五位字... | 33 | 1,275 | 183 | 1,458 | import json
import time
import requests
from logger import other
class YDMHttp:
apiurl = 'http://api.yundama.com/api.php'
username = ''
password = ''
appid = ''
appkey = ''
def __init__(self, name, passwd, app_id, app_key):
self.username = name
self.password = passwd
... | import json
import time
import requests
from logger import other
class YDMHttp:
apiurl = 'http://api.yundama.com/api.php'
username = ''
password = ''
appid = ''
appkey = ''
def __init__(self, name, passwd, app_id, app_key):
self.username = name
self.password = passwd
... | |
31,187 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/utils/code_verification.py | 56,57 | 9,113 | upload | YDMHttp | 57,69 | 57,69 | class YDMHttp:
apiurl = 'http://api.yundama.com/api.php'
username = ''
password = ''
appid = ''
appkey = ''
def __init__(self, name, passwd, app_id, app_key):
self.username = name
self.password = passwd
self.appid = str(app_id)
self.appkey = app_key
def requ... | class YDMHttp:
apiurl = 'http://api.yundama.com/api.php'
username = ''
password = ''
appid = ''
appkey = ''
def __init__(self, name, passwd, app_id, app_key):
self.username = name
self.password = passwd
self.appid = str(app_id)
self.appkey = app_key
def requ... | data = {'method': 'upload', 'username': self.username, 'password': self.password, 'appid': self.appid,
'appkey': self.appkey, 'codetype': str(codetype), 'timeout': str(timeout)}
file = {'file': filename}
response = self.request(data, file)
if response:
if resp... | data = {'method': 'upload', 'username': self.username, 'password': self.password, 'appid': self.appid,
'appkey': self.appkey, 'codetype': str(codetype), 'timeout': str(timeout)}
file = {'file': filename}
response = self.request(data, file)
if response:
if resp... | 40 | 814 | 146 | 960 | import json
import time
import requests
from logger import other
class YDMHttp:
apiurl = 'http://api.yundama.com/api.php'
username = ''
password = ''
appid = ''
appkey = ''
def __init__(self, name, passwd, app_id, app_key):
self.username = name
self.password = passwd
... | import json
import time
import requests
from logger import other
class YDMHttp:
apiurl = 'http://api.yundama.com/api.php'
username = ''
password = ''
appid = ''
appkey = ''
def __init__(self, name, passwd, app_id, app_key):
self.username = name
self.password = passwd
... |
31,188 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/utils/email_warning.py | 40,42 | 1,56 | send_email | 42,56 | 42,56 | from traceback import format_tb
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import (
parseaddr, formataddr)
from config import get_email_args
from logger import other
email_args = get_email_args()
smtp_server = email_args['server']
smtp_port = email_args[... | from traceback import format_tb
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import (
parseaddr, formataddr)
from config import get_email_args
from logger import other
email_args = get_email_args()
smtp_server = email_args['server']
smtp_port = email_args[... | if to_addrs is None or isinstance(to_addrs, str):
to_addrs = [to_addrs]
msg = gen_msg(warning_info, email_subject, email_from, to_addrs[0], from_nick, to_nick)
server = smtplib.SMTP(server, port)
try:
server.starttls()
server.login(email_from, email_pass)
rs = server.send... | if to_addrs is None or isinstance(to_addrs, str):
to_addrs = [to_addrs]
msg = gen_msg(warning_info, email_subject, email_from, to_addrs[0], from_nick, to_nick)
server = smtplib.SMTP(server, port)
try:
server.starttls()
server.login(email_from, email_pass)
rs = server.send... | 51 | 453 | 215 | 668 | from traceback import format_tb
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import (
parseaddr, formataddr)
from config import get_email_args
from logger import other
email_args = get_email_args()
smtp_server = email_args['server']
smtp_port = email_args[... | from traceback import format_tb
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import (
parseaddr, formataddr)
from config import get_email_args
from logger import other
email_args = get_email_args()
smtp_server = email_args['server']
smtp_port = email_args[... | |
31,189 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/utils/filters.py | 4,5 | 1,19 | url_filter | 5,13 | 5,13 | from bs4 import BeautifulSoup
def url_filter(url):
FILL_FUNC_BODYdef text_filter(html):
soup = BeautifulSoup(html, 'html.parser')
return soup.text.strip()
__all__ = ['url_filter', 'text_filter'] | from bs4 import BeautifulSoup
def url_filter(url):
FILL_FUNC_BODYdef text_filter(html):
soup = BeautifulSoup(html, 'html.parser')
return soup.text.strip()
__all__ = ['url_filter', 'text_filter'] | if url.lower().startswith('//'):
return 'http:{}'.format(url)
elif url.lower().startswith('/'):
return 'http://weibo.com{}'.format(url)
else:
return url
| if url.lower().startswith('//'):
return 'http:{}'.format(url)
elif url.lower().startswith('/'):
return 'http://weibo.com{}'.format(url)
else:
return url
| 11 | 79 | 74 | 153 | from bs4 import BeautifulSoup
def url_filter(url):
FILL_FUNC_BODYdef text_filter(html):
soup = BeautifulSoup(html, 'html.parser')
return soup.text.strip()
__all__ = ['url_filter', 'text_filter'] | from bs4 import BeautifulSoup
def url_filter(url):
FILL_FUNC_BODYdef text_filter(html):
soup = BeautifulSoup(html, 'html.parser')
return soup.text.strip()
__all__ = ['url_filter', 'text_filter'] | |
31,190 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/utils/getip.py | 1,2 | 1,13 | getIP | 2,8 | 2,8 | def getIP(param):
FILL_FUNC_BODYdef getIPWithoutLogin(param):
return {
'http': '',
'https': '',
} | def getIP(param):
FILL_FUNC_BODYdef getIPWithoutLogin(param):
return {
'http': '',
'https': '',
} | return {
'http': '',
'https': '',
}
| return {
'http': '',
'https': '',
}
| 7 | 44 | 27 | 71 | def getIP(param):
FILL_FUNC_BODYdef getIPWithoutLogin(param):
return {
'http': '',
'https': '',
} | def getIP(param):
FILL_FUNC_BODYdef getIPWithoutLogin(param):
return {
'http': '',
'https': '',
} | |
31,191 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/utils/parse_emoji.py | 5,6 | 1,22 | load_emoji_map | 6,13 | 6,13 | import json
def load_emoji_map(fn = 'utils/emoji_ios6.json'):
FILL_FUNC_BODYdef softband_to_utf8(emoji):
hex_emoji = sb_dict.get(emoji.lower(), '')
if hex_emoji:
return bytes.fromhex(hex_emoji).decode('utf-8')
else:
return ''
sb_dict = load_emoji_map()
| import json
def load_emoji_map(fn = 'utils/emoji_ios6.json'):
FILL_FUNC_BODYdef softband_to_utf8(emoji):
hex_emoji = sb_dict.get(emoji.lower(), '')
if hex_emoji:
return bytes.fromhex(hex_emoji).decode('utf-8')
else:
return ''
sb_dict = load_emoji_map()
| json_data = json.load(open(fn, encoding='utf-8'))
sb_dict = {}
for m in json_data:
sb_dict[m['sb'].lower()]=m['utf8']
return sb_dict
| json_data = json.load(open(fn, encoding='utf-8'))
sb_dict = {}
for m in json_data:
sb_dict[m['sb'].lower()]=m['utf8']
return sb_dict
| 14 | 130 | 70 | 200 | import json
def load_emoji_map(fn = 'utils/emoji_ios6.json'):
FILL_FUNC_BODYdef softband_to_utf8(emoji):
hex_emoji = sb_dict.get(emoji.lower(), '')
if hex_emoji:
return bytes.fromhex(hex_emoji).decode('utf-8')
else:
return ''
sb_dict = load_emoji_map()
| import json
def load_emoji_map(fn = 'utils/emoji_ios6.json'):
FILL_FUNC_BODYdef softband_to_utf8(emoji):
hex_emoji = sb_dict.get(emoji.lower(), '')
if hex_emoji:
return bytes.fromhex(hex_emoji).decode('utf-8')
else:
return ''
sb_dict = load_emoji_map()
| |
31,192 | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider | /home/hieuvd/dung_repo/raw/stars_02/SpiderClub_weibospider/weibospider/utils/util_cls.py | 17,18 | 5,40 | __run | KThread | 18,24 | 18,24 | class KThread(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
self.killed = False
def start(self):
"""Start the thread."""
self.__run_backup = self.run
self.run = self.__run # Force the Thread to install our trace... | class KThread(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
self.killed = False
def start(self):
"""Start the thread."""
self.__run_backup = self.run
self.run = self.__run # Force the Thread to install our trace... |
"""Hacked run function, which installs the trace."""
sys.settrace(self.globaltrace)
self.__run_backup()
self.run = self.__run_backup
|
"""Hacked run function, which installs the trace."""
sys.settrace(self.globaltrace)
self.__run_backup()
self.run = self.__run_backup
| 12 | 224 | 54 | 278 | import threading
import sys
class KThread(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
self.killed = False
def start(self):
"""Start the thread."""
self.__run_backup = self.run
self.run = self.__run # Force t... | import threading
import sys
class KThread(threading.Thread):
def __init__(self, *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
self.killed = False
def start(self):
"""Start the thread."""
self.__run_backup = self.run
self.run = self.__run # Force t... |
31,196 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/composite_demo/demo_agent_cogagent.py | 24,35 | 1,120 | main | 35,120 | 35,120 | from io import BytesIO
import base64
import streamlit as st
import re
from streamlit.delta_generator import DeltaGenerator
from client import get_client
from conversation import postprocess_text, Conversation, Role, postprocess_image
from PIL import Image
from utils import images_are_same
client = get_client()
def ... | from io import BytesIO
import base64
import streamlit as st
import re
from streamlit.delta_generator import DeltaGenerator
from client import get_client
from conversation import postprocess_text, Conversation, Role, postprocess_image
from PIL import Image
from utils import images_are_same
client = get_client()
def ... | if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
if prompt_text == "" and retry == False:
print("\n== Clean ==\n")
st.session_state.chat_history = []
return
history: list[Conversation] = st.session_state.chat_history
for conversation in hist... | if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
if prompt_text == "" and retry == False:
print("\n== Clean ==\n")
st.session_state.chat_history = []
return
history: list[Conversation] = st.session_state.chat_history
for conversation in hist... | 215 | 253 | 950 | 1,203 | from io import BytesIO
import base64
import streamlit as st
import re
from streamlit.delta_generator import DeltaGenerator
from client import get_client
from conversation import postprocess_text, Conversation, Role, postprocess_image
from PIL import Image
from utils import images_are_same
client = get_client()
def ... | from io import BytesIO
import base64
import streamlit as st
import re
from streamlit.delta_generator import DeltaGenerator
from client import get_client
from conversation import postprocess_text, Conversation, Role, postprocess_image
from PIL import Image
from utils import images_are_same
client = get_client()
def ... | |
31,197 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/composite_demo/demo_chat_cogagent.py | 24,35 | 1,114 | main | 35,114 | 35,114 | import streamlit as st
import base64
import re
from PIL import Image
from io import BytesIO
from streamlit.delta_generator import DeltaGenerator
from client import get_client
from utils import images_are_same
from conversation import Conversation, Role, postprocess_image, postprocess_text
client = get_client()
def ... | import streamlit as st
import base64
import re
from PIL import Image
from io import BytesIO
from streamlit.delta_generator import DeltaGenerator
from client import get_client
from utils import images_are_same
from conversation import Conversation, Role, postprocess_image, postprocess_text
client = get_client()
def ... | if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
if prompt_text == "" and retry == False:
print("\n== Clean ==\n")
st.session_state.chat_history = []
return
history: list[Conversation] = st.session_state.chat_history
for conversation in hist... | if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
if prompt_text == "" and retry == False:
print("\n== Clean ==\n")
st.session_state.chat_history = []
return
history: list[Conversation] = st.session_state.chat_history
for conversation in hist... | 191 | 253 | 896 | 1,149 | import streamlit as st
import base64
import re
from PIL import Image
from io import BytesIO
from streamlit.delta_generator import DeltaGenerator
from client import get_client
from utils import images_are_same
from conversation import Conversation, Role, postprocess_image, postprocess_text
client = get_client()
def ... | import streamlit as st
import base64
import re
from PIL import Image
from io import BytesIO
from streamlit.delta_generator import DeltaGenerator
from client import get_client
from utils import images_are_same
from conversation import Conversation, Role, postprocess_image, postprocess_text
client = get_client()
def ... | |
31,198 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/composite_demo/demo_chat_cogvlm.py | 24,35 | 1,114 | main | 35,114 | 35,114 | import streamlit as st
import base64
import re
from PIL import Image
from io import BytesIO
from streamlit.delta_generator import DeltaGenerator
from client import get_client
from utils import images_are_same
from conversation import Conversation, Role, postprocess_image, postprocess_text
client = get_client()
def ... | import streamlit as st
import base64
import re
from PIL import Image
from io import BytesIO
from streamlit.delta_generator import DeltaGenerator
from client import get_client
from utils import images_are_same
from conversation import Conversation, Role, postprocess_image, postprocess_text
client = get_client()
def ... | if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
if prompt_text == "" and retry == False:
print("\n== Clean ==\n")
st.session_state.chat_history = []
return
history: list[Conversation] = st.session_state.chat_history
for conversation in hist... | if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
if prompt_text == "" and retry == False:
print("\n== Clean ==\n")
st.session_state.chat_history = []
return
history: list[Conversation] = st.session_state.chat_history
for conversation in hist... | 195 | 253 | 907 | 1,160 | import streamlit as st
import base64
import re
from PIL import Image
from io import BytesIO
from streamlit.delta_generator import DeltaGenerator
from client import get_client
from utils import images_are_same
from conversation import Conversation, Role, postprocess_image, postprocess_text
client = get_client()
def ... | import streamlit as st
import base64
import re
from PIL import Image
from io import BytesIO
from streamlit.delta_generator import DeltaGenerator
from client import get_client
from utils import images_are_same
from conversation import Conversation, Role, postprocess_image, postprocess_text
client = get_client()
def ... | |
31,200 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/openai_demo/openai_api_request.py | 77,78 | 1,121 | simple_image_chat | 89,119 | 78,119 | """
This script is designed to mimic the OpenAI API interface with CogVLM & CogAgent Chat
It demonstrates how to integrate image and text-based input to generate a response.
Currently, the model can only handle a single image.
Therefore, do not use this script to process multiple images in one conversation. (includes i... | """
This script is designed to mimic the OpenAI API interface with CogVLM & CogAgent Chat
It demonstrates how to integrate image and text-based input to generate a response.
Currently, the model can only handle a single image.
Therefore, do not use this script to process multiple images in one conversation. (includes i... |
img_url = f"data:image/jpeg;base64,{encode_image(img_path)}"
messages = [
{
"role": "user",
"content": [
{
"type": "text",
"text": "What’s in this image?",
},
{
"type": "i... | """
Facilitates a simple chat interaction involving an image.
Args:
use_stream (bool): Specifies whether to use streaming for chat responses.
img_path (str): Path to the image file to be included in the chat.
This function encodes the specified image and constructs a predefined convers... | 127 | 1,016 | 334 | 1,350 | """
This script is designed to mimic the OpenAI API interface with CogVLM & CogAgent Chat
It demonstrates how to integrate image and text-based input to generate a response.
Currently, the model can only handle a single image.
Therefore, do not use this script to process multiple images in one conversation. (includes i... | """
This script is designed to mimic the OpenAI API interface with CogVLM & CogAgent Chat
It demonstrates how to integrate image and text-based input to generate a response.
Currently, the model can only handle a single image.
Therefore, do not use this script to process multiple images in one conversation. (includes i... | |
31,202 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/cogagent_model.py | 173,175 | 157,199 | add_model_specific_args | CogAgentModel | 175,181 | 175,181 | class CogAgentModel(LLaMAModel):
def __init__(self, args, transformer=None, **kwargs):
super().__init__(args, transformer=transformer, **kwargs)
self.image_length = args.image_length
self.cross_image_pix = args.cross_image_pix
self.add_mixin("eva", ImageMixin(args))
self.del_... | class CogAgentModel(LLaMAModel):
def __init__(self, args, transformer=None, **kwargs):
super().__init__(args, transformer=transformer, **kwargs)
self.image_length = args.image_length
self.cross_image_pix = args.cross_image_pix
self.add_mixin("eva", ImageMixin(args))
self.del_... | group = parser.add_argument_group('CogAgent', 'CogAgent Configurations')
group.add_argument('--image_length', type=int, default=256)
group.add_argument('--cross_image_pix', type=int, default=1120) # Standard CogAgent use 1120; if you want to adjust this param, finetune the model first.
g... | group = parser.add_argument_group('CogAgent', 'CogAgent Configurations')
group.add_argument('--image_length', type=int, default=256)
group.add_argument('--cross_image_pix', type=int, default=1120) # Standard CogAgent use 1120; if you want to adjust this param, finetune the model first.
g... | 32 | 601 | 147 | 748 | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from functools import partial
from sat.model.base_model import BaseMixin
import torch.nn as nn
import numpy as np
from sat.resources.urls import MODEL_URLS
from .eva_clip_L_hf import Eva2LargeEncoder
from .mixin import LlamaVisionExpertFCMi... | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from functools import partial
from sat.model.base_model import BaseMixin
import torch.nn as nn
import numpy as np
from sat.resources.urls import MODEL_URLS
from .eva_clip_L_hf import Eva2LargeEncoder
from .mixin import LlamaVisionExpertFCMi... |
31,203 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/cogagent_model.py | 100,101 | 75,111 | forward | ExternalVisionModel | 101,111 | 101,111 | class ExternalVisionModel(BaseMixin):
'''A combination of vit and a linear projection'''
def __init__(self, args, vitclass):
'''
args: the args to initialize the vit model
vitclass: the class of VIT model, must be a subclass of BaseModel
project_dim: the dimension of ... | class ExternalVisionModel(BaseMixin):
'''A combination of vit and a linear projection'''
def __init__(self, args, vitclass):
'''
args: the args to initialize the vit model
vitclass: the class of VIT model, must be a subclass of BaseModel
project_dim: the dimension of ... | enc = self.vit(*args, **kw_args)
# i = torch.arange(80, device=enc.device)
# j = torch.arange(80, device=enc.device)
# posx = self.ppx(i).unsqueeze(0).repeat(80, 1, 1)
# posy = self.ppy(j).unsqueeze(1).repeat(1, 80, 1)
# pos = (posx + posy).view(-1, 1024).unsqueeze(0)
... | enc = self.vit(*args, **kw_args)
# i = torch.arange(80, device=enc.device)
# j = torch.arange(80, device=enc.device)
# posx = self.ppx(i).unsqueeze(0).repeat(80, 1, 1)
# posy = self.ppy(j).unsqueeze(1).repeat(1, 80, 1)
# pos = (posx + posy).view(-1, 1024).unsqueeze(0)
... | 44 | 362 | 198 | 560 | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from functools import partial
from sat.model.base_model import BaseMixin
import torch.nn as nn
import numpy as np
from sat.resources.urls import MODEL_URLS
from .eva_clip_L_hf import Eva2LargeEncoder
from .mixin import LlamaVisionExpertFCMi... | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from functools import partial
from sat.model.base_model import BaseMixin
import torch.nn as nn
import numpy as np
from sat.resources.urls import MODEL_URLS
from .eva_clip_L_hf import Eva2LargeEncoder
from .mixin import LlamaVisionExpertFCMi... |
31,204 | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM | /home/hieuvd/dung_repo/raw/stars_02/THUDM_CogVLM/CogVLM/utils/models/cogagent_model.py | 232,234 | 220,242 | add_model_specific_args | FineTuneTestCogAgentModel | 234,242 | 234,242 | class FineTuneTestCogAgentModel(CogAgentModel):
def __init__(self, args, transformer=None, **kw_args):
super().__init__(args, transformer=transformer, **kw_args)
if args.use_ptuning:
self.add_mixin("ptuning", PTuningV2Mixin(args.num_layers, args.hidden_size // args.num_attention_heads, a... | class FineTuneTestCogAgentModel(CogAgentModel):
def __init__(self, args, transformer=None, **kw_args):
super().__init__(args, transformer=transformer, **kw_args)
if args.use_ptuning:
self.add_mixin("ptuning", PTuningV2Mixin(args.num_layers, args.hidden_size // args.num_attention_heads, a... | group = parser.add_argument_group('CogAgent-finetune', 'CogAgent finetune Configurations')
group.add_argument('--pre_seq_len', type=int, default=8)
group.add_argument('--lora_rank', type=int, default=10)
group.add_argument('--use_ptuning', action="store_true")
group.add_argument(... | group = parser.add_argument_group('CogAgent-finetune', 'CogAgent finetune Configurations')
group.add_argument('--pre_seq_len', type=int, default=8)
group.add_argument('--lora_rank', type=int, default=10)
group.add_argument('--use_ptuning', action="store_true")
group.add_argument(... | 24 | 338 | 190 | 528 | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from functools import partial
from sat.model.base_model import BaseMixin
import torch.nn as nn
import numpy as np
from sat.resources.urls import MODEL_URLS
from .eva_clip_L_hf import Eva2LargeEncoder
from .mixin import LlamaVisionExpertFCMi... | from sat.model.official.llama_model import LLaMAModel
import json
import torch
from functools import partial
from sat.model.base_model import BaseMixin
import torch.nn as nn
import numpy as np
from sat.resources.urls import MODEL_URLS
from .eva_clip_L_hf import Eva2LargeEncoder
from .mixin import LlamaVisionExpertFCMi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.