repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
binux/pyspider
pyspider/scheduler/scheduler.py
Scheduler.xmlrpc_run
def xmlrpc_run(self, port=23333, bind='127.0.0.1', logRequests=False): '''Start xmlrpc interface''' from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication application = WSGIXMLRPCApplication() application.register_function(self.quit, '_quit') application.register_function(self.__len__, 'size') def dump_counter(_time, _type): try: return self._cnt[_time].to_dict(_type) except: logger.exception('') application.register_function(dump_counter, 'counter') def new_task(task): if self.task_verify(task): self.newtask_queue.put(task) return True return False application.register_function(new_task, 'newtask') def send_task(task): '''dispatch task to fetcher''' self.send_task(task) return True application.register_function(send_task, 'send_task') def update_project(): self._force_update_project = True application.register_function(update_project, 'update_project') def get_active_tasks(project=None, limit=100): allowed_keys = set(( 'type', 'taskid', 'project', 'status', 'url', 'lastcrawltime', 'updatetime', 'track', )) track_allowed_keys = set(( 'ok', 'time', 'follows', 'status_code', )) iters = [iter(x.active_tasks) for k, x in iteritems(self.projects) if x and (k == project if project else True)] tasks = [next(x, None) for x in iters] result = [] while len(result) < limit and tasks and not all(x is None for x in tasks): updatetime, task = t = max(t for t in tasks if t) i = tasks.index(t) tasks[i] = next(iters[i], None) for key in list(task): if key == 'track': for k in list(task[key].get('fetch', [])): if k not in track_allowed_keys: del task[key]['fetch'][k] for k in list(task[key].get('process', [])): if k not in track_allowed_keys: del task[key]['process'][k] if key in allowed_keys: continue del task[key] result.append(t) # fix for "<type 'exceptions.TypeError'>:dictionary key must be string" # have no idea why return json.loads(json.dumps(result)) application.register_function(get_active_tasks, 'get_active_tasks') def get_projects_pause_status(): result = {} for project_name, project in iteritems(self.projects): result[project_name] = project.paused return result application.register_function(get_projects_pause_status, 'get_projects_pause_status') def webui_update(): return { 'pause_status': get_projects_pause_status(), 'counter': { '5m_time': dump_counter('5m_time', 'avg'), '5m': dump_counter('5m', 'sum'), '1h': dump_counter('1h', 'sum'), '1d': dump_counter('1d', 'sum'), 'all': dump_counter('all', 'sum'), }, } application.register_function(webui_update, 'webui_update') import tornado.wsgi import tornado.ioloop import tornado.httpserver container = tornado.wsgi.WSGIContainer(application) self.xmlrpc_ioloop = tornado.ioloop.IOLoop() self.xmlrpc_server = tornado.httpserver.HTTPServer(container, io_loop=self.xmlrpc_ioloop) self.xmlrpc_server.listen(port=port, address=bind) logger.info('scheduler.xmlrpc listening on %s:%s', bind, port) self.xmlrpc_ioloop.start()
python
def xmlrpc_run(self, port=23333, bind='127.0.0.1', logRequests=False): '''Start xmlrpc interface''' from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication application = WSGIXMLRPCApplication() application.register_function(self.quit, '_quit') application.register_function(self.__len__, 'size') def dump_counter(_time, _type): try: return self._cnt[_time].to_dict(_type) except: logger.exception('') application.register_function(dump_counter, 'counter') def new_task(task): if self.task_verify(task): self.newtask_queue.put(task) return True return False application.register_function(new_task, 'newtask') def send_task(task): '''dispatch task to fetcher''' self.send_task(task) return True application.register_function(send_task, 'send_task') def update_project(): self._force_update_project = True application.register_function(update_project, 'update_project') def get_active_tasks(project=None, limit=100): allowed_keys = set(( 'type', 'taskid', 'project', 'status', 'url', 'lastcrawltime', 'updatetime', 'track', )) track_allowed_keys = set(( 'ok', 'time', 'follows', 'status_code', )) iters = [iter(x.active_tasks) for k, x in iteritems(self.projects) if x and (k == project if project else True)] tasks = [next(x, None) for x in iters] result = [] while len(result) < limit and tasks and not all(x is None for x in tasks): updatetime, task = t = max(t for t in tasks if t) i = tasks.index(t) tasks[i] = next(iters[i], None) for key in list(task): if key == 'track': for k in list(task[key].get('fetch', [])): if k not in track_allowed_keys: del task[key]['fetch'][k] for k in list(task[key].get('process', [])): if k not in track_allowed_keys: del task[key]['process'][k] if key in allowed_keys: continue del task[key] result.append(t) # fix for "<type 'exceptions.TypeError'>:dictionary key must be string" # have no idea why return json.loads(json.dumps(result)) application.register_function(get_active_tasks, 'get_active_tasks') def get_projects_pause_status(): result = {} for project_name, project in iteritems(self.projects): result[project_name] = project.paused return result application.register_function(get_projects_pause_status, 'get_projects_pause_status') def webui_update(): return { 'pause_status': get_projects_pause_status(), 'counter': { '5m_time': dump_counter('5m_time', 'avg'), '5m': dump_counter('5m', 'sum'), '1h': dump_counter('1h', 'sum'), '1d': dump_counter('1d', 'sum'), 'all': dump_counter('all', 'sum'), }, } application.register_function(webui_update, 'webui_update') import tornado.wsgi import tornado.ioloop import tornado.httpserver container = tornado.wsgi.WSGIContainer(application) self.xmlrpc_ioloop = tornado.ioloop.IOLoop() self.xmlrpc_server = tornado.httpserver.HTTPServer(container, io_loop=self.xmlrpc_ioloop) self.xmlrpc_server.listen(port=port, address=bind) logger.info('scheduler.xmlrpc listening on %s:%s', bind, port) self.xmlrpc_ioloop.start()
[ "def", "xmlrpc_run", "(", "self", ",", "port", "=", "23333", ",", "bind", "=", "'127.0.0.1'", ",", "logRequests", "=", "False", ")", ":", "from", "pyspider", ".", "libs", ".", "wsgi_xmlrpc", "import", "WSGIXMLRPCApplication", "application", "=", "WSGIXMLRPCApplication", "(", ")", "application", ".", "register_function", "(", "self", ".", "quit", ",", "'_quit'", ")", "application", ".", "register_function", "(", "self", ".", "__len__", ",", "'size'", ")", "def", "dump_counter", "(", "_time", ",", "_type", ")", ":", "try", ":", "return", "self", ".", "_cnt", "[", "_time", "]", ".", "to_dict", "(", "_type", ")", "except", ":", "logger", ".", "exception", "(", "''", ")", "application", ".", "register_function", "(", "dump_counter", ",", "'counter'", ")", "def", "new_task", "(", "task", ")", ":", "if", "self", ".", "task_verify", "(", "task", ")", ":", "self", ".", "newtask_queue", ".", "put", "(", "task", ")", "return", "True", "return", "False", "application", ".", "register_function", "(", "new_task", ",", "'newtask'", ")", "def", "send_task", "(", "task", ")", ":", "'''dispatch task to fetcher'''", "self", ".", "send_task", "(", "task", ")", "return", "True", "application", ".", "register_function", "(", "send_task", ",", "'send_task'", ")", "def", "update_project", "(", ")", ":", "self", ".", "_force_update_project", "=", "True", "application", ".", "register_function", "(", "update_project", ",", "'update_project'", ")", "def", "get_active_tasks", "(", "project", "=", "None", ",", "limit", "=", "100", ")", ":", "allowed_keys", "=", "set", "(", "(", "'type'", ",", "'taskid'", ",", "'project'", ",", "'status'", ",", "'url'", ",", "'lastcrawltime'", ",", "'updatetime'", ",", "'track'", ",", ")", ")", "track_allowed_keys", "=", "set", "(", "(", "'ok'", ",", "'time'", ",", "'follows'", ",", "'status_code'", ",", ")", ")", "iters", "=", "[", "iter", "(", "x", ".", "active_tasks", ")", "for", "k", ",", "x", "in", "iteritems", "(", "self", ".", "projects", ")", "if", "x", "and", "(", "k", "==", "project", "if", "project", "else", "True", ")", "]", "tasks", "=", "[", "next", "(", "x", ",", "None", ")", "for", "x", "in", "iters", "]", "result", "=", "[", "]", "while", "len", "(", "result", ")", "<", "limit", "and", "tasks", "and", "not", "all", "(", "x", "is", "None", "for", "x", "in", "tasks", ")", ":", "updatetime", ",", "task", "=", "t", "=", "max", "(", "t", "for", "t", "in", "tasks", "if", "t", ")", "i", "=", "tasks", ".", "index", "(", "t", ")", "tasks", "[", "i", "]", "=", "next", "(", "iters", "[", "i", "]", ",", "None", ")", "for", "key", "in", "list", "(", "task", ")", ":", "if", "key", "==", "'track'", ":", "for", "k", "in", "list", "(", "task", "[", "key", "]", ".", "get", "(", "'fetch'", ",", "[", "]", ")", ")", ":", "if", "k", "not", "in", "track_allowed_keys", ":", "del", "task", "[", "key", "]", "[", "'fetch'", "]", "[", "k", "]", "for", "k", "in", "list", "(", "task", "[", "key", "]", ".", "get", "(", "'process'", ",", "[", "]", ")", ")", ":", "if", "k", "not", "in", "track_allowed_keys", ":", "del", "task", "[", "key", "]", "[", "'process'", "]", "[", "k", "]", "if", "key", "in", "allowed_keys", ":", "continue", "del", "task", "[", "key", "]", "result", ".", "append", "(", "t", ")", "# fix for \"<type 'exceptions.TypeError'>:dictionary key must be string\"", "# have no idea why", "return", "json", ".", "loads", "(", "json", ".", "dumps", "(", "result", ")", ")", "application", ".", "register_function", "(", "get_active_tasks", ",", "'get_active_tasks'", ")", "def", "get_projects_pause_status", "(", ")", ":", "result", "=", "{", "}", "for", "project_name", ",", "project", "in", "iteritems", "(", "self", ".", "projects", ")", ":", "result", "[", "project_name", "]", "=", "project", ".", "paused", "return", "result", "application", ".", "register_function", "(", "get_projects_pause_status", ",", "'get_projects_pause_status'", ")", "def", "webui_update", "(", ")", ":", "return", "{", "'pause_status'", ":", "get_projects_pause_status", "(", ")", ",", "'counter'", ":", "{", "'5m_time'", ":", "dump_counter", "(", "'5m_time'", ",", "'avg'", ")", ",", "'5m'", ":", "dump_counter", "(", "'5m'", ",", "'sum'", ")", ",", "'1h'", ":", "dump_counter", "(", "'1h'", ",", "'sum'", ")", ",", "'1d'", ":", "dump_counter", "(", "'1d'", ",", "'sum'", ")", ",", "'all'", ":", "dump_counter", "(", "'all'", ",", "'sum'", ")", ",", "}", ",", "}", "application", ".", "register_function", "(", "webui_update", ",", "'webui_update'", ")", "import", "tornado", ".", "wsgi", "import", "tornado", ".", "ioloop", "import", "tornado", ".", "httpserver", "container", "=", "tornado", ".", "wsgi", ".", "WSGIContainer", "(", "application", ")", "self", ".", "xmlrpc_ioloop", "=", "tornado", ".", "ioloop", ".", "IOLoop", "(", ")", "self", ".", "xmlrpc_server", "=", "tornado", ".", "httpserver", ".", "HTTPServer", "(", "container", ",", "io_loop", "=", "self", ".", "xmlrpc_ioloop", ")", "self", ".", "xmlrpc_server", ".", "listen", "(", "port", "=", "port", ",", "address", "=", "bind", ")", "logger", ".", "info", "(", "'scheduler.xmlrpc listening on %s:%s'", ",", "bind", ",", "port", ")", "self", ".", "xmlrpc_ioloop", ".", "start", "(", ")" ]
Start xmlrpc interface
[ "Start", "xmlrpc", "interface" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L705-L811
train
binux/pyspider
pyspider/scheduler/scheduler.py
Scheduler.on_new_request
def on_new_request(self, task): '''Called when a new request is arrived''' task['status'] = self.taskdb.ACTIVE self.insert_task(task) self.put_task(task) project = task['project'] self._cnt['5m'].event((project, 'pending'), +1) self._cnt['1h'].event((project, 'pending'), +1) self._cnt['1d'].event((project, 'pending'), +1) self._cnt['all'].event((project, 'pending'), +1) logger.info('new task %(project)s:%(taskid)s %(url)s', task) return task
python
def on_new_request(self, task): '''Called when a new request is arrived''' task['status'] = self.taskdb.ACTIVE self.insert_task(task) self.put_task(task) project = task['project'] self._cnt['5m'].event((project, 'pending'), +1) self._cnt['1h'].event((project, 'pending'), +1) self._cnt['1d'].event((project, 'pending'), +1) self._cnt['all'].event((project, 'pending'), +1) logger.info('new task %(project)s:%(taskid)s %(url)s', task) return task
[ "def", "on_new_request", "(", "self", ",", "task", ")", ":", "task", "[", "'status'", "]", "=", "self", ".", "taskdb", ".", "ACTIVE", "self", ".", "insert_task", "(", "task", ")", "self", ".", "put_task", "(", "task", ")", "project", "=", "task", "[", "'project'", "]", "self", ".", "_cnt", "[", "'5m'", "]", ".", "event", "(", "(", "project", ",", "'pending'", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'1h'", "]", ".", "event", "(", "(", "project", ",", "'pending'", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'1d'", "]", ".", "event", "(", "(", "project", ",", "'pending'", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'all'", "]", ".", "event", "(", "(", "project", ",", "'pending'", ")", ",", "+", "1", ")", "logger", ".", "info", "(", "'new task %(project)s:%(taskid)s %(url)s'", ",", "task", ")", "return", "task" ]
Called when a new request is arrived
[ "Called", "when", "a", "new", "request", "is", "arrived" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L825-L837
train
binux/pyspider
pyspider/scheduler/scheduler.py
Scheduler.on_old_request
def on_old_request(self, task, old_task): '''Called when a crawled task is arrived''' now = time.time() _schedule = task.get('schedule', self.default_schedule) old_schedule = old_task.get('schedule', {}) if _schedule.get('force_update') and self.projects[task['project']].task_queue.is_processing(task['taskid']): # when a task is in processing, the modify may conflict with the running task. # postpone the modify after task finished. logger.info('postpone modify task %(project)s:%(taskid)s %(url)s', task) self._postpone_request.append(task) return restart = False schedule_age = _schedule.get('age', self.default_schedule['age']) if _schedule.get('itag') and _schedule['itag'] != old_schedule.get('itag'): restart = True elif schedule_age >= 0 and schedule_age + (old_task.get('lastcrawltime', 0) or 0) < now: restart = True elif _schedule.get('force_update'): restart = True if not restart: logger.debug('ignore newtask %(project)s:%(taskid)s %(url)s', task) return if _schedule.get('cancel'): logger.info('cancel task %(project)s:%(taskid)s %(url)s', task) task['status'] = self.taskdb.BAD self.update_task(task) self.projects[task['project']].task_queue.delete(task['taskid']) return task task['status'] = self.taskdb.ACTIVE self.update_task(task) self.put_task(task) project = task['project'] if old_task['status'] != self.taskdb.ACTIVE: self._cnt['5m'].event((project, 'pending'), +1) self._cnt['1h'].event((project, 'pending'), +1) self._cnt['1d'].event((project, 'pending'), +1) if old_task['status'] == self.taskdb.SUCCESS: self._cnt['all'].event((project, 'success'), -1).event((project, 'pending'), +1) elif old_task['status'] == self.taskdb.FAILED: self._cnt['all'].event((project, 'failed'), -1).event((project, 'pending'), +1) logger.info('restart task %(project)s:%(taskid)s %(url)s', task) return task
python
def on_old_request(self, task, old_task): '''Called when a crawled task is arrived''' now = time.time() _schedule = task.get('schedule', self.default_schedule) old_schedule = old_task.get('schedule', {}) if _schedule.get('force_update') and self.projects[task['project']].task_queue.is_processing(task['taskid']): # when a task is in processing, the modify may conflict with the running task. # postpone the modify after task finished. logger.info('postpone modify task %(project)s:%(taskid)s %(url)s', task) self._postpone_request.append(task) return restart = False schedule_age = _schedule.get('age', self.default_schedule['age']) if _schedule.get('itag') and _schedule['itag'] != old_schedule.get('itag'): restart = True elif schedule_age >= 0 and schedule_age + (old_task.get('lastcrawltime', 0) or 0) < now: restart = True elif _schedule.get('force_update'): restart = True if not restart: logger.debug('ignore newtask %(project)s:%(taskid)s %(url)s', task) return if _schedule.get('cancel'): logger.info('cancel task %(project)s:%(taskid)s %(url)s', task) task['status'] = self.taskdb.BAD self.update_task(task) self.projects[task['project']].task_queue.delete(task['taskid']) return task task['status'] = self.taskdb.ACTIVE self.update_task(task) self.put_task(task) project = task['project'] if old_task['status'] != self.taskdb.ACTIVE: self._cnt['5m'].event((project, 'pending'), +1) self._cnt['1h'].event((project, 'pending'), +1) self._cnt['1d'].event((project, 'pending'), +1) if old_task['status'] == self.taskdb.SUCCESS: self._cnt['all'].event((project, 'success'), -1).event((project, 'pending'), +1) elif old_task['status'] == self.taskdb.FAILED: self._cnt['all'].event((project, 'failed'), -1).event((project, 'pending'), +1) logger.info('restart task %(project)s:%(taskid)s %(url)s', task) return task
[ "def", "on_old_request", "(", "self", ",", "task", ",", "old_task", ")", ":", "now", "=", "time", ".", "time", "(", ")", "_schedule", "=", "task", ".", "get", "(", "'schedule'", ",", "self", ".", "default_schedule", ")", "old_schedule", "=", "old_task", ".", "get", "(", "'schedule'", ",", "{", "}", ")", "if", "_schedule", ".", "get", "(", "'force_update'", ")", "and", "self", ".", "projects", "[", "task", "[", "'project'", "]", "]", ".", "task_queue", ".", "is_processing", "(", "task", "[", "'taskid'", "]", ")", ":", "# when a task is in processing, the modify may conflict with the running task.", "# postpone the modify after task finished.", "logger", ".", "info", "(", "'postpone modify task %(project)s:%(taskid)s %(url)s'", ",", "task", ")", "self", ".", "_postpone_request", ".", "append", "(", "task", ")", "return", "restart", "=", "False", "schedule_age", "=", "_schedule", ".", "get", "(", "'age'", ",", "self", ".", "default_schedule", "[", "'age'", "]", ")", "if", "_schedule", ".", "get", "(", "'itag'", ")", "and", "_schedule", "[", "'itag'", "]", "!=", "old_schedule", ".", "get", "(", "'itag'", ")", ":", "restart", "=", "True", "elif", "schedule_age", ">=", "0", "and", "schedule_age", "+", "(", "old_task", ".", "get", "(", "'lastcrawltime'", ",", "0", ")", "or", "0", ")", "<", "now", ":", "restart", "=", "True", "elif", "_schedule", ".", "get", "(", "'force_update'", ")", ":", "restart", "=", "True", "if", "not", "restart", ":", "logger", ".", "debug", "(", "'ignore newtask %(project)s:%(taskid)s %(url)s'", ",", "task", ")", "return", "if", "_schedule", ".", "get", "(", "'cancel'", ")", ":", "logger", ".", "info", "(", "'cancel task %(project)s:%(taskid)s %(url)s'", ",", "task", ")", "task", "[", "'status'", "]", "=", "self", ".", "taskdb", ".", "BAD", "self", ".", "update_task", "(", "task", ")", "self", ".", "projects", "[", "task", "[", "'project'", "]", "]", ".", "task_queue", ".", "delete", "(", "task", "[", "'taskid'", "]", ")", "return", "task", "task", "[", "'status'", "]", "=", "self", ".", "taskdb", ".", "ACTIVE", "self", ".", "update_task", "(", "task", ")", "self", ".", "put_task", "(", "task", ")", "project", "=", "task", "[", "'project'", "]", "if", "old_task", "[", "'status'", "]", "!=", "self", ".", "taskdb", ".", "ACTIVE", ":", "self", ".", "_cnt", "[", "'5m'", "]", ".", "event", "(", "(", "project", ",", "'pending'", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'1h'", "]", ".", "event", "(", "(", "project", ",", "'pending'", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'1d'", "]", ".", "event", "(", "(", "project", ",", "'pending'", ")", ",", "+", "1", ")", "if", "old_task", "[", "'status'", "]", "==", "self", ".", "taskdb", ".", "SUCCESS", ":", "self", ".", "_cnt", "[", "'all'", "]", ".", "event", "(", "(", "project", ",", "'success'", ")", ",", "-", "1", ")", ".", "event", "(", "(", "project", ",", "'pending'", ")", ",", "+", "1", ")", "elif", "old_task", "[", "'status'", "]", "==", "self", ".", "taskdb", ".", "FAILED", ":", "self", ".", "_cnt", "[", "'all'", "]", ".", "event", "(", "(", "project", ",", "'failed'", ")", ",", "-", "1", ")", ".", "event", "(", "(", "project", ",", "'pending'", ")", ",", "+", "1", ")", "logger", ".", "info", "(", "'restart task %(project)s:%(taskid)s %(url)s'", ",", "task", ")", "return", "task" ]
Called when a crawled task is arrived
[ "Called", "when", "a", "crawled", "task", "is", "arrived" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L839-L887
train
binux/pyspider
pyspider/scheduler/scheduler.py
Scheduler.on_task_status
def on_task_status(self, task): '''Called when a status pack is arrived''' try: procesok = task['track']['process']['ok'] if not self.projects[task['project']].task_queue.done(task['taskid']): logging.error('not processing pack: %(project)s:%(taskid)s %(url)s', task) return None except KeyError as e: logger.error("Bad status pack: %s", e) return None if procesok: ret = self.on_task_done(task) else: ret = self.on_task_failed(task) if task['track']['fetch'].get('time'): self._cnt['5m_time'].event((task['project'], 'fetch_time'), task['track']['fetch']['time']) if task['track']['process'].get('time'): self._cnt['5m_time'].event((task['project'], 'process_time'), task['track']['process'].get('time')) self.projects[task['project']].active_tasks.appendleft((time.time(), task)) return ret
python
def on_task_status(self, task): '''Called when a status pack is arrived''' try: procesok = task['track']['process']['ok'] if not self.projects[task['project']].task_queue.done(task['taskid']): logging.error('not processing pack: %(project)s:%(taskid)s %(url)s', task) return None except KeyError as e: logger.error("Bad status pack: %s", e) return None if procesok: ret = self.on_task_done(task) else: ret = self.on_task_failed(task) if task['track']['fetch'].get('time'): self._cnt['5m_time'].event((task['project'], 'fetch_time'), task['track']['fetch']['time']) if task['track']['process'].get('time'): self._cnt['5m_time'].event((task['project'], 'process_time'), task['track']['process'].get('time')) self.projects[task['project']].active_tasks.appendleft((time.time(), task)) return ret
[ "def", "on_task_status", "(", "self", ",", "task", ")", ":", "try", ":", "procesok", "=", "task", "[", "'track'", "]", "[", "'process'", "]", "[", "'ok'", "]", "if", "not", "self", ".", "projects", "[", "task", "[", "'project'", "]", "]", ".", "task_queue", ".", "done", "(", "task", "[", "'taskid'", "]", ")", ":", "logging", ".", "error", "(", "'not processing pack: %(project)s:%(taskid)s %(url)s'", ",", "task", ")", "return", "None", "except", "KeyError", "as", "e", ":", "logger", ".", "error", "(", "\"Bad status pack: %s\"", ",", "e", ")", "return", "None", "if", "procesok", ":", "ret", "=", "self", ".", "on_task_done", "(", "task", ")", "else", ":", "ret", "=", "self", ".", "on_task_failed", "(", "task", ")", "if", "task", "[", "'track'", "]", "[", "'fetch'", "]", ".", "get", "(", "'time'", ")", ":", "self", ".", "_cnt", "[", "'5m_time'", "]", ".", "event", "(", "(", "task", "[", "'project'", "]", ",", "'fetch_time'", ")", ",", "task", "[", "'track'", "]", "[", "'fetch'", "]", "[", "'time'", "]", ")", "if", "task", "[", "'track'", "]", "[", "'process'", "]", ".", "get", "(", "'time'", ")", ":", "self", ".", "_cnt", "[", "'5m_time'", "]", ".", "event", "(", "(", "task", "[", "'project'", "]", ",", "'process_time'", ")", ",", "task", "[", "'track'", "]", "[", "'process'", "]", ".", "get", "(", "'time'", ")", ")", "self", ".", "projects", "[", "task", "[", "'project'", "]", "]", ".", "active_tasks", ".", "appendleft", "(", "(", "time", ".", "time", "(", ")", ",", "task", ")", ")", "return", "ret" ]
Called when a status pack is arrived
[ "Called", "when", "a", "status", "pack", "is", "arrived" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L889-L912
train
binux/pyspider
pyspider/scheduler/scheduler.py
Scheduler.on_task_done
def on_task_done(self, task): '''Called when a task is done and success, called by `on_task_status`''' task['status'] = self.taskdb.SUCCESS task['lastcrawltime'] = time.time() if 'schedule' in task: if task['schedule'].get('auto_recrawl') and 'age' in task['schedule']: task['status'] = self.taskdb.ACTIVE next_exetime = task['schedule'].get('age') task['schedule']['exetime'] = time.time() + next_exetime self.put_task(task) else: del task['schedule'] self.update_task(task) project = task['project'] self._cnt['5m'].event((project, 'success'), +1) self._cnt['1h'].event((project, 'success'), +1) self._cnt['1d'].event((project, 'success'), +1) self._cnt['all'].event((project, 'success'), +1).event((project, 'pending'), -1) logger.info('task done %(project)s:%(taskid)s %(url)s', task) return task
python
def on_task_done(self, task): '''Called when a task is done and success, called by `on_task_status`''' task['status'] = self.taskdb.SUCCESS task['lastcrawltime'] = time.time() if 'schedule' in task: if task['schedule'].get('auto_recrawl') and 'age' in task['schedule']: task['status'] = self.taskdb.ACTIVE next_exetime = task['schedule'].get('age') task['schedule']['exetime'] = time.time() + next_exetime self.put_task(task) else: del task['schedule'] self.update_task(task) project = task['project'] self._cnt['5m'].event((project, 'success'), +1) self._cnt['1h'].event((project, 'success'), +1) self._cnt['1d'].event((project, 'success'), +1) self._cnt['all'].event((project, 'success'), +1).event((project, 'pending'), -1) logger.info('task done %(project)s:%(taskid)s %(url)s', task) return task
[ "def", "on_task_done", "(", "self", ",", "task", ")", ":", "task", "[", "'status'", "]", "=", "self", ".", "taskdb", ".", "SUCCESS", "task", "[", "'lastcrawltime'", "]", "=", "time", ".", "time", "(", ")", "if", "'schedule'", "in", "task", ":", "if", "task", "[", "'schedule'", "]", ".", "get", "(", "'auto_recrawl'", ")", "and", "'age'", "in", "task", "[", "'schedule'", "]", ":", "task", "[", "'status'", "]", "=", "self", ".", "taskdb", ".", "ACTIVE", "next_exetime", "=", "task", "[", "'schedule'", "]", ".", "get", "(", "'age'", ")", "task", "[", "'schedule'", "]", "[", "'exetime'", "]", "=", "time", ".", "time", "(", ")", "+", "next_exetime", "self", ".", "put_task", "(", "task", ")", "else", ":", "del", "task", "[", "'schedule'", "]", "self", ".", "update_task", "(", "task", ")", "project", "=", "task", "[", "'project'", "]", "self", ".", "_cnt", "[", "'5m'", "]", ".", "event", "(", "(", "project", ",", "'success'", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'1h'", "]", ".", "event", "(", "(", "project", ",", "'success'", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'1d'", "]", ".", "event", "(", "(", "project", ",", "'success'", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'all'", "]", ".", "event", "(", "(", "project", ",", "'success'", ")", ",", "+", "1", ")", ".", "event", "(", "(", "project", ",", "'pending'", ")", ",", "-", "1", ")", "logger", ".", "info", "(", "'task done %(project)s:%(taskid)s %(url)s'", ",", "task", ")", "return", "task" ]
Called when a task is done and success, called by `on_task_status`
[ "Called", "when", "a", "task", "is", "done", "and", "success", "called", "by", "on_task_status" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L914-L935
train
binux/pyspider
pyspider/scheduler/scheduler.py
Scheduler.on_task_failed
def on_task_failed(self, task): '''Called when a task is failed, called by `on_task_status`''' if 'schedule' not in task: old_task = self.taskdb.get_task(task['project'], task['taskid'], fields=['schedule']) if old_task is None: logging.error('unknown status pack: %s' % task) return task['schedule'] = old_task.get('schedule', {}) retries = task['schedule'].get('retries', self.default_schedule['retries']) retried = task['schedule'].get('retried', 0) project_info = self.projects[task['project']] retry_delay = project_info.retry_delay or self.DEFAULT_RETRY_DELAY next_exetime = retry_delay.get(retried, retry_delay.get('', self.DEFAULT_RETRY_DELAY[''])) if task['schedule'].get('auto_recrawl') and 'age' in task['schedule']: next_exetime = min(next_exetime, task['schedule'].get('age')) else: if retried >= retries: next_exetime = -1 elif 'age' in task['schedule'] and next_exetime > task['schedule'].get('age'): next_exetime = task['schedule'].get('age') if next_exetime < 0: task['status'] = self.taskdb.FAILED task['lastcrawltime'] = time.time() self.update_task(task) project = task['project'] self._cnt['5m'].event((project, 'failed'), +1) self._cnt['1h'].event((project, 'failed'), +1) self._cnt['1d'].event((project, 'failed'), +1) self._cnt['all'].event((project, 'failed'), +1).event((project, 'pending'), -1) logger.info('task failed %(project)s:%(taskid)s %(url)s' % task) return task else: task['schedule']['retried'] = retried + 1 task['schedule']['exetime'] = time.time() + next_exetime task['lastcrawltime'] = time.time() self.update_task(task) self.put_task(task) project = task['project'] self._cnt['5m'].event((project, 'retry'), +1) self._cnt['1h'].event((project, 'retry'), +1) self._cnt['1d'].event((project, 'retry'), +1) # self._cnt['all'].event((project, 'retry'), +1) logger.info('task retry %d/%d %%(project)s:%%(taskid)s %%(url)s' % ( retried, retries), task) return task
python
def on_task_failed(self, task): '''Called when a task is failed, called by `on_task_status`''' if 'schedule' not in task: old_task = self.taskdb.get_task(task['project'], task['taskid'], fields=['schedule']) if old_task is None: logging.error('unknown status pack: %s' % task) return task['schedule'] = old_task.get('schedule', {}) retries = task['schedule'].get('retries', self.default_schedule['retries']) retried = task['schedule'].get('retried', 0) project_info = self.projects[task['project']] retry_delay = project_info.retry_delay or self.DEFAULT_RETRY_DELAY next_exetime = retry_delay.get(retried, retry_delay.get('', self.DEFAULT_RETRY_DELAY[''])) if task['schedule'].get('auto_recrawl') and 'age' in task['schedule']: next_exetime = min(next_exetime, task['schedule'].get('age')) else: if retried >= retries: next_exetime = -1 elif 'age' in task['schedule'] and next_exetime > task['schedule'].get('age'): next_exetime = task['schedule'].get('age') if next_exetime < 0: task['status'] = self.taskdb.FAILED task['lastcrawltime'] = time.time() self.update_task(task) project = task['project'] self._cnt['5m'].event((project, 'failed'), +1) self._cnt['1h'].event((project, 'failed'), +1) self._cnt['1d'].event((project, 'failed'), +1) self._cnt['all'].event((project, 'failed'), +1).event((project, 'pending'), -1) logger.info('task failed %(project)s:%(taskid)s %(url)s' % task) return task else: task['schedule']['retried'] = retried + 1 task['schedule']['exetime'] = time.time() + next_exetime task['lastcrawltime'] = time.time() self.update_task(task) self.put_task(task) project = task['project'] self._cnt['5m'].event((project, 'retry'), +1) self._cnt['1h'].event((project, 'retry'), +1) self._cnt['1d'].event((project, 'retry'), +1) # self._cnt['all'].event((project, 'retry'), +1) logger.info('task retry %d/%d %%(project)s:%%(taskid)s %%(url)s' % ( retried, retries), task) return task
[ "def", "on_task_failed", "(", "self", ",", "task", ")", ":", "if", "'schedule'", "not", "in", "task", ":", "old_task", "=", "self", ".", "taskdb", ".", "get_task", "(", "task", "[", "'project'", "]", ",", "task", "[", "'taskid'", "]", ",", "fields", "=", "[", "'schedule'", "]", ")", "if", "old_task", "is", "None", ":", "logging", ".", "error", "(", "'unknown status pack: %s'", "%", "task", ")", "return", "task", "[", "'schedule'", "]", "=", "old_task", ".", "get", "(", "'schedule'", ",", "{", "}", ")", "retries", "=", "task", "[", "'schedule'", "]", ".", "get", "(", "'retries'", ",", "self", ".", "default_schedule", "[", "'retries'", "]", ")", "retried", "=", "task", "[", "'schedule'", "]", ".", "get", "(", "'retried'", ",", "0", ")", "project_info", "=", "self", ".", "projects", "[", "task", "[", "'project'", "]", "]", "retry_delay", "=", "project_info", ".", "retry_delay", "or", "self", ".", "DEFAULT_RETRY_DELAY", "next_exetime", "=", "retry_delay", ".", "get", "(", "retried", ",", "retry_delay", ".", "get", "(", "''", ",", "self", ".", "DEFAULT_RETRY_DELAY", "[", "''", "]", ")", ")", "if", "task", "[", "'schedule'", "]", ".", "get", "(", "'auto_recrawl'", ")", "and", "'age'", "in", "task", "[", "'schedule'", "]", ":", "next_exetime", "=", "min", "(", "next_exetime", ",", "task", "[", "'schedule'", "]", ".", "get", "(", "'age'", ")", ")", "else", ":", "if", "retried", ">=", "retries", ":", "next_exetime", "=", "-", "1", "elif", "'age'", "in", "task", "[", "'schedule'", "]", "and", "next_exetime", ">", "task", "[", "'schedule'", "]", ".", "get", "(", "'age'", ")", ":", "next_exetime", "=", "task", "[", "'schedule'", "]", ".", "get", "(", "'age'", ")", "if", "next_exetime", "<", "0", ":", "task", "[", "'status'", "]", "=", "self", ".", "taskdb", ".", "FAILED", "task", "[", "'lastcrawltime'", "]", "=", "time", ".", "time", "(", ")", "self", ".", "update_task", "(", "task", ")", "project", "=", "task", "[", "'project'", "]", "self", ".", "_cnt", "[", "'5m'", "]", ".", "event", "(", "(", "project", ",", "'failed'", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'1h'", "]", ".", "event", "(", "(", "project", ",", "'failed'", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'1d'", "]", ".", "event", "(", "(", "project", ",", "'failed'", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'all'", "]", ".", "event", "(", "(", "project", ",", "'failed'", ")", ",", "+", "1", ")", ".", "event", "(", "(", "project", ",", "'pending'", ")", ",", "-", "1", ")", "logger", ".", "info", "(", "'task failed %(project)s:%(taskid)s %(url)s'", "%", "task", ")", "return", "task", "else", ":", "task", "[", "'schedule'", "]", "[", "'retried'", "]", "=", "retried", "+", "1", "task", "[", "'schedule'", "]", "[", "'exetime'", "]", "=", "time", ".", "time", "(", ")", "+", "next_exetime", "task", "[", "'lastcrawltime'", "]", "=", "time", ".", "time", "(", ")", "self", ".", "update_task", "(", "task", ")", "self", ".", "put_task", "(", "task", ")", "project", "=", "task", "[", "'project'", "]", "self", ".", "_cnt", "[", "'5m'", "]", ".", "event", "(", "(", "project", ",", "'retry'", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'1h'", "]", ".", "event", "(", "(", "project", ",", "'retry'", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'1d'", "]", ".", "event", "(", "(", "project", ",", "'retry'", ")", ",", "+", "1", ")", "# self._cnt['all'].event((project, 'retry'), +1)", "logger", ".", "info", "(", "'task retry %d/%d %%(project)s:%%(taskid)s %%(url)s'", "%", "(", "retried", ",", "retries", ")", ",", "task", ")", "return", "task" ]
Called when a task is failed, called by `on_task_status`
[ "Called", "when", "a", "task", "is", "failed", "called", "by", "on_task_status" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L937-L988
train
binux/pyspider
pyspider/scheduler/scheduler.py
Scheduler.on_select_task
def on_select_task(self, task): '''Called when a task is selected to fetch & process''' # inject informations about project logger.info('select %(project)s:%(taskid)s %(url)s', task) project_info = self.projects.get(task['project']) assert project_info, 'no such project' task['type'] = self.TASK_PACK task['group'] = project_info.group task['project_md5sum'] = project_info.md5sum task['project_updatetime'] = project_info.updatetime # lazy join project.crawl_config if getattr(project_info, 'crawl_config', None): task = BaseHandler.task_join_crawl_config(task, project_info.crawl_config) project_info.active_tasks.appendleft((time.time(), task)) self.send_task(task) return task
python
def on_select_task(self, task): '''Called when a task is selected to fetch & process''' # inject informations about project logger.info('select %(project)s:%(taskid)s %(url)s', task) project_info = self.projects.get(task['project']) assert project_info, 'no such project' task['type'] = self.TASK_PACK task['group'] = project_info.group task['project_md5sum'] = project_info.md5sum task['project_updatetime'] = project_info.updatetime # lazy join project.crawl_config if getattr(project_info, 'crawl_config', None): task = BaseHandler.task_join_crawl_config(task, project_info.crawl_config) project_info.active_tasks.appendleft((time.time(), task)) self.send_task(task) return task
[ "def", "on_select_task", "(", "self", ",", "task", ")", ":", "# inject informations about project", "logger", ".", "info", "(", "'select %(project)s:%(taskid)s %(url)s'", ",", "task", ")", "project_info", "=", "self", ".", "projects", ".", "get", "(", "task", "[", "'project'", "]", ")", "assert", "project_info", ",", "'no such project'", "task", "[", "'type'", "]", "=", "self", ".", "TASK_PACK", "task", "[", "'group'", "]", "=", "project_info", ".", "group", "task", "[", "'project_md5sum'", "]", "=", "project_info", ".", "md5sum", "task", "[", "'project_updatetime'", "]", "=", "project_info", ".", "updatetime", "# lazy join project.crawl_config", "if", "getattr", "(", "project_info", ",", "'crawl_config'", ",", "None", ")", ":", "task", "=", "BaseHandler", ".", "task_join_crawl_config", "(", "task", ",", "project_info", ".", "crawl_config", ")", "project_info", ".", "active_tasks", ".", "appendleft", "(", "(", "time", ".", "time", "(", ")", ",", "task", ")", ")", "self", ".", "send_task", "(", "task", ")", "return", "task" ]
Called when a task is selected to fetch & process
[ "Called", "when", "a", "task", "is", "selected", "to", "fetch", "&", "process" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L990-L1008
train
binux/pyspider
pyspider/scheduler/scheduler.py
OneScheduler._check_select
def _check_select(self): """ interactive mode of select tasks """ if not self.interactive: return super(OneScheduler, self)._check_select() # waiting for running tasks if self.running_task > 0: return is_crawled = [] def run(project=None): return crawl('on_start', project=project) def crawl(url, project=None, **kwargs): """ Crawl given url, same parameters as BaseHandler.crawl url - url or taskid, parameters will be used if in taskdb project - can be ignored if only one project exists. """ # looking up the project instance if project is None: if len(self.projects) == 1: project = list(self.projects.keys())[0] else: raise LookupError('You need specify the project: %r' % list(self.projects.keys())) project_data = self.processor.project_manager.get(project) if not project_data: raise LookupError('no such project: %s' % project) # get task package instance = project_data['instance'] instance._reset() task = instance.crawl(url, **kwargs) if isinstance(task, list): raise Exception('url list is not allowed in interactive mode') # check task in taskdb if not kwargs: dbtask = self.taskdb.get_task(task['project'], task['taskid'], fields=self.request_task_fields) if not dbtask: dbtask = self.taskdb.get_task(task['project'], task['url'], fields=self.request_task_fields) if dbtask: task = dbtask # select the task self.on_select_task(task) is_crawled.append(True) shell.ask_exit() def quit_interactive(): '''Quit interactive mode''' is_crawled.append(True) self.interactive = False shell.ask_exit() def quit_pyspider(): '''Close pyspider''' is_crawled[:] = [] shell.ask_exit() shell = utils.get_python_console() banner = ( 'pyspider shell - Select task\n' 'crawl(url, project=None, **kwargs) - same parameters as BaseHandler.crawl\n' 'quit_interactive() - Quit interactive mode\n' 'quit_pyspider() - Close pyspider' ) if hasattr(shell, 'show_banner'): shell.show_banner(banner) shell.interact() else: shell.interact(banner) if not is_crawled: self.ioloop.add_callback(self.ioloop.stop)
python
def _check_select(self): """ interactive mode of select tasks """ if not self.interactive: return super(OneScheduler, self)._check_select() # waiting for running tasks if self.running_task > 0: return is_crawled = [] def run(project=None): return crawl('on_start', project=project) def crawl(url, project=None, **kwargs): """ Crawl given url, same parameters as BaseHandler.crawl url - url or taskid, parameters will be used if in taskdb project - can be ignored if only one project exists. """ # looking up the project instance if project is None: if len(self.projects) == 1: project = list(self.projects.keys())[0] else: raise LookupError('You need specify the project: %r' % list(self.projects.keys())) project_data = self.processor.project_manager.get(project) if not project_data: raise LookupError('no such project: %s' % project) # get task package instance = project_data['instance'] instance._reset() task = instance.crawl(url, **kwargs) if isinstance(task, list): raise Exception('url list is not allowed in interactive mode') # check task in taskdb if not kwargs: dbtask = self.taskdb.get_task(task['project'], task['taskid'], fields=self.request_task_fields) if not dbtask: dbtask = self.taskdb.get_task(task['project'], task['url'], fields=self.request_task_fields) if dbtask: task = dbtask # select the task self.on_select_task(task) is_crawled.append(True) shell.ask_exit() def quit_interactive(): '''Quit interactive mode''' is_crawled.append(True) self.interactive = False shell.ask_exit() def quit_pyspider(): '''Close pyspider''' is_crawled[:] = [] shell.ask_exit() shell = utils.get_python_console() banner = ( 'pyspider shell - Select task\n' 'crawl(url, project=None, **kwargs) - same parameters as BaseHandler.crawl\n' 'quit_interactive() - Quit interactive mode\n' 'quit_pyspider() - Close pyspider' ) if hasattr(shell, 'show_banner'): shell.show_banner(banner) shell.interact() else: shell.interact(banner) if not is_crawled: self.ioloop.add_callback(self.ioloop.stop)
[ "def", "_check_select", "(", "self", ")", ":", "if", "not", "self", ".", "interactive", ":", "return", "super", "(", "OneScheduler", ",", "self", ")", ".", "_check_select", "(", ")", "# waiting for running tasks", "if", "self", ".", "running_task", ">", "0", ":", "return", "is_crawled", "=", "[", "]", "def", "run", "(", "project", "=", "None", ")", ":", "return", "crawl", "(", "'on_start'", ",", "project", "=", "project", ")", "def", "crawl", "(", "url", ",", "project", "=", "None", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Crawl given url, same parameters as BaseHandler.crawl\n\n url - url or taskid, parameters will be used if in taskdb\n project - can be ignored if only one project exists.\n \"\"\"", "# looking up the project instance", "if", "project", "is", "None", ":", "if", "len", "(", "self", ".", "projects", ")", "==", "1", ":", "project", "=", "list", "(", "self", ".", "projects", ".", "keys", "(", ")", ")", "[", "0", "]", "else", ":", "raise", "LookupError", "(", "'You need specify the project: %r'", "%", "list", "(", "self", ".", "projects", ".", "keys", "(", ")", ")", ")", "project_data", "=", "self", ".", "processor", ".", "project_manager", ".", "get", "(", "project", ")", "if", "not", "project_data", ":", "raise", "LookupError", "(", "'no such project: %s'", "%", "project", ")", "# get task package", "instance", "=", "project_data", "[", "'instance'", "]", "instance", ".", "_reset", "(", ")", "task", "=", "instance", ".", "crawl", "(", "url", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "task", ",", "list", ")", ":", "raise", "Exception", "(", "'url list is not allowed in interactive mode'", ")", "# check task in taskdb", "if", "not", "kwargs", ":", "dbtask", "=", "self", ".", "taskdb", ".", "get_task", "(", "task", "[", "'project'", "]", ",", "task", "[", "'taskid'", "]", ",", "fields", "=", "self", ".", "request_task_fields", ")", "if", "not", "dbtask", ":", "dbtask", "=", "self", ".", "taskdb", ".", "get_task", "(", "task", "[", "'project'", "]", ",", "task", "[", "'url'", "]", ",", "fields", "=", "self", ".", "request_task_fields", ")", "if", "dbtask", ":", "task", "=", "dbtask", "# select the task", "self", ".", "on_select_task", "(", "task", ")", "is_crawled", ".", "append", "(", "True", ")", "shell", ".", "ask_exit", "(", ")", "def", "quit_interactive", "(", ")", ":", "'''Quit interactive mode'''", "is_crawled", ".", "append", "(", "True", ")", "self", ".", "interactive", "=", "False", "shell", ".", "ask_exit", "(", ")", "def", "quit_pyspider", "(", ")", ":", "'''Close pyspider'''", "is_crawled", "[", ":", "]", "=", "[", "]", "shell", ".", "ask_exit", "(", ")", "shell", "=", "utils", ".", "get_python_console", "(", ")", "banner", "=", "(", "'pyspider shell - Select task\\n'", "'crawl(url, project=None, **kwargs) - same parameters as BaseHandler.crawl\\n'", "'quit_interactive() - Quit interactive mode\\n'", "'quit_pyspider() - Close pyspider'", ")", "if", "hasattr", "(", "shell", ",", "'show_banner'", ")", ":", "shell", ".", "show_banner", "(", "banner", ")", "shell", ".", "interact", "(", ")", "else", ":", "shell", ".", "interact", "(", "banner", ")", "if", "not", "is_crawled", ":", "self", ".", "ioloop", ".", "add_callback", "(", "self", ".", "ioloop", ".", "stop", ")" ]
interactive mode of select tasks
[ "interactive", "mode", "of", "select", "tasks" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L1022-L1104
train
binux/pyspider
pyspider/scheduler/scheduler.py
OneScheduler.on_task_status
def on_task_status(self, task): """Ignore not processing error in interactive mode""" if not self.interactive: super(OneScheduler, self).on_task_status(task) try: procesok = task['track']['process']['ok'] except KeyError as e: logger.error("Bad status pack: %s", e) return None if procesok: ret = self.on_task_done(task) else: ret = self.on_task_failed(task) if task['track']['fetch'].get('time'): self._cnt['5m_time'].event((task['project'], 'fetch_time'), task['track']['fetch']['time']) if task['track']['process'].get('time'): self._cnt['5m_time'].event((task['project'], 'process_time'), task['track']['process'].get('time')) self.projects[task['project']].active_tasks.appendleft((time.time(), task)) return ret
python
def on_task_status(self, task): """Ignore not processing error in interactive mode""" if not self.interactive: super(OneScheduler, self).on_task_status(task) try: procesok = task['track']['process']['ok'] except KeyError as e: logger.error("Bad status pack: %s", e) return None if procesok: ret = self.on_task_done(task) else: ret = self.on_task_failed(task) if task['track']['fetch'].get('time'): self._cnt['5m_time'].event((task['project'], 'fetch_time'), task['track']['fetch']['time']) if task['track']['process'].get('time'): self._cnt['5m_time'].event((task['project'], 'process_time'), task['track']['process'].get('time')) self.projects[task['project']].active_tasks.appendleft((time.time(), task)) return ret
[ "def", "on_task_status", "(", "self", ",", "task", ")", ":", "if", "not", "self", ".", "interactive", ":", "super", "(", "OneScheduler", ",", "self", ")", ".", "on_task_status", "(", "task", ")", "try", ":", "procesok", "=", "task", "[", "'track'", "]", "[", "'process'", "]", "[", "'ok'", "]", "except", "KeyError", "as", "e", ":", "logger", ".", "error", "(", "\"Bad status pack: %s\"", ",", "e", ")", "return", "None", "if", "procesok", ":", "ret", "=", "self", ".", "on_task_done", "(", "task", ")", "else", ":", "ret", "=", "self", ".", "on_task_failed", "(", "task", ")", "if", "task", "[", "'track'", "]", "[", "'fetch'", "]", ".", "get", "(", "'time'", ")", ":", "self", ".", "_cnt", "[", "'5m_time'", "]", ".", "event", "(", "(", "task", "[", "'project'", "]", ",", "'fetch_time'", ")", ",", "task", "[", "'track'", "]", "[", "'fetch'", "]", "[", "'time'", "]", ")", "if", "task", "[", "'track'", "]", "[", "'process'", "]", ".", "get", "(", "'time'", ")", ":", "self", ".", "_cnt", "[", "'5m_time'", "]", ".", "event", "(", "(", "task", "[", "'project'", "]", ",", "'process_time'", ")", ",", "task", "[", "'track'", "]", "[", "'process'", "]", ".", "get", "(", "'time'", ")", ")", "self", ".", "projects", "[", "task", "[", "'project'", "]", "]", ".", "active_tasks", ".", "appendleft", "(", "(", "time", ".", "time", "(", ")", ",", "task", ")", ")", "return", "ret" ]
Ignore not processing error in interactive mode
[ "Ignore", "not", "processing", "error", "in", "interactive", "mode" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L1112-L1134
train
binux/pyspider
pyspider/processor/project_module.py
ProjectManager.build_module
def build_module(project, env=None): '''Build project script as module''' from pyspider.libs import base_handler assert 'name' in project, 'need name of project' assert 'script' in project, 'need script of project' if env is None: env = {} # fix for old non-package version scripts pyspider_path = os.path.join(os.path.dirname(__file__), "..") if pyspider_path not in sys.path: sys.path.insert(1, pyspider_path) env = dict(env) env.update({ 'debug': project.get('status', 'DEBUG') == 'DEBUG', }) loader = ProjectLoader(project) module = loader.load_module(project['name']) # logger inject module.log_buffer = [] module.logging = module.logger = logging.Logger(project['name']) if env.get('enable_stdout_capture', True): handler = SaveLogHandler(module.log_buffer) handler.setFormatter(LogFormatter(color=False)) else: handler = logging.StreamHandler() handler.setFormatter(LogFormatter(color=True)) module.logger.addHandler(handler) if '__handler_cls__' not in module.__dict__: BaseHandler = module.__dict__.get('BaseHandler', base_handler.BaseHandler) for each in list(six.itervalues(module.__dict__)): if inspect.isclass(each) and each is not BaseHandler \ and issubclass(each, BaseHandler): module.__dict__['__handler_cls__'] = each _class = module.__dict__.get('__handler_cls__') assert _class is not None, "need BaseHandler in project module" instance = _class() instance.__env__ = env instance.project_name = project['name'] instance.project = project return { 'loader': loader, 'module': module, 'class': _class, 'instance': instance, 'exception': None, 'exception_log': '', 'info': project, 'load_time': time.time(), }
python
def build_module(project, env=None): '''Build project script as module''' from pyspider.libs import base_handler assert 'name' in project, 'need name of project' assert 'script' in project, 'need script of project' if env is None: env = {} # fix for old non-package version scripts pyspider_path = os.path.join(os.path.dirname(__file__), "..") if pyspider_path not in sys.path: sys.path.insert(1, pyspider_path) env = dict(env) env.update({ 'debug': project.get('status', 'DEBUG') == 'DEBUG', }) loader = ProjectLoader(project) module = loader.load_module(project['name']) # logger inject module.log_buffer = [] module.logging = module.logger = logging.Logger(project['name']) if env.get('enable_stdout_capture', True): handler = SaveLogHandler(module.log_buffer) handler.setFormatter(LogFormatter(color=False)) else: handler = logging.StreamHandler() handler.setFormatter(LogFormatter(color=True)) module.logger.addHandler(handler) if '__handler_cls__' not in module.__dict__: BaseHandler = module.__dict__.get('BaseHandler', base_handler.BaseHandler) for each in list(six.itervalues(module.__dict__)): if inspect.isclass(each) and each is not BaseHandler \ and issubclass(each, BaseHandler): module.__dict__['__handler_cls__'] = each _class = module.__dict__.get('__handler_cls__') assert _class is not None, "need BaseHandler in project module" instance = _class() instance.__env__ = env instance.project_name = project['name'] instance.project = project return { 'loader': loader, 'module': module, 'class': _class, 'instance': instance, 'exception': None, 'exception_log': '', 'info': project, 'load_time': time.time(), }
[ "def", "build_module", "(", "project", ",", "env", "=", "None", ")", ":", "from", "pyspider", ".", "libs", "import", "base_handler", "assert", "'name'", "in", "project", ",", "'need name of project'", "assert", "'script'", "in", "project", ",", "'need script of project'", "if", "env", "is", "None", ":", "env", "=", "{", "}", "# fix for old non-package version scripts", "pyspider_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"..\"", ")", "if", "pyspider_path", "not", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "insert", "(", "1", ",", "pyspider_path", ")", "env", "=", "dict", "(", "env", ")", "env", ".", "update", "(", "{", "'debug'", ":", "project", ".", "get", "(", "'status'", ",", "'DEBUG'", ")", "==", "'DEBUG'", ",", "}", ")", "loader", "=", "ProjectLoader", "(", "project", ")", "module", "=", "loader", ".", "load_module", "(", "project", "[", "'name'", "]", ")", "# logger inject", "module", ".", "log_buffer", "=", "[", "]", "module", ".", "logging", "=", "module", ".", "logger", "=", "logging", ".", "Logger", "(", "project", "[", "'name'", "]", ")", "if", "env", ".", "get", "(", "'enable_stdout_capture'", ",", "True", ")", ":", "handler", "=", "SaveLogHandler", "(", "module", ".", "log_buffer", ")", "handler", ".", "setFormatter", "(", "LogFormatter", "(", "color", "=", "False", ")", ")", "else", ":", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "handler", ".", "setFormatter", "(", "LogFormatter", "(", "color", "=", "True", ")", ")", "module", ".", "logger", ".", "addHandler", "(", "handler", ")", "if", "'__handler_cls__'", "not", "in", "module", ".", "__dict__", ":", "BaseHandler", "=", "module", ".", "__dict__", ".", "get", "(", "'BaseHandler'", ",", "base_handler", ".", "BaseHandler", ")", "for", "each", "in", "list", "(", "six", ".", "itervalues", "(", "module", ".", "__dict__", ")", ")", ":", "if", "inspect", ".", "isclass", "(", "each", ")", "and", "each", "is", "not", "BaseHandler", "and", "issubclass", "(", "each", ",", "BaseHandler", ")", ":", "module", ".", "__dict__", "[", "'__handler_cls__'", "]", "=", "each", "_class", "=", "module", ".", "__dict__", ".", "get", "(", "'__handler_cls__'", ")", "assert", "_class", "is", "not", "None", ",", "\"need BaseHandler in project module\"", "instance", "=", "_class", "(", ")", "instance", ".", "__env__", "=", "env", "instance", ".", "project_name", "=", "project", "[", "'name'", "]", "instance", ".", "project", "=", "project", "return", "{", "'loader'", ":", "loader", ",", "'module'", ":", "module", ",", "'class'", ":", "_class", ",", "'instance'", ":", "instance", ",", "'exception'", ":", "None", ",", "'exception_log'", ":", "''", ",", "'info'", ":", "project", ",", "'load_time'", ":", "time", ".", "time", "(", ")", ",", "}" ]
Build project script as module
[ "Build", "project", "script", "as", "module" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L32-L87
train
binux/pyspider
pyspider/processor/project_module.py
ProjectManager._need_update
def _need_update(self, project_name, updatetime=None, md5sum=None): '''Check if project_name need update''' if project_name not in self.projects: return True elif md5sum and md5sum != self.projects[project_name]['info'].get('md5sum'): return True elif updatetime and updatetime > self.projects[project_name]['info'].get('updatetime', 0): return True elif time.time() - self.projects[project_name]['load_time'] > self.RELOAD_PROJECT_INTERVAL: return True return False
python
def _need_update(self, project_name, updatetime=None, md5sum=None): '''Check if project_name need update''' if project_name not in self.projects: return True elif md5sum and md5sum != self.projects[project_name]['info'].get('md5sum'): return True elif updatetime and updatetime > self.projects[project_name]['info'].get('updatetime', 0): return True elif time.time() - self.projects[project_name]['load_time'] > self.RELOAD_PROJECT_INTERVAL: return True return False
[ "def", "_need_update", "(", "self", ",", "project_name", ",", "updatetime", "=", "None", ",", "md5sum", "=", "None", ")", ":", "if", "project_name", "not", "in", "self", ".", "projects", ":", "return", "True", "elif", "md5sum", "and", "md5sum", "!=", "self", ".", "projects", "[", "project_name", "]", "[", "'info'", "]", ".", "get", "(", "'md5sum'", ")", ":", "return", "True", "elif", "updatetime", "and", "updatetime", ">", "self", ".", "projects", "[", "project_name", "]", "[", "'info'", "]", ".", "get", "(", "'updatetime'", ",", "0", ")", ":", "return", "True", "elif", "time", ".", "time", "(", ")", "-", "self", ".", "projects", "[", "project_name", "]", "[", "'load_time'", "]", ">", "self", ".", "RELOAD_PROJECT_INTERVAL", ":", "return", "True", "return", "False" ]
Check if project_name need update
[ "Check", "if", "project_name", "need", "update" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L96-L106
train
binux/pyspider
pyspider/processor/project_module.py
ProjectManager._check_projects
def _check_projects(self): '''Check projects by last update time''' for project in self.projectdb.check_update(self.last_check_projects, ['name', 'updatetime']): if project['name'] not in self.projects: continue if project['updatetime'] > self.projects[project['name']]['info'].get('updatetime', 0): self._update_project(project['name']) self.last_check_projects = time.time()
python
def _check_projects(self): '''Check projects by last update time''' for project in self.projectdb.check_update(self.last_check_projects, ['name', 'updatetime']): if project['name'] not in self.projects: continue if project['updatetime'] > self.projects[project['name']]['info'].get('updatetime', 0): self._update_project(project['name']) self.last_check_projects = time.time()
[ "def", "_check_projects", "(", "self", ")", ":", "for", "project", "in", "self", ".", "projectdb", ".", "check_update", "(", "self", ".", "last_check_projects", ",", "[", "'name'", ",", "'updatetime'", "]", ")", ":", "if", "project", "[", "'name'", "]", "not", "in", "self", ".", "projects", ":", "continue", "if", "project", "[", "'updatetime'", "]", ">", "self", ".", "projects", "[", "project", "[", "'name'", "]", "]", "[", "'info'", "]", ".", "get", "(", "'updatetime'", ",", "0", ")", ":", "self", ".", "_update_project", "(", "project", "[", "'name'", "]", ")", "self", ".", "last_check_projects", "=", "time", ".", "time", "(", ")" ]
Check projects by last update time
[ "Check", "projects", "by", "last", "update", "time" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L108-L116
train
binux/pyspider
pyspider/processor/project_module.py
ProjectManager._update_project
def _update_project(self, project_name): '''Update one project from database''' project = self.projectdb.get(project_name) if not project: return None return self._load_project(project)
python
def _update_project(self, project_name): '''Update one project from database''' project = self.projectdb.get(project_name) if not project: return None return self._load_project(project)
[ "def", "_update_project", "(", "self", ",", "project_name", ")", ":", "project", "=", "self", ".", "projectdb", ".", "get", "(", "project_name", ")", "if", "not", "project", ":", "return", "None", "return", "self", ".", "_load_project", "(", "project", ")" ]
Update one project from database
[ "Update", "one", "project", "from", "database" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L118-L123
train
binux/pyspider
pyspider/processor/project_module.py
ProjectManager._load_project
def _load_project(self, project): '''Load project into self.projects from project info dict''' try: project['md5sum'] = utils.md5string(project['script']) ret = self.build_module(project, self.env) self.projects[project['name']] = ret except Exception as e: logger.exception("load project %s error", project.get('name', None)) ret = { 'loader': None, 'module': None, 'class': None, 'instance': None, 'exception': e, 'exception_log': traceback.format_exc(), 'info': project, 'load_time': time.time(), } self.projects[project['name']] = ret return False logger.debug('project: %s updated.', project.get('name', None)) return True
python
def _load_project(self, project): '''Load project into self.projects from project info dict''' try: project['md5sum'] = utils.md5string(project['script']) ret = self.build_module(project, self.env) self.projects[project['name']] = ret except Exception as e: logger.exception("load project %s error", project.get('name', None)) ret = { 'loader': None, 'module': None, 'class': None, 'instance': None, 'exception': e, 'exception_log': traceback.format_exc(), 'info': project, 'load_time': time.time(), } self.projects[project['name']] = ret return False logger.debug('project: %s updated.', project.get('name', None)) return True
[ "def", "_load_project", "(", "self", ",", "project", ")", ":", "try", ":", "project", "[", "'md5sum'", "]", "=", "utils", ".", "md5string", "(", "project", "[", "'script'", "]", ")", "ret", "=", "self", ".", "build_module", "(", "project", ",", "self", ".", "env", ")", "self", ".", "projects", "[", "project", "[", "'name'", "]", "]", "=", "ret", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "\"load project %s error\"", ",", "project", ".", "get", "(", "'name'", ",", "None", ")", ")", "ret", "=", "{", "'loader'", ":", "None", ",", "'module'", ":", "None", ",", "'class'", ":", "None", ",", "'instance'", ":", "None", ",", "'exception'", ":", "e", ",", "'exception_log'", ":", "traceback", ".", "format_exc", "(", ")", ",", "'info'", ":", "project", ",", "'load_time'", ":", "time", ".", "time", "(", ")", ",", "}", "self", ".", "projects", "[", "project", "[", "'name'", "]", "]", "=", "ret", "return", "False", "logger", ".", "debug", "(", "'project: %s updated.'", ",", "project", ".", "get", "(", "'name'", ",", "None", ")", ")", "return", "True" ]
Load project into self.projects from project info dict
[ "Load", "project", "into", "self", ".", "projects", "from", "project", "info", "dict" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L125-L146
train
binux/pyspider
pyspider/processor/project_module.py
ProjectManager.get
def get(self, project_name, updatetime=None, md5sum=None): '''get project data object, return None if not exists''' if time.time() - self.last_check_projects > self.CHECK_PROJECTS_INTERVAL: self._check_projects() if self._need_update(project_name, updatetime, md5sum): self._update_project(project_name) return self.projects.get(project_name, None)
python
def get(self, project_name, updatetime=None, md5sum=None): '''get project data object, return None if not exists''' if time.time() - self.last_check_projects > self.CHECK_PROJECTS_INTERVAL: self._check_projects() if self._need_update(project_name, updatetime, md5sum): self._update_project(project_name) return self.projects.get(project_name, None)
[ "def", "get", "(", "self", ",", "project_name", ",", "updatetime", "=", "None", ",", "md5sum", "=", "None", ")", ":", "if", "time", ".", "time", "(", ")", "-", "self", ".", "last_check_projects", ">", "self", ".", "CHECK_PROJECTS_INTERVAL", ":", "self", ".", "_check_projects", "(", ")", "if", "self", ".", "_need_update", "(", "project_name", ",", "updatetime", ",", "md5sum", ")", ":", "self", ".", "_update_project", "(", "project_name", ")", "return", "self", ".", "projects", ".", "get", "(", "project_name", ",", "None", ")" ]
get project data object, return None if not exists
[ "get", "project", "data", "object", "return", "None", "if", "not", "exists" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L148-L154
train
binux/pyspider
pyspider/fetcher/cookie_utils.py
MockResponse.get_all
def get_all(self, name, default=None): """make cookie python 3 version use this instead of getheaders""" if default is None: default = [] return self._headers.get_list(name) or default
python
def get_all(self, name, default=None): """make cookie python 3 version use this instead of getheaders""" if default is None: default = [] return self._headers.get_list(name) or default
[ "def", "get_all", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "if", "default", "is", "None", ":", "default", "=", "[", "]", "return", "self", ".", "_headers", ".", "get_list", "(", "name", ")", "or", "default" ]
make cookie python 3 version use this instead of getheaders
[ "make", "cookie", "python", "3", "version", "use", "this", "instead", "of", "getheaders" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/cookie_utils.py#L23-L27
train
binux/pyspider
pyspider/database/redis/taskdb.py
TaskDB.status_count
def status_count(self, project): ''' return a dict ''' pipe = self.redis.pipeline(transaction=False) for status in range(1, 5): pipe.scard(self._gen_status_key(project, status)) ret = pipe.execute() result = {} for status, count in enumerate(ret): if count > 0: result[status + 1] = count return result
python
def status_count(self, project): ''' return a dict ''' pipe = self.redis.pipeline(transaction=False) for status in range(1, 5): pipe.scard(self._gen_status_key(project, status)) ret = pipe.execute() result = {} for status, count in enumerate(ret): if count > 0: result[status + 1] = count return result
[ "def", "status_count", "(", "self", ",", "project", ")", ":", "pipe", "=", "self", ".", "redis", ".", "pipeline", "(", "transaction", "=", "False", ")", "for", "status", "in", "range", "(", "1", ",", "5", ")", ":", "pipe", ".", "scard", "(", "self", ".", "_gen_status_key", "(", "project", ",", "status", ")", ")", "ret", "=", "pipe", ".", "execute", "(", ")", "result", "=", "{", "}", "for", "status", ",", "count", "in", "enumerate", "(", "ret", ")", ":", "if", "count", ">", "0", ":", "result", "[", "status", "+", "1", "]", "=", "count", "return", "result" ]
return a dict
[ "return", "a", "dict" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/database/redis/taskdb.py#L118-L131
train
binux/pyspider
pyspider/libs/multiprocessing_queue.py
SharedCounter.increment
def increment(self, n=1): """ Increment the counter by n (default = 1) """ with self.count.get_lock(): self.count.value += n
python
def increment(self, n=1): """ Increment the counter by n (default = 1) """ with self.count.get_lock(): self.count.value += n
[ "def", "increment", "(", "self", ",", "n", "=", "1", ")", ":", "with", "self", ".", "count", ".", "get_lock", "(", ")", ":", "self", ".", "count", ".", "value", "+=", "n" ]
Increment the counter by n (default = 1)
[ "Increment", "the", "counter", "by", "n", "(", "default", "=", "1", ")" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/multiprocessing_queue.py#L25-L28
train
binux/pyspider
pyspider/database/elasticsearch/taskdb.py
TaskDB.refresh
def refresh(self): """ Explicitly refresh one or more index, making all operations performed since the last refresh available for search. """ self._changed = False self.es.indices.refresh(index=self.index)
python
def refresh(self): """ Explicitly refresh one or more index, making all operations performed since the last refresh available for search. """ self._changed = False self.es.indices.refresh(index=self.index)
[ "def", "refresh", "(", "self", ")", ":", "self", ".", "_changed", "=", "False", "self", ".", "es", ".", "indices", ".", "refresh", "(", "index", "=", "self", ".", "index", ")" ]
Explicitly refresh one or more index, making all operations performed since the last refresh available for search.
[ "Explicitly", "refresh", "one", "or", "more", "index", "making", "all", "operations", "performed", "since", "the", "last", "refresh", "available", "for", "search", "." ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/database/elasticsearch/taskdb.py#L119-L125
train
binux/pyspider
pyspider/fetcher/tornado_fetcher.py
Fetcher.send_result
def send_result(self, type, task, result): '''Send fetch result to processor''' if self.outqueue: try: self.outqueue.put((task, result)) except Exception as e: logger.exception(e)
python
def send_result(self, type, task, result): '''Send fetch result to processor''' if self.outqueue: try: self.outqueue.put((task, result)) except Exception as e: logger.exception(e)
[ "def", "send_result", "(", "self", ",", "type", ",", "task", ",", "result", ")", ":", "if", "self", ".", "outqueue", ":", "try", ":", "self", ".", "outqueue", ".", "put", "(", "(", "task", ",", "result", ")", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "e", ")" ]
Send fetch result to processor
[ "Send", "fetch", "result", "to", "processor" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L108-L114
train
binux/pyspider
pyspider/fetcher/tornado_fetcher.py
Fetcher.async_fetch
def async_fetch(self, task, callback=None): '''Do one fetch''' url = task.get('url', 'data:,') if callback is None: callback = self.send_result type = 'None' start_time = time.time() try: if url.startswith('data:'): type = 'data' result = yield gen.maybe_future(self.data_fetch(url, task)) elif task.get('fetch', {}).get('fetch_type') in ('js', 'phantomjs'): type = 'phantomjs' result = yield self.phantomjs_fetch(url, task) elif task.get('fetch', {}).get('fetch_type') in ('splash', ): type = 'splash' result = yield self.splash_fetch(url, task) elif task.get('fetch', {}).get('fetch_type') in ('puppeteer', ): type = 'puppeteer' result = yield self.puppeteer_fetch(url, task) else: type = 'http' result = yield self.http_fetch(url, task) except Exception as e: logger.exception(e) result = self.handle_error(type, url, task, start_time, e) callback(type, task, result) self.on_result(type, task, result) raise gen.Return(result)
python
def async_fetch(self, task, callback=None): '''Do one fetch''' url = task.get('url', 'data:,') if callback is None: callback = self.send_result type = 'None' start_time = time.time() try: if url.startswith('data:'): type = 'data' result = yield gen.maybe_future(self.data_fetch(url, task)) elif task.get('fetch', {}).get('fetch_type') in ('js', 'phantomjs'): type = 'phantomjs' result = yield self.phantomjs_fetch(url, task) elif task.get('fetch', {}).get('fetch_type') in ('splash', ): type = 'splash' result = yield self.splash_fetch(url, task) elif task.get('fetch', {}).get('fetch_type') in ('puppeteer', ): type = 'puppeteer' result = yield self.puppeteer_fetch(url, task) else: type = 'http' result = yield self.http_fetch(url, task) except Exception as e: logger.exception(e) result = self.handle_error(type, url, task, start_time, e) callback(type, task, result) self.on_result(type, task, result) raise gen.Return(result)
[ "def", "async_fetch", "(", "self", ",", "task", ",", "callback", "=", "None", ")", ":", "url", "=", "task", ".", "get", "(", "'url'", ",", "'data:,'", ")", "if", "callback", "is", "None", ":", "callback", "=", "self", ".", "send_result", "type", "=", "'None'", "start_time", "=", "time", ".", "time", "(", ")", "try", ":", "if", "url", ".", "startswith", "(", "'data:'", ")", ":", "type", "=", "'data'", "result", "=", "yield", "gen", ".", "maybe_future", "(", "self", ".", "data_fetch", "(", "url", ",", "task", ")", ")", "elif", "task", ".", "get", "(", "'fetch'", ",", "{", "}", ")", ".", "get", "(", "'fetch_type'", ")", "in", "(", "'js'", ",", "'phantomjs'", ")", ":", "type", "=", "'phantomjs'", "result", "=", "yield", "self", ".", "phantomjs_fetch", "(", "url", ",", "task", ")", "elif", "task", ".", "get", "(", "'fetch'", ",", "{", "}", ")", ".", "get", "(", "'fetch_type'", ")", "in", "(", "'splash'", ",", ")", ":", "type", "=", "'splash'", "result", "=", "yield", "self", ".", "splash_fetch", "(", "url", ",", "task", ")", "elif", "task", ".", "get", "(", "'fetch'", ",", "{", "}", ")", ".", "get", "(", "'fetch_type'", ")", "in", "(", "'puppeteer'", ",", ")", ":", "type", "=", "'puppeteer'", "result", "=", "yield", "self", ".", "puppeteer_fetch", "(", "url", ",", "task", ")", "else", ":", "type", "=", "'http'", "result", "=", "yield", "self", ".", "http_fetch", "(", "url", ",", "task", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "e", ")", "result", "=", "self", ".", "handle_error", "(", "type", ",", "url", ",", "task", ",", "start_time", ",", "e", ")", "callback", "(", "type", ",", "task", ",", "result", ")", "self", ".", "on_result", "(", "type", ",", "task", ",", "result", ")", "raise", "gen", ".", "Return", "(", "result", ")" ]
Do one fetch
[ "Do", "one", "fetch" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L123-L153
train
binux/pyspider
pyspider/fetcher/tornado_fetcher.py
Fetcher.sync_fetch
def sync_fetch(self, task): '''Synchronization fetch, usually used in xmlrpc thread''' if not self._running: return self.ioloop.run_sync(functools.partial(self.async_fetch, task, lambda t, _, r: True)) wait_result = threading.Condition() _result = {} def callback(type, task, result): wait_result.acquire() _result['type'] = type _result['task'] = task _result['result'] = result wait_result.notify() wait_result.release() wait_result.acquire() self.ioloop.add_callback(self.fetch, task, callback) while 'result' not in _result: wait_result.wait() wait_result.release() return _result['result']
python
def sync_fetch(self, task): '''Synchronization fetch, usually used in xmlrpc thread''' if not self._running: return self.ioloop.run_sync(functools.partial(self.async_fetch, task, lambda t, _, r: True)) wait_result = threading.Condition() _result = {} def callback(type, task, result): wait_result.acquire() _result['type'] = type _result['task'] = task _result['result'] = result wait_result.notify() wait_result.release() wait_result.acquire() self.ioloop.add_callback(self.fetch, task, callback) while 'result' not in _result: wait_result.wait() wait_result.release() return _result['result']
[ "def", "sync_fetch", "(", "self", ",", "task", ")", ":", "if", "not", "self", ".", "_running", ":", "return", "self", ".", "ioloop", ".", "run_sync", "(", "functools", ".", "partial", "(", "self", ".", "async_fetch", ",", "task", ",", "lambda", "t", ",", "_", ",", "r", ":", "True", ")", ")", "wait_result", "=", "threading", ".", "Condition", "(", ")", "_result", "=", "{", "}", "def", "callback", "(", "type", ",", "task", ",", "result", ")", ":", "wait_result", ".", "acquire", "(", ")", "_result", "[", "'type'", "]", "=", "type", "_result", "[", "'task'", "]", "=", "task", "_result", "[", "'result'", "]", "=", "result", "wait_result", ".", "notify", "(", ")", "wait_result", ".", "release", "(", ")", "wait_result", ".", "acquire", "(", ")", "self", ".", "ioloop", ".", "add_callback", "(", "self", ".", "fetch", ",", "task", ",", "callback", ")", "while", "'result'", "not", "in", "_result", ":", "wait_result", ".", "wait", "(", ")", "wait_result", ".", "release", "(", ")", "return", "_result", "[", "'result'", "]" ]
Synchronization fetch, usually used in xmlrpc thread
[ "Synchronization", "fetch", "usually", "used", "in", "xmlrpc", "thread" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L155-L176
train
binux/pyspider
pyspider/fetcher/tornado_fetcher.py
Fetcher.data_fetch
def data_fetch(self, url, task): '''A fake fetcher for dataurl''' self.on_fetch('data', task) result = {} result['orig_url'] = url result['content'] = dataurl.decode(url) result['headers'] = {} result['status_code'] = 200 result['url'] = url result['cookies'] = {} result['time'] = 0 result['save'] = task.get('fetch', {}).get('save') if len(result['content']) < 70: logger.info("[200] %s:%s %s 0s", task.get('project'), task.get('taskid'), url) else: logger.info( "[200] %s:%s data:,%s...[content:%d] 0s", task.get('project'), task.get('taskid'), result['content'][:70], len(result['content']) ) return result
python
def data_fetch(self, url, task): '''A fake fetcher for dataurl''' self.on_fetch('data', task) result = {} result['orig_url'] = url result['content'] = dataurl.decode(url) result['headers'] = {} result['status_code'] = 200 result['url'] = url result['cookies'] = {} result['time'] = 0 result['save'] = task.get('fetch', {}).get('save') if len(result['content']) < 70: logger.info("[200] %s:%s %s 0s", task.get('project'), task.get('taskid'), url) else: logger.info( "[200] %s:%s data:,%s...[content:%d] 0s", task.get('project'), task.get('taskid'), result['content'][:70], len(result['content']) ) return result
[ "def", "data_fetch", "(", "self", ",", "url", ",", "task", ")", ":", "self", ".", "on_fetch", "(", "'data'", ",", "task", ")", "result", "=", "{", "}", "result", "[", "'orig_url'", "]", "=", "url", "result", "[", "'content'", "]", "=", "dataurl", ".", "decode", "(", "url", ")", "result", "[", "'headers'", "]", "=", "{", "}", "result", "[", "'status_code'", "]", "=", "200", "result", "[", "'url'", "]", "=", "url", "result", "[", "'cookies'", "]", "=", "{", "}", "result", "[", "'time'", "]", "=", "0", "result", "[", "'save'", "]", "=", "task", ".", "get", "(", "'fetch'", ",", "{", "}", ")", ".", "get", "(", "'save'", ")", "if", "len", "(", "result", "[", "'content'", "]", ")", "<", "70", ":", "logger", ".", "info", "(", "\"[200] %s:%s %s 0s\"", ",", "task", ".", "get", "(", "'project'", ")", ",", "task", ".", "get", "(", "'taskid'", ")", ",", "url", ")", "else", ":", "logger", ".", "info", "(", "\"[200] %s:%s data:,%s...[content:%d] 0s\"", ",", "task", ".", "get", "(", "'project'", ")", ",", "task", ".", "get", "(", "'taskid'", ")", ",", "result", "[", "'content'", "]", "[", ":", "70", "]", ",", "len", "(", "result", "[", "'content'", "]", ")", ")", "return", "result" ]
A fake fetcher for dataurl
[ "A", "fake", "fetcher", "for", "dataurl" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L178-L200
train
binux/pyspider
pyspider/fetcher/tornado_fetcher.py
Fetcher.http_fetch
def http_fetch(self, url, task): '''HTTP fetcher''' start_time = time.time() self.on_fetch('http', task) handle_error = lambda x: self.handle_error('http', url, task, start_time, x) # setup request parameters fetch = self.pack_tornado_request_parameters(url, task) task_fetch = task.get('fetch', {}) session = cookies.RequestsCookieJar() # fix for tornado request obj if 'Cookie' in fetch['headers']: c = http_cookies.SimpleCookie() try: c.load(fetch['headers']['Cookie']) except AttributeError: c.load(utils.utf8(fetch['headers']['Cookie'])) for key in c: session.set(key, c[key]) del fetch['headers']['Cookie'] if 'cookies' in fetch: session.update(fetch['cookies']) del fetch['cookies'] max_redirects = task_fetch.get('max_redirects', 5) # we will handle redirects by hand to capture cookies fetch['follow_redirects'] = False # making requests while True: # robots.txt if task_fetch.get('robots_txt', False): can_fetch = yield self.can_fetch(fetch['headers']['User-Agent'], fetch['url']) if not can_fetch: error = tornado.httpclient.HTTPError(403, 'Disallowed by robots.txt') raise gen.Return(handle_error(error)) try: request = tornado.httpclient.HTTPRequest(**fetch) # if cookie already in header, get_cookie_header wouldn't work old_cookie_header = request.headers.get('Cookie') if old_cookie_header: del request.headers['Cookie'] cookie_header = cookies.get_cookie_header(session, request) if cookie_header: request.headers['Cookie'] = cookie_header elif old_cookie_header: request.headers['Cookie'] = old_cookie_header except Exception as e: logger.exception(fetch) raise gen.Return(handle_error(e)) try: response = yield gen.maybe_future(self.http_client.fetch(request)) except tornado.httpclient.HTTPError as e: if e.response: response = e.response else: raise gen.Return(handle_error(e)) extract_cookies_to_jar(session, response.request, response.headers) if (response.code in (301, 302, 303, 307) and response.headers.get('Location') and task_fetch.get('allow_redirects', True)): if max_redirects <= 0: error = tornado.httpclient.HTTPError( 599, 'Maximum (%d) redirects followed' % task_fetch.get('max_redirects', 5), response) raise gen.Return(handle_error(error)) if response.code in (302, 303): fetch['method'] = 'GET' if 'body' in fetch: del fetch['body'] fetch['url'] = quote_chinese(urljoin(fetch['url'], response.headers['Location'])) fetch['request_timeout'] -= time.time() - start_time if fetch['request_timeout'] < 0: fetch['request_timeout'] = 0.1 max_redirects -= 1 continue result = {} result['orig_url'] = url result['content'] = response.body or '' result['headers'] = dict(response.headers) result['status_code'] = response.code result['url'] = response.effective_url or url result['time'] = time.time() - start_time result['cookies'] = session.get_dict() result['save'] = task_fetch.get('save') if response.error: result['error'] = utils.text(response.error) if 200 <= response.code < 300: logger.info("[%d] %s:%s %s %.2fs", response.code, task.get('project'), task.get('taskid'), url, result['time']) else: logger.warning("[%d] %s:%s %s %.2fs", response.code, task.get('project'), task.get('taskid'), url, result['time']) raise gen.Return(result)
python
def http_fetch(self, url, task): '''HTTP fetcher''' start_time = time.time() self.on_fetch('http', task) handle_error = lambda x: self.handle_error('http', url, task, start_time, x) # setup request parameters fetch = self.pack_tornado_request_parameters(url, task) task_fetch = task.get('fetch', {}) session = cookies.RequestsCookieJar() # fix for tornado request obj if 'Cookie' in fetch['headers']: c = http_cookies.SimpleCookie() try: c.load(fetch['headers']['Cookie']) except AttributeError: c.load(utils.utf8(fetch['headers']['Cookie'])) for key in c: session.set(key, c[key]) del fetch['headers']['Cookie'] if 'cookies' in fetch: session.update(fetch['cookies']) del fetch['cookies'] max_redirects = task_fetch.get('max_redirects', 5) # we will handle redirects by hand to capture cookies fetch['follow_redirects'] = False # making requests while True: # robots.txt if task_fetch.get('robots_txt', False): can_fetch = yield self.can_fetch(fetch['headers']['User-Agent'], fetch['url']) if not can_fetch: error = tornado.httpclient.HTTPError(403, 'Disallowed by robots.txt') raise gen.Return(handle_error(error)) try: request = tornado.httpclient.HTTPRequest(**fetch) # if cookie already in header, get_cookie_header wouldn't work old_cookie_header = request.headers.get('Cookie') if old_cookie_header: del request.headers['Cookie'] cookie_header = cookies.get_cookie_header(session, request) if cookie_header: request.headers['Cookie'] = cookie_header elif old_cookie_header: request.headers['Cookie'] = old_cookie_header except Exception as e: logger.exception(fetch) raise gen.Return(handle_error(e)) try: response = yield gen.maybe_future(self.http_client.fetch(request)) except tornado.httpclient.HTTPError as e: if e.response: response = e.response else: raise gen.Return(handle_error(e)) extract_cookies_to_jar(session, response.request, response.headers) if (response.code in (301, 302, 303, 307) and response.headers.get('Location') and task_fetch.get('allow_redirects', True)): if max_redirects <= 0: error = tornado.httpclient.HTTPError( 599, 'Maximum (%d) redirects followed' % task_fetch.get('max_redirects', 5), response) raise gen.Return(handle_error(error)) if response.code in (302, 303): fetch['method'] = 'GET' if 'body' in fetch: del fetch['body'] fetch['url'] = quote_chinese(urljoin(fetch['url'], response.headers['Location'])) fetch['request_timeout'] -= time.time() - start_time if fetch['request_timeout'] < 0: fetch['request_timeout'] = 0.1 max_redirects -= 1 continue result = {} result['orig_url'] = url result['content'] = response.body or '' result['headers'] = dict(response.headers) result['status_code'] = response.code result['url'] = response.effective_url or url result['time'] = time.time() - start_time result['cookies'] = session.get_dict() result['save'] = task_fetch.get('save') if response.error: result['error'] = utils.text(response.error) if 200 <= response.code < 300: logger.info("[%d] %s:%s %s %.2fs", response.code, task.get('project'), task.get('taskid'), url, result['time']) else: logger.warning("[%d] %s:%s %s %.2fs", response.code, task.get('project'), task.get('taskid'), url, result['time']) raise gen.Return(result)
[ "def", "http_fetch", "(", "self", ",", "url", ",", "task", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "self", ".", "on_fetch", "(", "'http'", ",", "task", ")", "handle_error", "=", "lambda", "x", ":", "self", ".", "handle_error", "(", "'http'", ",", "url", ",", "task", ",", "start_time", ",", "x", ")", "# setup request parameters", "fetch", "=", "self", ".", "pack_tornado_request_parameters", "(", "url", ",", "task", ")", "task_fetch", "=", "task", ".", "get", "(", "'fetch'", ",", "{", "}", ")", "session", "=", "cookies", ".", "RequestsCookieJar", "(", ")", "# fix for tornado request obj", "if", "'Cookie'", "in", "fetch", "[", "'headers'", "]", ":", "c", "=", "http_cookies", ".", "SimpleCookie", "(", ")", "try", ":", "c", ".", "load", "(", "fetch", "[", "'headers'", "]", "[", "'Cookie'", "]", ")", "except", "AttributeError", ":", "c", ".", "load", "(", "utils", ".", "utf8", "(", "fetch", "[", "'headers'", "]", "[", "'Cookie'", "]", ")", ")", "for", "key", "in", "c", ":", "session", ".", "set", "(", "key", ",", "c", "[", "key", "]", ")", "del", "fetch", "[", "'headers'", "]", "[", "'Cookie'", "]", "if", "'cookies'", "in", "fetch", ":", "session", ".", "update", "(", "fetch", "[", "'cookies'", "]", ")", "del", "fetch", "[", "'cookies'", "]", "max_redirects", "=", "task_fetch", ".", "get", "(", "'max_redirects'", ",", "5", ")", "# we will handle redirects by hand to capture cookies", "fetch", "[", "'follow_redirects'", "]", "=", "False", "# making requests", "while", "True", ":", "# robots.txt", "if", "task_fetch", ".", "get", "(", "'robots_txt'", ",", "False", ")", ":", "can_fetch", "=", "yield", "self", ".", "can_fetch", "(", "fetch", "[", "'headers'", "]", "[", "'User-Agent'", "]", ",", "fetch", "[", "'url'", "]", ")", "if", "not", "can_fetch", ":", "error", "=", "tornado", ".", "httpclient", ".", "HTTPError", "(", "403", ",", "'Disallowed by robots.txt'", ")", "raise", "gen", ".", "Return", "(", "handle_error", "(", "error", ")", ")", "try", ":", "request", "=", "tornado", ".", "httpclient", ".", "HTTPRequest", "(", "*", "*", "fetch", ")", "# if cookie already in header, get_cookie_header wouldn't work", "old_cookie_header", "=", "request", ".", "headers", ".", "get", "(", "'Cookie'", ")", "if", "old_cookie_header", ":", "del", "request", ".", "headers", "[", "'Cookie'", "]", "cookie_header", "=", "cookies", ".", "get_cookie_header", "(", "session", ",", "request", ")", "if", "cookie_header", ":", "request", ".", "headers", "[", "'Cookie'", "]", "=", "cookie_header", "elif", "old_cookie_header", ":", "request", ".", "headers", "[", "'Cookie'", "]", "=", "old_cookie_header", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "fetch", ")", "raise", "gen", ".", "Return", "(", "handle_error", "(", "e", ")", ")", "try", ":", "response", "=", "yield", "gen", ".", "maybe_future", "(", "self", ".", "http_client", ".", "fetch", "(", "request", ")", ")", "except", "tornado", ".", "httpclient", ".", "HTTPError", "as", "e", ":", "if", "e", ".", "response", ":", "response", "=", "e", ".", "response", "else", ":", "raise", "gen", ".", "Return", "(", "handle_error", "(", "e", ")", ")", "extract_cookies_to_jar", "(", "session", ",", "response", ".", "request", ",", "response", ".", "headers", ")", "if", "(", "response", ".", "code", "in", "(", "301", ",", "302", ",", "303", ",", "307", ")", "and", "response", ".", "headers", ".", "get", "(", "'Location'", ")", "and", "task_fetch", ".", "get", "(", "'allow_redirects'", ",", "True", ")", ")", ":", "if", "max_redirects", "<=", "0", ":", "error", "=", "tornado", ".", "httpclient", ".", "HTTPError", "(", "599", ",", "'Maximum (%d) redirects followed'", "%", "task_fetch", ".", "get", "(", "'max_redirects'", ",", "5", ")", ",", "response", ")", "raise", "gen", ".", "Return", "(", "handle_error", "(", "error", ")", ")", "if", "response", ".", "code", "in", "(", "302", ",", "303", ")", ":", "fetch", "[", "'method'", "]", "=", "'GET'", "if", "'body'", "in", "fetch", ":", "del", "fetch", "[", "'body'", "]", "fetch", "[", "'url'", "]", "=", "quote_chinese", "(", "urljoin", "(", "fetch", "[", "'url'", "]", ",", "response", ".", "headers", "[", "'Location'", "]", ")", ")", "fetch", "[", "'request_timeout'", "]", "-=", "time", ".", "time", "(", ")", "-", "start_time", "if", "fetch", "[", "'request_timeout'", "]", "<", "0", ":", "fetch", "[", "'request_timeout'", "]", "=", "0.1", "max_redirects", "-=", "1", "continue", "result", "=", "{", "}", "result", "[", "'orig_url'", "]", "=", "url", "result", "[", "'content'", "]", "=", "response", ".", "body", "or", "''", "result", "[", "'headers'", "]", "=", "dict", "(", "response", ".", "headers", ")", "result", "[", "'status_code'", "]", "=", "response", ".", "code", "result", "[", "'url'", "]", "=", "response", ".", "effective_url", "or", "url", "result", "[", "'time'", "]", "=", "time", ".", "time", "(", ")", "-", "start_time", "result", "[", "'cookies'", "]", "=", "session", ".", "get_dict", "(", ")", "result", "[", "'save'", "]", "=", "task_fetch", ".", "get", "(", "'save'", ")", "if", "response", ".", "error", ":", "result", "[", "'error'", "]", "=", "utils", ".", "text", "(", "response", ".", "error", ")", "if", "200", "<=", "response", ".", "code", "<", "300", ":", "logger", ".", "info", "(", "\"[%d] %s:%s %s %.2fs\"", ",", "response", ".", "code", ",", "task", ".", "get", "(", "'project'", ")", ",", "task", ".", "get", "(", "'taskid'", ")", ",", "url", ",", "result", "[", "'time'", "]", ")", "else", ":", "logger", ".", "warning", "(", "\"[%d] %s:%s %s %.2fs\"", ",", "response", ".", "code", ",", "task", ".", "get", "(", "'project'", ")", ",", "task", ".", "get", "(", "'taskid'", ")", ",", "url", ",", "result", "[", "'time'", "]", ")", "raise", "gen", ".", "Return", "(", "result", ")" ]
HTTP fetcher
[ "HTTP", "fetcher" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L327-L428
train
binux/pyspider
pyspider/fetcher/tornado_fetcher.py
Fetcher.phantomjs_fetch
def phantomjs_fetch(self, url, task): '''Fetch with phantomjs proxy''' start_time = time.time() self.on_fetch('phantomjs', task) handle_error = lambda x: self.handle_error('phantomjs', url, task, start_time, x) # check phantomjs proxy is enabled if not self.phantomjs_proxy: result = { "orig_url": url, "content": "phantomjs is not enabled.", "headers": {}, "status_code": 501, "url": url, "time": time.time() - start_time, "cookies": {}, "save": task.get('fetch', {}).get('save') } logger.warning("[501] %s:%s %s 0s", task.get('project'), task.get('taskid'), url) raise gen.Return(result) # setup request parameters fetch = self.pack_tornado_request_parameters(url, task) task_fetch = task.get('fetch', {}) for each in task_fetch: if each not in fetch: fetch[each] = task_fetch[each] # robots.txt if task_fetch.get('robots_txt', False): user_agent = fetch['headers']['User-Agent'] can_fetch = yield self.can_fetch(user_agent, url) if not can_fetch: error = tornado.httpclient.HTTPError(403, 'Disallowed by robots.txt') raise gen.Return(handle_error(error)) request_conf = { 'follow_redirects': False } request_conf['connect_timeout'] = fetch.get('connect_timeout', 20) request_conf['request_timeout'] = fetch.get('request_timeout', 120) + 1 session = cookies.RequestsCookieJar() if 'Cookie' in fetch['headers']: c = http_cookies.SimpleCookie() try: c.load(fetch['headers']['Cookie']) except AttributeError: c.load(utils.utf8(fetch['headers']['Cookie'])) for key in c: session.set(key, c[key]) del fetch['headers']['Cookie'] if 'cookies' in fetch: session.update(fetch['cookies']) del fetch['cookies'] request = tornado.httpclient.HTTPRequest(url=fetch['url']) cookie_header = cookies.get_cookie_header(session, request) if cookie_header: fetch['headers']['Cookie'] = cookie_header # making requests fetch['headers'] = dict(fetch['headers']) try: request = tornado.httpclient.HTTPRequest( url=self.phantomjs_proxy, method="POST", body=json.dumps(fetch), **request_conf) except Exception as e: raise gen.Return(handle_error(e)) try: response = yield gen.maybe_future(self.http_client.fetch(request)) except tornado.httpclient.HTTPError as e: if e.response: response = e.response else: raise gen.Return(handle_error(e)) if not response.body: raise gen.Return(handle_error(Exception('no response from phantomjs: %r' % response))) result = {} try: result = json.loads(utils.text(response.body)) assert 'status_code' in result, result except Exception as e: if response.error: result['error'] = utils.text(response.error) raise gen.Return(handle_error(e)) if result.get('status_code', 200): logger.info("[%d] %s:%s %s %.2fs", result['status_code'], task.get('project'), task.get('taskid'), url, result['time']) else: logger.error("[%d] %s:%s %s, %r %.2fs", result['status_code'], task.get('project'), task.get('taskid'), url, result['content'], result['time']) raise gen.Return(result)
python
def phantomjs_fetch(self, url, task): '''Fetch with phantomjs proxy''' start_time = time.time() self.on_fetch('phantomjs', task) handle_error = lambda x: self.handle_error('phantomjs', url, task, start_time, x) # check phantomjs proxy is enabled if not self.phantomjs_proxy: result = { "orig_url": url, "content": "phantomjs is not enabled.", "headers": {}, "status_code": 501, "url": url, "time": time.time() - start_time, "cookies": {}, "save": task.get('fetch', {}).get('save') } logger.warning("[501] %s:%s %s 0s", task.get('project'), task.get('taskid'), url) raise gen.Return(result) # setup request parameters fetch = self.pack_tornado_request_parameters(url, task) task_fetch = task.get('fetch', {}) for each in task_fetch: if each not in fetch: fetch[each] = task_fetch[each] # robots.txt if task_fetch.get('robots_txt', False): user_agent = fetch['headers']['User-Agent'] can_fetch = yield self.can_fetch(user_agent, url) if not can_fetch: error = tornado.httpclient.HTTPError(403, 'Disallowed by robots.txt') raise gen.Return(handle_error(error)) request_conf = { 'follow_redirects': False } request_conf['connect_timeout'] = fetch.get('connect_timeout', 20) request_conf['request_timeout'] = fetch.get('request_timeout', 120) + 1 session = cookies.RequestsCookieJar() if 'Cookie' in fetch['headers']: c = http_cookies.SimpleCookie() try: c.load(fetch['headers']['Cookie']) except AttributeError: c.load(utils.utf8(fetch['headers']['Cookie'])) for key in c: session.set(key, c[key]) del fetch['headers']['Cookie'] if 'cookies' in fetch: session.update(fetch['cookies']) del fetch['cookies'] request = tornado.httpclient.HTTPRequest(url=fetch['url']) cookie_header = cookies.get_cookie_header(session, request) if cookie_header: fetch['headers']['Cookie'] = cookie_header # making requests fetch['headers'] = dict(fetch['headers']) try: request = tornado.httpclient.HTTPRequest( url=self.phantomjs_proxy, method="POST", body=json.dumps(fetch), **request_conf) except Exception as e: raise gen.Return(handle_error(e)) try: response = yield gen.maybe_future(self.http_client.fetch(request)) except tornado.httpclient.HTTPError as e: if e.response: response = e.response else: raise gen.Return(handle_error(e)) if not response.body: raise gen.Return(handle_error(Exception('no response from phantomjs: %r' % response))) result = {} try: result = json.loads(utils.text(response.body)) assert 'status_code' in result, result except Exception as e: if response.error: result['error'] = utils.text(response.error) raise gen.Return(handle_error(e)) if result.get('status_code', 200): logger.info("[%d] %s:%s %s %.2fs", result['status_code'], task.get('project'), task.get('taskid'), url, result['time']) else: logger.error("[%d] %s:%s %s, %r %.2fs", result['status_code'], task.get('project'), task.get('taskid'), url, result['content'], result['time']) raise gen.Return(result)
[ "def", "phantomjs_fetch", "(", "self", ",", "url", ",", "task", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "self", ".", "on_fetch", "(", "'phantomjs'", ",", "task", ")", "handle_error", "=", "lambda", "x", ":", "self", ".", "handle_error", "(", "'phantomjs'", ",", "url", ",", "task", ",", "start_time", ",", "x", ")", "# check phantomjs proxy is enabled", "if", "not", "self", ".", "phantomjs_proxy", ":", "result", "=", "{", "\"orig_url\"", ":", "url", ",", "\"content\"", ":", "\"phantomjs is not enabled.\"", ",", "\"headers\"", ":", "{", "}", ",", "\"status_code\"", ":", "501", ",", "\"url\"", ":", "url", ",", "\"time\"", ":", "time", ".", "time", "(", ")", "-", "start_time", ",", "\"cookies\"", ":", "{", "}", ",", "\"save\"", ":", "task", ".", "get", "(", "'fetch'", ",", "{", "}", ")", ".", "get", "(", "'save'", ")", "}", "logger", ".", "warning", "(", "\"[501] %s:%s %s 0s\"", ",", "task", ".", "get", "(", "'project'", ")", ",", "task", ".", "get", "(", "'taskid'", ")", ",", "url", ")", "raise", "gen", ".", "Return", "(", "result", ")", "# setup request parameters", "fetch", "=", "self", ".", "pack_tornado_request_parameters", "(", "url", ",", "task", ")", "task_fetch", "=", "task", ".", "get", "(", "'fetch'", ",", "{", "}", ")", "for", "each", "in", "task_fetch", ":", "if", "each", "not", "in", "fetch", ":", "fetch", "[", "each", "]", "=", "task_fetch", "[", "each", "]", "# robots.txt", "if", "task_fetch", ".", "get", "(", "'robots_txt'", ",", "False", ")", ":", "user_agent", "=", "fetch", "[", "'headers'", "]", "[", "'User-Agent'", "]", "can_fetch", "=", "yield", "self", ".", "can_fetch", "(", "user_agent", ",", "url", ")", "if", "not", "can_fetch", ":", "error", "=", "tornado", ".", "httpclient", ".", "HTTPError", "(", "403", ",", "'Disallowed by robots.txt'", ")", "raise", "gen", ".", "Return", "(", "handle_error", "(", "error", ")", ")", "request_conf", "=", "{", "'follow_redirects'", ":", "False", "}", "request_conf", "[", "'connect_timeout'", "]", "=", "fetch", ".", "get", "(", "'connect_timeout'", ",", "20", ")", "request_conf", "[", "'request_timeout'", "]", "=", "fetch", ".", "get", "(", "'request_timeout'", ",", "120", ")", "+", "1", "session", "=", "cookies", ".", "RequestsCookieJar", "(", ")", "if", "'Cookie'", "in", "fetch", "[", "'headers'", "]", ":", "c", "=", "http_cookies", ".", "SimpleCookie", "(", ")", "try", ":", "c", ".", "load", "(", "fetch", "[", "'headers'", "]", "[", "'Cookie'", "]", ")", "except", "AttributeError", ":", "c", ".", "load", "(", "utils", ".", "utf8", "(", "fetch", "[", "'headers'", "]", "[", "'Cookie'", "]", ")", ")", "for", "key", "in", "c", ":", "session", ".", "set", "(", "key", ",", "c", "[", "key", "]", ")", "del", "fetch", "[", "'headers'", "]", "[", "'Cookie'", "]", "if", "'cookies'", "in", "fetch", ":", "session", ".", "update", "(", "fetch", "[", "'cookies'", "]", ")", "del", "fetch", "[", "'cookies'", "]", "request", "=", "tornado", ".", "httpclient", ".", "HTTPRequest", "(", "url", "=", "fetch", "[", "'url'", "]", ")", "cookie_header", "=", "cookies", ".", "get_cookie_header", "(", "session", ",", "request", ")", "if", "cookie_header", ":", "fetch", "[", "'headers'", "]", "[", "'Cookie'", "]", "=", "cookie_header", "# making requests", "fetch", "[", "'headers'", "]", "=", "dict", "(", "fetch", "[", "'headers'", "]", ")", "try", ":", "request", "=", "tornado", ".", "httpclient", ".", "HTTPRequest", "(", "url", "=", "self", ".", "phantomjs_proxy", ",", "method", "=", "\"POST\"", ",", "body", "=", "json", ".", "dumps", "(", "fetch", ")", ",", "*", "*", "request_conf", ")", "except", "Exception", "as", "e", ":", "raise", "gen", ".", "Return", "(", "handle_error", "(", "e", ")", ")", "try", ":", "response", "=", "yield", "gen", ".", "maybe_future", "(", "self", ".", "http_client", ".", "fetch", "(", "request", ")", ")", "except", "tornado", ".", "httpclient", ".", "HTTPError", "as", "e", ":", "if", "e", ".", "response", ":", "response", "=", "e", ".", "response", "else", ":", "raise", "gen", ".", "Return", "(", "handle_error", "(", "e", ")", ")", "if", "not", "response", ".", "body", ":", "raise", "gen", ".", "Return", "(", "handle_error", "(", "Exception", "(", "'no response from phantomjs: %r'", "%", "response", ")", ")", ")", "result", "=", "{", "}", "try", ":", "result", "=", "json", ".", "loads", "(", "utils", ".", "text", "(", "response", ".", "body", ")", ")", "assert", "'status_code'", "in", "result", ",", "result", "except", "Exception", "as", "e", ":", "if", "response", ".", "error", ":", "result", "[", "'error'", "]", "=", "utils", ".", "text", "(", "response", ".", "error", ")", "raise", "gen", ".", "Return", "(", "handle_error", "(", "e", ")", ")", "if", "result", ".", "get", "(", "'status_code'", ",", "200", ")", ":", "logger", ".", "info", "(", "\"[%d] %s:%s %s %.2fs\"", ",", "result", "[", "'status_code'", "]", ",", "task", ".", "get", "(", "'project'", ")", ",", "task", ".", "get", "(", "'taskid'", ")", ",", "url", ",", "result", "[", "'time'", "]", ")", "else", ":", "logger", ".", "error", "(", "\"[%d] %s:%s %s, %r %.2fs\"", ",", "result", "[", "'status_code'", "]", ",", "task", ".", "get", "(", "'project'", ")", ",", "task", ".", "get", "(", "'taskid'", ")", ",", "url", ",", "result", "[", "'content'", "]", ",", "result", "[", "'time'", "]", ")", "raise", "gen", ".", "Return", "(", "result", ")" ]
Fetch with phantomjs proxy
[ "Fetch", "with", "phantomjs", "proxy" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L431-L529
train
binux/pyspider
pyspider/fetcher/tornado_fetcher.py
Fetcher.run
def run(self): '''Run loop''' logger.info("fetcher starting...") def queue_loop(): if not self.outqueue or not self.inqueue: return while not self._quit: try: if self.outqueue.full(): break if self.http_client.free_size() <= 0: break task = self.inqueue.get_nowait() # FIXME: decode unicode_obj should used after data selete from # database, it's used here for performance task = utils.decode_unicode_obj(task) self.fetch(task) except queue.Empty: break except KeyboardInterrupt: break except Exception as e: logger.exception(e) break tornado.ioloop.PeriodicCallback(queue_loop, 100, io_loop=self.ioloop).start() tornado.ioloop.PeriodicCallback(self.clear_robot_txt_cache, 10000, io_loop=self.ioloop).start() self._running = True try: self.ioloop.start() except KeyboardInterrupt: pass logger.info("fetcher exiting...")
python
def run(self): '''Run loop''' logger.info("fetcher starting...") def queue_loop(): if not self.outqueue or not self.inqueue: return while not self._quit: try: if self.outqueue.full(): break if self.http_client.free_size() <= 0: break task = self.inqueue.get_nowait() # FIXME: decode unicode_obj should used after data selete from # database, it's used here for performance task = utils.decode_unicode_obj(task) self.fetch(task) except queue.Empty: break except KeyboardInterrupt: break except Exception as e: logger.exception(e) break tornado.ioloop.PeriodicCallback(queue_loop, 100, io_loop=self.ioloop).start() tornado.ioloop.PeriodicCallback(self.clear_robot_txt_cache, 10000, io_loop=self.ioloop).start() self._running = True try: self.ioloop.start() except KeyboardInterrupt: pass logger.info("fetcher exiting...")
[ "def", "run", "(", "self", ")", ":", "logger", ".", "info", "(", "\"fetcher starting...\"", ")", "def", "queue_loop", "(", ")", ":", "if", "not", "self", ".", "outqueue", "or", "not", "self", ".", "inqueue", ":", "return", "while", "not", "self", ".", "_quit", ":", "try", ":", "if", "self", ".", "outqueue", ".", "full", "(", ")", ":", "break", "if", "self", ".", "http_client", ".", "free_size", "(", ")", "<=", "0", ":", "break", "task", "=", "self", ".", "inqueue", ".", "get_nowait", "(", ")", "# FIXME: decode unicode_obj should used after data selete from", "# database, it's used here for performance", "task", "=", "utils", ".", "decode_unicode_obj", "(", "task", ")", "self", ".", "fetch", "(", "task", ")", "except", "queue", ".", "Empty", ":", "break", "except", "KeyboardInterrupt", ":", "break", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "e", ")", "break", "tornado", ".", "ioloop", ".", "PeriodicCallback", "(", "queue_loop", ",", "100", ",", "io_loop", "=", "self", ".", "ioloop", ")", ".", "start", "(", ")", "tornado", ".", "ioloop", ".", "PeriodicCallback", "(", "self", ".", "clear_robot_txt_cache", ",", "10000", ",", "io_loop", "=", "self", ".", "ioloop", ")", ".", "start", "(", ")", "self", ".", "_running", "=", "True", "try", ":", "self", ".", "ioloop", ".", "start", "(", ")", "except", "KeyboardInterrupt", ":", "pass", "logger", ".", "info", "(", "\"fetcher exiting...\"", ")" ]
Run loop
[ "Run", "loop" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L743-L778
train
binux/pyspider
pyspider/fetcher/tornado_fetcher.py
Fetcher.quit
def quit(self): '''Quit fetcher''' self._running = False self._quit = True self.ioloop.add_callback(self.ioloop.stop) if hasattr(self, 'xmlrpc_server'): self.xmlrpc_ioloop.add_callback(self.xmlrpc_server.stop) self.xmlrpc_ioloop.add_callback(self.xmlrpc_ioloop.stop)
python
def quit(self): '''Quit fetcher''' self._running = False self._quit = True self.ioloop.add_callback(self.ioloop.stop) if hasattr(self, 'xmlrpc_server'): self.xmlrpc_ioloop.add_callback(self.xmlrpc_server.stop) self.xmlrpc_ioloop.add_callback(self.xmlrpc_ioloop.stop)
[ "def", "quit", "(", "self", ")", ":", "self", ".", "_running", "=", "False", "self", ".", "_quit", "=", "True", "self", ".", "ioloop", ".", "add_callback", "(", "self", ".", "ioloop", ".", "stop", ")", "if", "hasattr", "(", "self", ",", "'xmlrpc_server'", ")", ":", "self", ".", "xmlrpc_ioloop", ".", "add_callback", "(", "self", ".", "xmlrpc_server", ".", "stop", ")", "self", ".", "xmlrpc_ioloop", ".", "add_callback", "(", "self", ".", "xmlrpc_ioloop", ".", "stop", ")" ]
Quit fetcher
[ "Quit", "fetcher" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L780-L787
train
binux/pyspider
pyspider/fetcher/tornado_fetcher.py
Fetcher.xmlrpc_run
def xmlrpc_run(self, port=24444, bind='127.0.0.1', logRequests=False): '''Run xmlrpc server''' import umsgpack from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication try: from xmlrpc.client import Binary except ImportError: from xmlrpclib import Binary application = WSGIXMLRPCApplication() application.register_function(self.quit, '_quit') application.register_function(self.size) def sync_fetch(task): result = self.sync_fetch(task) result = Binary(umsgpack.packb(result)) return result application.register_function(sync_fetch, 'fetch') def dump_counter(_time, _type): return self._cnt[_time].to_dict(_type) application.register_function(dump_counter, 'counter') import tornado.wsgi import tornado.ioloop import tornado.httpserver container = tornado.wsgi.WSGIContainer(application) self.xmlrpc_ioloop = tornado.ioloop.IOLoop() self.xmlrpc_server = tornado.httpserver.HTTPServer(container, io_loop=self.xmlrpc_ioloop) self.xmlrpc_server.listen(port=port, address=bind) logger.info('fetcher.xmlrpc listening on %s:%s', bind, port) self.xmlrpc_ioloop.start()
python
def xmlrpc_run(self, port=24444, bind='127.0.0.1', logRequests=False): '''Run xmlrpc server''' import umsgpack from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication try: from xmlrpc.client import Binary except ImportError: from xmlrpclib import Binary application = WSGIXMLRPCApplication() application.register_function(self.quit, '_quit') application.register_function(self.size) def sync_fetch(task): result = self.sync_fetch(task) result = Binary(umsgpack.packb(result)) return result application.register_function(sync_fetch, 'fetch') def dump_counter(_time, _type): return self._cnt[_time].to_dict(_type) application.register_function(dump_counter, 'counter') import tornado.wsgi import tornado.ioloop import tornado.httpserver container = tornado.wsgi.WSGIContainer(application) self.xmlrpc_ioloop = tornado.ioloop.IOLoop() self.xmlrpc_server = tornado.httpserver.HTTPServer(container, io_loop=self.xmlrpc_ioloop) self.xmlrpc_server.listen(port=port, address=bind) logger.info('fetcher.xmlrpc listening on %s:%s', bind, port) self.xmlrpc_ioloop.start()
[ "def", "xmlrpc_run", "(", "self", ",", "port", "=", "24444", ",", "bind", "=", "'127.0.0.1'", ",", "logRequests", "=", "False", ")", ":", "import", "umsgpack", "from", "pyspider", ".", "libs", ".", "wsgi_xmlrpc", "import", "WSGIXMLRPCApplication", "try", ":", "from", "xmlrpc", ".", "client", "import", "Binary", "except", "ImportError", ":", "from", "xmlrpclib", "import", "Binary", "application", "=", "WSGIXMLRPCApplication", "(", ")", "application", ".", "register_function", "(", "self", ".", "quit", ",", "'_quit'", ")", "application", ".", "register_function", "(", "self", ".", "size", ")", "def", "sync_fetch", "(", "task", ")", ":", "result", "=", "self", ".", "sync_fetch", "(", "task", ")", "result", "=", "Binary", "(", "umsgpack", ".", "packb", "(", "result", ")", ")", "return", "result", "application", ".", "register_function", "(", "sync_fetch", ",", "'fetch'", ")", "def", "dump_counter", "(", "_time", ",", "_type", ")", ":", "return", "self", ".", "_cnt", "[", "_time", "]", ".", "to_dict", "(", "_type", ")", "application", ".", "register_function", "(", "dump_counter", ",", "'counter'", ")", "import", "tornado", ".", "wsgi", "import", "tornado", ".", "ioloop", "import", "tornado", ".", "httpserver", "container", "=", "tornado", ".", "wsgi", ".", "WSGIContainer", "(", "application", ")", "self", ".", "xmlrpc_ioloop", "=", "tornado", ".", "ioloop", ".", "IOLoop", "(", ")", "self", ".", "xmlrpc_server", "=", "tornado", ".", "httpserver", ".", "HTTPServer", "(", "container", ",", "io_loop", "=", "self", ".", "xmlrpc_ioloop", ")", "self", ".", "xmlrpc_server", ".", "listen", "(", "port", "=", "port", ",", "address", "=", "bind", ")", "logger", ".", "info", "(", "'fetcher.xmlrpc listening on %s:%s'", ",", "bind", ",", "port", ")", "self", ".", "xmlrpc_ioloop", ".", "start", "(", ")" ]
Run xmlrpc server
[ "Run", "xmlrpc", "server" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L792-L825
train
binux/pyspider
pyspider/fetcher/tornado_fetcher.py
Fetcher.on_result
def on_result(self, type, task, result): '''Called after task fetched''' status_code = result.get('status_code', 599) if status_code != 599: status_code = (int(status_code) / 100 * 100) self._cnt['5m'].event((task.get('project'), status_code), +1) self._cnt['1h'].event((task.get('project'), status_code), +1) if type in ('http', 'phantomjs') and result.get('time'): content_len = len(result.get('content', '')) self._cnt['5m'].event((task.get('project'), 'speed'), float(content_len) / result.get('time')) self._cnt['1h'].event((task.get('project'), 'speed'), float(content_len) / result.get('time')) self._cnt['5m'].event((task.get('project'), 'time'), result.get('time')) self._cnt['1h'].event((task.get('project'), 'time'), result.get('time'))
python
def on_result(self, type, task, result): '''Called after task fetched''' status_code = result.get('status_code', 599) if status_code != 599: status_code = (int(status_code) / 100 * 100) self._cnt['5m'].event((task.get('project'), status_code), +1) self._cnt['1h'].event((task.get('project'), status_code), +1) if type in ('http', 'phantomjs') and result.get('time'): content_len = len(result.get('content', '')) self._cnt['5m'].event((task.get('project'), 'speed'), float(content_len) / result.get('time')) self._cnt['1h'].event((task.get('project'), 'speed'), float(content_len) / result.get('time')) self._cnt['5m'].event((task.get('project'), 'time'), result.get('time')) self._cnt['1h'].event((task.get('project'), 'time'), result.get('time'))
[ "def", "on_result", "(", "self", ",", "type", ",", "task", ",", "result", ")", ":", "status_code", "=", "result", ".", "get", "(", "'status_code'", ",", "599", ")", "if", "status_code", "!=", "599", ":", "status_code", "=", "(", "int", "(", "status_code", ")", "/", "100", "*", "100", ")", "self", ".", "_cnt", "[", "'5m'", "]", ".", "event", "(", "(", "task", ".", "get", "(", "'project'", ")", ",", "status_code", ")", ",", "+", "1", ")", "self", ".", "_cnt", "[", "'1h'", "]", ".", "event", "(", "(", "task", ".", "get", "(", "'project'", ")", ",", "status_code", ")", ",", "+", "1", ")", "if", "type", "in", "(", "'http'", ",", "'phantomjs'", ")", "and", "result", ".", "get", "(", "'time'", ")", ":", "content_len", "=", "len", "(", "result", ".", "get", "(", "'content'", ",", "''", ")", ")", "self", ".", "_cnt", "[", "'5m'", "]", ".", "event", "(", "(", "task", ".", "get", "(", "'project'", ")", ",", "'speed'", ")", ",", "float", "(", "content_len", ")", "/", "result", ".", "get", "(", "'time'", ")", ")", "self", ".", "_cnt", "[", "'1h'", "]", ".", "event", "(", "(", "task", ".", "get", "(", "'project'", ")", ",", "'speed'", ")", ",", "float", "(", "content_len", ")", "/", "result", ".", "get", "(", "'time'", ")", ")", "self", ".", "_cnt", "[", "'5m'", "]", ".", "event", "(", "(", "task", ".", "get", "(", "'project'", ")", ",", "'time'", ")", ",", "result", ".", "get", "(", "'time'", ")", ")", "self", ".", "_cnt", "[", "'1h'", "]", ".", "event", "(", "(", "task", ".", "get", "(", "'project'", ")", ",", "'time'", ")", ",", "result", ".", "get", "(", "'time'", ")", ")" ]
Called after task fetched
[ "Called", "after", "task", "fetched" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L831-L846
train
binux/pyspider
pyspider/libs/counter.py
CounterValue.to_dict
def to_dict(self, get_value=None): """Dump counters as a dict""" result = {} for key, value in iteritems(self): if isinstance(value, BaseCounter): if get_value is not None: value = getattr(value, get_value) result[key] = value else: result[key] = value.to_dict(get_value) return result
python
def to_dict(self, get_value=None): """Dump counters as a dict""" result = {} for key, value in iteritems(self): if isinstance(value, BaseCounter): if get_value is not None: value = getattr(value, get_value) result[key] = value else: result[key] = value.to_dict(get_value) return result
[ "def", "to_dict", "(", "self", ",", "get_value", "=", "None", ")", ":", "result", "=", "{", "}", "for", "key", ",", "value", "in", "iteritems", "(", "self", ")", ":", "if", "isinstance", "(", "value", ",", "BaseCounter", ")", ":", "if", "get_value", "is", "not", "None", ":", "value", "=", "getattr", "(", "value", ",", "get_value", ")", "result", "[", "key", "]", "=", "value", "else", ":", "result", "[", "key", "]", "=", "value", ".", "to_dict", "(", "get_value", ")", "return", "result" ]
Dump counters as a dict
[ "Dump", "counters", "as", "a", "dict" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L316-L326
train
binux/pyspider
pyspider/libs/counter.py
CounterManager.value
def value(self, key, value=1): """Set value of a counter by counter key""" if isinstance(key, six.string_types): key = (key, ) # assert all(isinstance(k, six.string_types) for k in key) assert isinstance(key, tuple), "event key type error" if key not in self.counters: self.counters[key] = self.cls() self.counters[key].value(value) return self
python
def value(self, key, value=1): """Set value of a counter by counter key""" if isinstance(key, six.string_types): key = (key, ) # assert all(isinstance(k, six.string_types) for k in key) assert isinstance(key, tuple), "event key type error" if key not in self.counters: self.counters[key] = self.cls() self.counters[key].value(value) return self
[ "def", "value", "(", "self", ",", "key", ",", "value", "=", "1", ")", ":", "if", "isinstance", "(", "key", ",", "six", ".", "string_types", ")", ":", "key", "=", "(", "key", ",", ")", "# assert all(isinstance(k, six.string_types) for k in key)", "assert", "isinstance", "(", "key", ",", "tuple", ")", ",", "\"event key type error\"", "if", "key", "not", "in", "self", ".", "counters", ":", "self", ".", "counters", "[", "key", "]", "=", "self", ".", "cls", "(", ")", "self", ".", "counters", "[", "key", "]", ".", "value", "(", "value", ")", "return", "self" ]
Set value of a counter by counter key
[ "Set", "value", "of", "a", "counter", "by", "counter", "key" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L355-L364
train
binux/pyspider
pyspider/libs/counter.py
CounterManager.trim
def trim(self): """Clear not used counters""" for key, value in list(iteritems(self.counters)): if value.empty(): del self.counters[key]
python
def trim(self): """Clear not used counters""" for key, value in list(iteritems(self.counters)): if value.empty(): del self.counters[key]
[ "def", "trim", "(", "self", ")", ":", "for", "key", ",", "value", "in", "list", "(", "iteritems", "(", "self", ".", "counters", ")", ")", ":", "if", "value", ".", "empty", "(", ")", ":", "del", "self", ".", "counters", "[", "key", "]" ]
Clear not used counters
[ "Clear", "not", "used", "counters" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L366-L370
train
binux/pyspider
pyspider/libs/counter.py
CounterManager.to_dict
def to_dict(self, get_value=None): """Dump counters as a dict""" self.trim() result = {} for key, value in iteritems(self.counters): if get_value is not None: value = getattr(value, get_value) r = result for _key in key[:-1]: r = r.setdefault(_key, {}) r[key[-1]] = value return result
python
def to_dict(self, get_value=None): """Dump counters as a dict""" self.trim() result = {} for key, value in iteritems(self.counters): if get_value is not None: value = getattr(value, get_value) r = result for _key in key[:-1]: r = r.setdefault(_key, {}) r[key[-1]] = value return result
[ "def", "to_dict", "(", "self", ",", "get_value", "=", "None", ")", ":", "self", ".", "trim", "(", ")", "result", "=", "{", "}", "for", "key", ",", "value", "in", "iteritems", "(", "self", ".", "counters", ")", ":", "if", "get_value", "is", "not", "None", ":", "value", "=", "getattr", "(", "value", ",", "get_value", ")", "r", "=", "result", "for", "_key", "in", "key", "[", ":", "-", "1", "]", ":", "r", "=", "r", ".", "setdefault", "(", "_key", ",", "{", "}", ")", "r", "[", "key", "[", "-", "1", "]", "]", "=", "value", "return", "result" ]
Dump counters as a dict
[ "Dump", "counters", "as", "a", "dict" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L410-L421
train
binux/pyspider
pyspider/libs/counter.py
CounterManager.dump
def dump(self, filename): """Dump counters to file""" try: with open(filename, 'wb') as fp: cPickle.dump(self.counters, fp) except Exception as e: logging.warning("can't dump counter to file %s: %s", filename, e) return False return True
python
def dump(self, filename): """Dump counters to file""" try: with open(filename, 'wb') as fp: cPickle.dump(self.counters, fp) except Exception as e: logging.warning("can't dump counter to file %s: %s", filename, e) return False return True
[ "def", "dump", "(", "self", ",", "filename", ")", ":", "try", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "fp", ":", "cPickle", ".", "dump", "(", "self", ".", "counters", ",", "fp", ")", "except", "Exception", "as", "e", ":", "logging", ".", "warning", "(", "\"can't dump counter to file %s: %s\"", ",", "filename", ",", "e", ")", "return", "False", "return", "True" ]
Dump counters to file
[ "Dump", "counters", "to", "file" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L423-L431
train
binux/pyspider
pyspider/libs/counter.py
CounterManager.load
def load(self, filename): """Load counters to file""" try: with open(filename, 'rb') as fp: self.counters = cPickle.load(fp) except: logging.debug("can't load counter from file: %s", filename) return False return True
python
def load(self, filename): """Load counters to file""" try: with open(filename, 'rb') as fp: self.counters = cPickle.load(fp) except: logging.debug("can't load counter from file: %s", filename) return False return True
[ "def", "load", "(", "self", ",", "filename", ")", ":", "try", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fp", ":", "self", ".", "counters", "=", "cPickle", ".", "load", "(", "fp", ")", "except", ":", "logging", ".", "debug", "(", "\"can't load counter from file: %s\"", ",", "filename", ")", "return", "False", "return", "True" ]
Load counters to file
[ "Load", "counters", "to", "file" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L433-L441
train
binux/pyspider
pyspider/run.py
cli
def cli(ctx, **kwargs): """ A powerful spider system in python. """ if kwargs['add_sys_path']: sys.path.append(os.getcwd()) logging.config.fileConfig(kwargs['logging_config']) # get db from env for db in ('taskdb', 'projectdb', 'resultdb'): if kwargs[db] is not None: continue if os.environ.get('MYSQL_NAME'): kwargs[db] = utils.Get(lambda db=db: connect_database( 'sqlalchemy+mysql+%s://%s:%s/%s' % ( db, os.environ['MYSQL_PORT_3306_TCP_ADDR'], os.environ['MYSQL_PORT_3306_TCP_PORT'], db))) elif os.environ.get('MONGODB_NAME'): kwargs[db] = utils.Get(lambda db=db: connect_database( 'mongodb+%s://%s:%s/%s' % ( db, os.environ['MONGODB_PORT_27017_TCP_ADDR'], os.environ['MONGODB_PORT_27017_TCP_PORT'], db))) elif ctx.invoked_subcommand == 'bench': if kwargs['data_path'] == './data': kwargs['data_path'] += '/bench' shutil.rmtree(kwargs['data_path'], ignore_errors=True) os.mkdir(kwargs['data_path']) if db in ('taskdb', 'resultdb'): kwargs[db] = utils.Get(lambda db=db: connect_database('sqlite+%s://' % (db))) elif db in ('projectdb', ): kwargs[db] = utils.Get(lambda db=db: connect_database('local+%s://%s' % ( db, os.path.join(os.path.dirname(__file__), 'libs/bench.py')))) else: if not os.path.exists(kwargs['data_path']): os.mkdir(kwargs['data_path']) kwargs[db] = utils.Get(lambda db=db: connect_database('sqlite+%s:///%s/%s.db' % ( db, kwargs['data_path'], db[:-2]))) kwargs['is_%s_default' % db] = True # create folder for counter.dump if not os.path.exists(kwargs['data_path']): os.mkdir(kwargs['data_path']) # message queue, compatible with old version if kwargs.get('message_queue'): pass elif kwargs.get('amqp_url'): kwargs['message_queue'] = kwargs['amqp_url'] elif os.environ.get('RABBITMQ_NAME'): kwargs['message_queue'] = ("amqp://guest:guest@%(RABBITMQ_PORT_5672_TCP_ADDR)s" ":%(RABBITMQ_PORT_5672_TCP_PORT)s/%%2F" % os.environ) elif kwargs.get('beanstalk'): kwargs['message_queue'] = "beanstalk://%s/" % kwargs['beanstalk'] for name in ('newtask_queue', 'status_queue', 'scheduler2fetcher', 'fetcher2processor', 'processor2result'): if kwargs.get('message_queue'): kwargs[name] = utils.Get(lambda name=name: connect_message_queue( name, kwargs.get('message_queue'), kwargs['queue_maxsize'])) else: kwargs[name] = connect_message_queue(name, kwargs.get('message_queue'), kwargs['queue_maxsize']) # phantomjs-proxy if kwargs.get('phantomjs_proxy'): pass elif os.environ.get('PHANTOMJS_NAME'): kwargs['phantomjs_proxy'] = os.environ['PHANTOMJS_PORT_25555_TCP'][len('tcp://'):] # puppeteer-proxy if kwargs.get('puppeteer_proxy'): pass elif os.environ.get('PUPPETEER_NAME'): kwargs['puppeteer_proxy'] = os.environ['PUPPETEER_PORT_22222_TCP'][len('tcp://'):] ctx.obj = utils.ObjectDict(ctx.obj or {}) ctx.obj['instances'] = [] ctx.obj.update(kwargs) if ctx.invoked_subcommand is None and not ctx.obj.get('testing_mode'): ctx.invoke(all) return ctx
python
def cli(ctx, **kwargs): """ A powerful spider system in python. """ if kwargs['add_sys_path']: sys.path.append(os.getcwd()) logging.config.fileConfig(kwargs['logging_config']) # get db from env for db in ('taskdb', 'projectdb', 'resultdb'): if kwargs[db] is not None: continue if os.environ.get('MYSQL_NAME'): kwargs[db] = utils.Get(lambda db=db: connect_database( 'sqlalchemy+mysql+%s://%s:%s/%s' % ( db, os.environ['MYSQL_PORT_3306_TCP_ADDR'], os.environ['MYSQL_PORT_3306_TCP_PORT'], db))) elif os.environ.get('MONGODB_NAME'): kwargs[db] = utils.Get(lambda db=db: connect_database( 'mongodb+%s://%s:%s/%s' % ( db, os.environ['MONGODB_PORT_27017_TCP_ADDR'], os.environ['MONGODB_PORT_27017_TCP_PORT'], db))) elif ctx.invoked_subcommand == 'bench': if kwargs['data_path'] == './data': kwargs['data_path'] += '/bench' shutil.rmtree(kwargs['data_path'], ignore_errors=True) os.mkdir(kwargs['data_path']) if db in ('taskdb', 'resultdb'): kwargs[db] = utils.Get(lambda db=db: connect_database('sqlite+%s://' % (db))) elif db in ('projectdb', ): kwargs[db] = utils.Get(lambda db=db: connect_database('local+%s://%s' % ( db, os.path.join(os.path.dirname(__file__), 'libs/bench.py')))) else: if not os.path.exists(kwargs['data_path']): os.mkdir(kwargs['data_path']) kwargs[db] = utils.Get(lambda db=db: connect_database('sqlite+%s:///%s/%s.db' % ( db, kwargs['data_path'], db[:-2]))) kwargs['is_%s_default' % db] = True # create folder for counter.dump if not os.path.exists(kwargs['data_path']): os.mkdir(kwargs['data_path']) # message queue, compatible with old version if kwargs.get('message_queue'): pass elif kwargs.get('amqp_url'): kwargs['message_queue'] = kwargs['amqp_url'] elif os.environ.get('RABBITMQ_NAME'): kwargs['message_queue'] = ("amqp://guest:guest@%(RABBITMQ_PORT_5672_TCP_ADDR)s" ":%(RABBITMQ_PORT_5672_TCP_PORT)s/%%2F" % os.environ) elif kwargs.get('beanstalk'): kwargs['message_queue'] = "beanstalk://%s/" % kwargs['beanstalk'] for name in ('newtask_queue', 'status_queue', 'scheduler2fetcher', 'fetcher2processor', 'processor2result'): if kwargs.get('message_queue'): kwargs[name] = utils.Get(lambda name=name: connect_message_queue( name, kwargs.get('message_queue'), kwargs['queue_maxsize'])) else: kwargs[name] = connect_message_queue(name, kwargs.get('message_queue'), kwargs['queue_maxsize']) # phantomjs-proxy if kwargs.get('phantomjs_proxy'): pass elif os.environ.get('PHANTOMJS_NAME'): kwargs['phantomjs_proxy'] = os.environ['PHANTOMJS_PORT_25555_TCP'][len('tcp://'):] # puppeteer-proxy if kwargs.get('puppeteer_proxy'): pass elif os.environ.get('PUPPETEER_NAME'): kwargs['puppeteer_proxy'] = os.environ['PUPPETEER_PORT_22222_TCP'][len('tcp://'):] ctx.obj = utils.ObjectDict(ctx.obj or {}) ctx.obj['instances'] = [] ctx.obj.update(kwargs) if ctx.invoked_subcommand is None and not ctx.obj.get('testing_mode'): ctx.invoke(all) return ctx
[ "def", "cli", "(", "ctx", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", "[", "'add_sys_path'", "]", ":", "sys", ".", "path", ".", "append", "(", "os", ".", "getcwd", "(", ")", ")", "logging", ".", "config", ".", "fileConfig", "(", "kwargs", "[", "'logging_config'", "]", ")", "# get db from env", "for", "db", "in", "(", "'taskdb'", ",", "'projectdb'", ",", "'resultdb'", ")", ":", "if", "kwargs", "[", "db", "]", "is", "not", "None", ":", "continue", "if", "os", ".", "environ", ".", "get", "(", "'MYSQL_NAME'", ")", ":", "kwargs", "[", "db", "]", "=", "utils", ".", "Get", "(", "lambda", "db", "=", "db", ":", "connect_database", "(", "'sqlalchemy+mysql+%s://%s:%s/%s'", "%", "(", "db", ",", "os", ".", "environ", "[", "'MYSQL_PORT_3306_TCP_ADDR'", "]", ",", "os", ".", "environ", "[", "'MYSQL_PORT_3306_TCP_PORT'", "]", ",", "db", ")", ")", ")", "elif", "os", ".", "environ", ".", "get", "(", "'MONGODB_NAME'", ")", ":", "kwargs", "[", "db", "]", "=", "utils", ".", "Get", "(", "lambda", "db", "=", "db", ":", "connect_database", "(", "'mongodb+%s://%s:%s/%s'", "%", "(", "db", ",", "os", ".", "environ", "[", "'MONGODB_PORT_27017_TCP_ADDR'", "]", ",", "os", ".", "environ", "[", "'MONGODB_PORT_27017_TCP_PORT'", "]", ",", "db", ")", ")", ")", "elif", "ctx", ".", "invoked_subcommand", "==", "'bench'", ":", "if", "kwargs", "[", "'data_path'", "]", "==", "'./data'", ":", "kwargs", "[", "'data_path'", "]", "+=", "'/bench'", "shutil", ".", "rmtree", "(", "kwargs", "[", "'data_path'", "]", ",", "ignore_errors", "=", "True", ")", "os", ".", "mkdir", "(", "kwargs", "[", "'data_path'", "]", ")", "if", "db", "in", "(", "'taskdb'", ",", "'resultdb'", ")", ":", "kwargs", "[", "db", "]", "=", "utils", ".", "Get", "(", "lambda", "db", "=", "db", ":", "connect_database", "(", "'sqlite+%s://'", "%", "(", "db", ")", ")", ")", "elif", "db", "in", "(", "'projectdb'", ",", ")", ":", "kwargs", "[", "db", "]", "=", "utils", ".", "Get", "(", "lambda", "db", "=", "db", ":", "connect_database", "(", "'local+%s://%s'", "%", "(", "db", ",", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'libs/bench.py'", ")", ")", ")", ")", "else", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "kwargs", "[", "'data_path'", "]", ")", ":", "os", ".", "mkdir", "(", "kwargs", "[", "'data_path'", "]", ")", "kwargs", "[", "db", "]", "=", "utils", ".", "Get", "(", "lambda", "db", "=", "db", ":", "connect_database", "(", "'sqlite+%s:///%s/%s.db'", "%", "(", "db", ",", "kwargs", "[", "'data_path'", "]", ",", "db", "[", ":", "-", "2", "]", ")", ")", ")", "kwargs", "[", "'is_%s_default'", "%", "db", "]", "=", "True", "# create folder for counter.dump", "if", "not", "os", ".", "path", ".", "exists", "(", "kwargs", "[", "'data_path'", "]", ")", ":", "os", ".", "mkdir", "(", "kwargs", "[", "'data_path'", "]", ")", "# message queue, compatible with old version", "if", "kwargs", ".", "get", "(", "'message_queue'", ")", ":", "pass", "elif", "kwargs", ".", "get", "(", "'amqp_url'", ")", ":", "kwargs", "[", "'message_queue'", "]", "=", "kwargs", "[", "'amqp_url'", "]", "elif", "os", ".", "environ", ".", "get", "(", "'RABBITMQ_NAME'", ")", ":", "kwargs", "[", "'message_queue'", "]", "=", "(", "\"amqp://guest:guest@%(RABBITMQ_PORT_5672_TCP_ADDR)s\"", "\":%(RABBITMQ_PORT_5672_TCP_PORT)s/%%2F\"", "%", "os", ".", "environ", ")", "elif", "kwargs", ".", "get", "(", "'beanstalk'", ")", ":", "kwargs", "[", "'message_queue'", "]", "=", "\"beanstalk://%s/\"", "%", "kwargs", "[", "'beanstalk'", "]", "for", "name", "in", "(", "'newtask_queue'", ",", "'status_queue'", ",", "'scheduler2fetcher'", ",", "'fetcher2processor'", ",", "'processor2result'", ")", ":", "if", "kwargs", ".", "get", "(", "'message_queue'", ")", ":", "kwargs", "[", "name", "]", "=", "utils", ".", "Get", "(", "lambda", "name", "=", "name", ":", "connect_message_queue", "(", "name", ",", "kwargs", ".", "get", "(", "'message_queue'", ")", ",", "kwargs", "[", "'queue_maxsize'", "]", ")", ")", "else", ":", "kwargs", "[", "name", "]", "=", "connect_message_queue", "(", "name", ",", "kwargs", ".", "get", "(", "'message_queue'", ")", ",", "kwargs", "[", "'queue_maxsize'", "]", ")", "# phantomjs-proxy", "if", "kwargs", ".", "get", "(", "'phantomjs_proxy'", ")", ":", "pass", "elif", "os", ".", "environ", ".", "get", "(", "'PHANTOMJS_NAME'", ")", ":", "kwargs", "[", "'phantomjs_proxy'", "]", "=", "os", ".", "environ", "[", "'PHANTOMJS_PORT_25555_TCP'", "]", "[", "len", "(", "'tcp://'", ")", ":", "]", "# puppeteer-proxy", "if", "kwargs", ".", "get", "(", "'puppeteer_proxy'", ")", ":", "pass", "elif", "os", ".", "environ", ".", "get", "(", "'PUPPETEER_NAME'", ")", ":", "kwargs", "[", "'puppeteer_proxy'", "]", "=", "os", ".", "environ", "[", "'PUPPETEER_PORT_22222_TCP'", "]", "[", "len", "(", "'tcp://'", ")", ":", "]", "ctx", ".", "obj", "=", "utils", ".", "ObjectDict", "(", "ctx", ".", "obj", "or", "{", "}", ")", "ctx", ".", "obj", "[", "'instances'", "]", "=", "[", "]", "ctx", ".", "obj", ".", "update", "(", "kwargs", ")", "if", "ctx", ".", "invoked_subcommand", "is", "None", "and", "not", "ctx", ".", "obj", ".", "get", "(", "'testing_mode'", ")", ":", "ctx", ".", "invoke", "(", "all", ")", "return", "ctx" ]
A powerful spider system in python.
[ "A", "powerful", "spider", "system", "in", "python", "." ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L91-L173
train
binux/pyspider
pyspider/run.py
scheduler
def scheduler(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, inqueue_limit, delete_time, active_tasks, loop_limit, fail_pause_num, scheduler_cls, threads, get_object=False): """ Run Scheduler, only one scheduler is allowed. """ g = ctx.obj Scheduler = load_cls(None, None, scheduler_cls) kwargs = dict(taskdb=g.taskdb, projectdb=g.projectdb, resultdb=g.resultdb, newtask_queue=g.newtask_queue, status_queue=g.status_queue, out_queue=g.scheduler2fetcher, data_path=g.get('data_path', 'data')) if threads: kwargs['threads'] = int(threads) scheduler = Scheduler(**kwargs) scheduler.INQUEUE_LIMIT = inqueue_limit scheduler.DELETE_TIME = delete_time scheduler.ACTIVE_TASKS = active_tasks scheduler.LOOP_LIMIT = loop_limit scheduler.FAIL_PAUSE_NUM = fail_pause_num g.instances.append(scheduler) if g.get('testing_mode') or get_object: return scheduler if xmlrpc: utils.run_in_thread(scheduler.xmlrpc_run, port=xmlrpc_port, bind=xmlrpc_host) scheduler.run()
python
def scheduler(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, inqueue_limit, delete_time, active_tasks, loop_limit, fail_pause_num, scheduler_cls, threads, get_object=False): """ Run Scheduler, only one scheduler is allowed. """ g = ctx.obj Scheduler = load_cls(None, None, scheduler_cls) kwargs = dict(taskdb=g.taskdb, projectdb=g.projectdb, resultdb=g.resultdb, newtask_queue=g.newtask_queue, status_queue=g.status_queue, out_queue=g.scheduler2fetcher, data_path=g.get('data_path', 'data')) if threads: kwargs['threads'] = int(threads) scheduler = Scheduler(**kwargs) scheduler.INQUEUE_LIMIT = inqueue_limit scheduler.DELETE_TIME = delete_time scheduler.ACTIVE_TASKS = active_tasks scheduler.LOOP_LIMIT = loop_limit scheduler.FAIL_PAUSE_NUM = fail_pause_num g.instances.append(scheduler) if g.get('testing_mode') or get_object: return scheduler if xmlrpc: utils.run_in_thread(scheduler.xmlrpc_run, port=xmlrpc_port, bind=xmlrpc_host) scheduler.run()
[ "def", "scheduler", "(", "ctx", ",", "xmlrpc", ",", "xmlrpc_host", ",", "xmlrpc_port", ",", "inqueue_limit", ",", "delete_time", ",", "active_tasks", ",", "loop_limit", ",", "fail_pause_num", ",", "scheduler_cls", ",", "threads", ",", "get_object", "=", "False", ")", ":", "g", "=", "ctx", ".", "obj", "Scheduler", "=", "load_cls", "(", "None", ",", "None", ",", "scheduler_cls", ")", "kwargs", "=", "dict", "(", "taskdb", "=", "g", ".", "taskdb", ",", "projectdb", "=", "g", ".", "projectdb", ",", "resultdb", "=", "g", ".", "resultdb", ",", "newtask_queue", "=", "g", ".", "newtask_queue", ",", "status_queue", "=", "g", ".", "status_queue", ",", "out_queue", "=", "g", ".", "scheduler2fetcher", ",", "data_path", "=", "g", ".", "get", "(", "'data_path'", ",", "'data'", ")", ")", "if", "threads", ":", "kwargs", "[", "'threads'", "]", "=", "int", "(", "threads", ")", "scheduler", "=", "Scheduler", "(", "*", "*", "kwargs", ")", "scheduler", ".", "INQUEUE_LIMIT", "=", "inqueue_limit", "scheduler", ".", "DELETE_TIME", "=", "delete_time", "scheduler", ".", "ACTIVE_TASKS", "=", "active_tasks", "scheduler", ".", "LOOP_LIMIT", "=", "loop_limit", "scheduler", ".", "FAIL_PAUSE_NUM", "=", "fail_pause_num", "g", ".", "instances", ".", "append", "(", "scheduler", ")", "if", "g", ".", "get", "(", "'testing_mode'", ")", "or", "get_object", ":", "return", "scheduler", "if", "xmlrpc", ":", "utils", ".", "run_in_thread", "(", "scheduler", ".", "xmlrpc_run", ",", "port", "=", "xmlrpc_port", ",", "bind", "=", "xmlrpc_host", ")", "scheduler", ".", "run", "(", ")" ]
Run Scheduler, only one scheduler is allowed.
[ "Run", "Scheduler", "only", "one", "scheduler", "is", "allowed", "." ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L192-L220
train
binux/pyspider
pyspider/run.py
fetcher
def fetcher(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, poolsize, proxy, user_agent, timeout, phantomjs_endpoint, puppeteer_endpoint, splash_endpoint, fetcher_cls, async_mode=True, get_object=False, no_input=False): """ Run Fetcher. """ g = ctx.obj Fetcher = load_cls(None, None, fetcher_cls) if no_input: inqueue = None outqueue = None else: inqueue = g.scheduler2fetcher outqueue = g.fetcher2processor fetcher = Fetcher(inqueue=inqueue, outqueue=outqueue, poolsize=poolsize, proxy=proxy, async_mode=async_mode) fetcher.phantomjs_proxy = phantomjs_endpoint or g.phantomjs_proxy fetcher.puppeteer_proxy = puppeteer_endpoint or g.puppeteer_proxy fetcher.splash_endpoint = splash_endpoint if user_agent: fetcher.user_agent = user_agent if timeout: fetcher.default_options = copy.deepcopy(fetcher.default_options) fetcher.default_options['timeout'] = timeout g.instances.append(fetcher) if g.get('testing_mode') or get_object: return fetcher if xmlrpc: utils.run_in_thread(fetcher.xmlrpc_run, port=xmlrpc_port, bind=xmlrpc_host) fetcher.run()
python
def fetcher(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, poolsize, proxy, user_agent, timeout, phantomjs_endpoint, puppeteer_endpoint, splash_endpoint, fetcher_cls, async_mode=True, get_object=False, no_input=False): """ Run Fetcher. """ g = ctx.obj Fetcher = load_cls(None, None, fetcher_cls) if no_input: inqueue = None outqueue = None else: inqueue = g.scheduler2fetcher outqueue = g.fetcher2processor fetcher = Fetcher(inqueue=inqueue, outqueue=outqueue, poolsize=poolsize, proxy=proxy, async_mode=async_mode) fetcher.phantomjs_proxy = phantomjs_endpoint or g.phantomjs_proxy fetcher.puppeteer_proxy = puppeteer_endpoint or g.puppeteer_proxy fetcher.splash_endpoint = splash_endpoint if user_agent: fetcher.user_agent = user_agent if timeout: fetcher.default_options = copy.deepcopy(fetcher.default_options) fetcher.default_options['timeout'] = timeout g.instances.append(fetcher) if g.get('testing_mode') or get_object: return fetcher if xmlrpc: utils.run_in_thread(fetcher.xmlrpc_run, port=xmlrpc_port, bind=xmlrpc_host) fetcher.run()
[ "def", "fetcher", "(", "ctx", ",", "xmlrpc", ",", "xmlrpc_host", ",", "xmlrpc_port", ",", "poolsize", ",", "proxy", ",", "user_agent", ",", "timeout", ",", "phantomjs_endpoint", ",", "puppeteer_endpoint", ",", "splash_endpoint", ",", "fetcher_cls", ",", "async_mode", "=", "True", ",", "get_object", "=", "False", ",", "no_input", "=", "False", ")", ":", "g", "=", "ctx", ".", "obj", "Fetcher", "=", "load_cls", "(", "None", ",", "None", ",", "fetcher_cls", ")", "if", "no_input", ":", "inqueue", "=", "None", "outqueue", "=", "None", "else", ":", "inqueue", "=", "g", ".", "scheduler2fetcher", "outqueue", "=", "g", ".", "fetcher2processor", "fetcher", "=", "Fetcher", "(", "inqueue", "=", "inqueue", ",", "outqueue", "=", "outqueue", ",", "poolsize", "=", "poolsize", ",", "proxy", "=", "proxy", ",", "async_mode", "=", "async_mode", ")", "fetcher", ".", "phantomjs_proxy", "=", "phantomjs_endpoint", "or", "g", ".", "phantomjs_proxy", "fetcher", ".", "puppeteer_proxy", "=", "puppeteer_endpoint", "or", "g", ".", "puppeteer_proxy", "fetcher", ".", "splash_endpoint", "=", "splash_endpoint", "if", "user_agent", ":", "fetcher", ".", "user_agent", "=", "user_agent", "if", "timeout", ":", "fetcher", ".", "default_options", "=", "copy", ".", "deepcopy", "(", "fetcher", ".", "default_options", ")", "fetcher", ".", "default_options", "[", "'timeout'", "]", "=", "timeout", "g", ".", "instances", ".", "append", "(", "fetcher", ")", "if", "g", ".", "get", "(", "'testing_mode'", ")", "or", "get_object", ":", "return", "fetcher", "if", "xmlrpc", ":", "utils", ".", "run_in_thread", "(", "fetcher", ".", "xmlrpc_run", ",", "port", "=", "xmlrpc_port", ",", "bind", "=", "xmlrpc_host", ")", "fetcher", ".", "run", "(", ")" ]
Run Fetcher.
[ "Run", "Fetcher", "." ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L237-L269
train
binux/pyspider
pyspider/run.py
processor
def processor(ctx, processor_cls, process_time_limit, enable_stdout_capture=True, get_object=False): """ Run Processor. """ g = ctx.obj Processor = load_cls(None, None, processor_cls) processor = Processor(projectdb=g.projectdb, inqueue=g.fetcher2processor, status_queue=g.status_queue, newtask_queue=g.newtask_queue, result_queue=g.processor2result, enable_stdout_capture=enable_stdout_capture, process_time_limit=process_time_limit) g.instances.append(processor) if g.get('testing_mode') or get_object: return processor processor.run()
python
def processor(ctx, processor_cls, process_time_limit, enable_stdout_capture=True, get_object=False): """ Run Processor. """ g = ctx.obj Processor = load_cls(None, None, processor_cls) processor = Processor(projectdb=g.projectdb, inqueue=g.fetcher2processor, status_queue=g.status_queue, newtask_queue=g.newtask_queue, result_queue=g.processor2result, enable_stdout_capture=enable_stdout_capture, process_time_limit=process_time_limit) g.instances.append(processor) if g.get('testing_mode') or get_object: return processor processor.run()
[ "def", "processor", "(", "ctx", ",", "processor_cls", ",", "process_time_limit", ",", "enable_stdout_capture", "=", "True", ",", "get_object", "=", "False", ")", ":", "g", "=", "ctx", ".", "obj", "Processor", "=", "load_cls", "(", "None", ",", "None", ",", "processor_cls", ")", "processor", "=", "Processor", "(", "projectdb", "=", "g", ".", "projectdb", ",", "inqueue", "=", "g", ".", "fetcher2processor", ",", "status_queue", "=", "g", ".", "status_queue", ",", "newtask_queue", "=", "g", ".", "newtask_queue", ",", "result_queue", "=", "g", ".", "processor2result", ",", "enable_stdout_capture", "=", "enable_stdout_capture", ",", "process_time_limit", "=", "process_time_limit", ")", "g", ".", "instances", ".", "append", "(", "processor", ")", "if", "g", ".", "get", "(", "'testing_mode'", ")", "or", "get_object", ":", "return", "processor", "processor", ".", "run", "(", ")" ]
Run Processor.
[ "Run", "Processor", "." ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L277-L294
train
binux/pyspider
pyspider/run.py
result_worker
def result_worker(ctx, result_cls, get_object=False): """ Run result worker. """ g = ctx.obj ResultWorker = load_cls(None, None, result_cls) result_worker = ResultWorker(resultdb=g.resultdb, inqueue=g.processor2result) g.instances.append(result_worker) if g.get('testing_mode') or get_object: return result_worker result_worker.run()
python
def result_worker(ctx, result_cls, get_object=False): """ Run result worker. """ g = ctx.obj ResultWorker = load_cls(None, None, result_cls) result_worker = ResultWorker(resultdb=g.resultdb, inqueue=g.processor2result) g.instances.append(result_worker) if g.get('testing_mode') or get_object: return result_worker result_worker.run()
[ "def", "result_worker", "(", "ctx", ",", "result_cls", ",", "get_object", "=", "False", ")", ":", "g", "=", "ctx", ".", "obj", "ResultWorker", "=", "load_cls", "(", "None", ",", "None", ",", "result_cls", ")", "result_worker", "=", "ResultWorker", "(", "resultdb", "=", "g", ".", "resultdb", ",", "inqueue", "=", "g", ".", "processor2result", ")", "g", ".", "instances", ".", "append", "(", "result_worker", ")", "if", "g", ".", "get", "(", "'testing_mode'", ")", "or", "get_object", ":", "return", "result_worker", "result_worker", ".", "run", "(", ")" ]
Run result worker.
[ "Run", "result", "worker", "." ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L301-L314
train
binux/pyspider
pyspider/run.py
webui
def webui(ctx, host, port, cdn, scheduler_rpc, fetcher_rpc, max_rate, max_burst, username, password, need_auth, webui_instance, process_time_limit, get_object=False): """ Run WebUI """ app = load_cls(None, None, webui_instance) g = ctx.obj app.config['taskdb'] = g.taskdb app.config['projectdb'] = g.projectdb app.config['resultdb'] = g.resultdb app.config['cdn'] = cdn if max_rate: app.config['max_rate'] = max_rate if max_burst: app.config['max_burst'] = max_burst if username: app.config['webui_username'] = username if password: app.config['webui_password'] = password app.config['need_auth'] = need_auth app.config['process_time_limit'] = process_time_limit # inject queues for webui for name in ('newtask_queue', 'status_queue', 'scheduler2fetcher', 'fetcher2processor', 'processor2result'): app.config['queues'][name] = getattr(g, name, None) # fetcher rpc if isinstance(fetcher_rpc, six.string_types): import umsgpack fetcher_rpc = connect_rpc(ctx, None, fetcher_rpc) app.config['fetch'] = lambda x: umsgpack.unpackb(fetcher_rpc.fetch(x).data) else: # get fetcher instance for webui fetcher_config = g.config.get('fetcher', {}) webui_fetcher = ctx.invoke(fetcher, async_mode=False, get_object=True, no_input=True, **fetcher_config) app.config['fetch'] = lambda x: webui_fetcher.fetch(x) if isinstance(scheduler_rpc, six.string_types): scheduler_rpc = connect_rpc(ctx, None, scheduler_rpc) if scheduler_rpc is None and os.environ.get('SCHEDULER_NAME'): app.config['scheduler_rpc'] = connect_rpc(ctx, None, 'http://%s/' % ( os.environ['SCHEDULER_PORT_23333_TCP'][len('tcp://'):])) elif scheduler_rpc is None: app.config['scheduler_rpc'] = connect_rpc(ctx, None, 'http://127.0.0.1:23333/') else: app.config['scheduler_rpc'] = scheduler_rpc app.debug = g.debug g.instances.append(app) if g.get('testing_mode') or get_object: return app app.run(host=host, port=port)
python
def webui(ctx, host, port, cdn, scheduler_rpc, fetcher_rpc, max_rate, max_burst, username, password, need_auth, webui_instance, process_time_limit, get_object=False): """ Run WebUI """ app = load_cls(None, None, webui_instance) g = ctx.obj app.config['taskdb'] = g.taskdb app.config['projectdb'] = g.projectdb app.config['resultdb'] = g.resultdb app.config['cdn'] = cdn if max_rate: app.config['max_rate'] = max_rate if max_burst: app.config['max_burst'] = max_burst if username: app.config['webui_username'] = username if password: app.config['webui_password'] = password app.config['need_auth'] = need_auth app.config['process_time_limit'] = process_time_limit # inject queues for webui for name in ('newtask_queue', 'status_queue', 'scheduler2fetcher', 'fetcher2processor', 'processor2result'): app.config['queues'][name] = getattr(g, name, None) # fetcher rpc if isinstance(fetcher_rpc, six.string_types): import umsgpack fetcher_rpc = connect_rpc(ctx, None, fetcher_rpc) app.config['fetch'] = lambda x: umsgpack.unpackb(fetcher_rpc.fetch(x).data) else: # get fetcher instance for webui fetcher_config = g.config.get('fetcher', {}) webui_fetcher = ctx.invoke(fetcher, async_mode=False, get_object=True, no_input=True, **fetcher_config) app.config['fetch'] = lambda x: webui_fetcher.fetch(x) if isinstance(scheduler_rpc, six.string_types): scheduler_rpc = connect_rpc(ctx, None, scheduler_rpc) if scheduler_rpc is None and os.environ.get('SCHEDULER_NAME'): app.config['scheduler_rpc'] = connect_rpc(ctx, None, 'http://%s/' % ( os.environ['SCHEDULER_PORT_23333_TCP'][len('tcp://'):])) elif scheduler_rpc is None: app.config['scheduler_rpc'] = connect_rpc(ctx, None, 'http://127.0.0.1:23333/') else: app.config['scheduler_rpc'] = scheduler_rpc app.debug = g.debug g.instances.append(app) if g.get('testing_mode') or get_object: return app app.run(host=host, port=port)
[ "def", "webui", "(", "ctx", ",", "host", ",", "port", ",", "cdn", ",", "scheduler_rpc", ",", "fetcher_rpc", ",", "max_rate", ",", "max_burst", ",", "username", ",", "password", ",", "need_auth", ",", "webui_instance", ",", "process_time_limit", ",", "get_object", "=", "False", ")", ":", "app", "=", "load_cls", "(", "None", ",", "None", ",", "webui_instance", ")", "g", "=", "ctx", ".", "obj", "app", ".", "config", "[", "'taskdb'", "]", "=", "g", ".", "taskdb", "app", ".", "config", "[", "'projectdb'", "]", "=", "g", ".", "projectdb", "app", ".", "config", "[", "'resultdb'", "]", "=", "g", ".", "resultdb", "app", ".", "config", "[", "'cdn'", "]", "=", "cdn", "if", "max_rate", ":", "app", ".", "config", "[", "'max_rate'", "]", "=", "max_rate", "if", "max_burst", ":", "app", ".", "config", "[", "'max_burst'", "]", "=", "max_burst", "if", "username", ":", "app", ".", "config", "[", "'webui_username'", "]", "=", "username", "if", "password", ":", "app", ".", "config", "[", "'webui_password'", "]", "=", "password", "app", ".", "config", "[", "'need_auth'", "]", "=", "need_auth", "app", ".", "config", "[", "'process_time_limit'", "]", "=", "process_time_limit", "# inject queues for webui", "for", "name", "in", "(", "'newtask_queue'", ",", "'status_queue'", ",", "'scheduler2fetcher'", ",", "'fetcher2processor'", ",", "'processor2result'", ")", ":", "app", ".", "config", "[", "'queues'", "]", "[", "name", "]", "=", "getattr", "(", "g", ",", "name", ",", "None", ")", "# fetcher rpc", "if", "isinstance", "(", "fetcher_rpc", ",", "six", ".", "string_types", ")", ":", "import", "umsgpack", "fetcher_rpc", "=", "connect_rpc", "(", "ctx", ",", "None", ",", "fetcher_rpc", ")", "app", ".", "config", "[", "'fetch'", "]", "=", "lambda", "x", ":", "umsgpack", ".", "unpackb", "(", "fetcher_rpc", ".", "fetch", "(", "x", ")", ".", "data", ")", "else", ":", "# get fetcher instance for webui", "fetcher_config", "=", "g", ".", "config", ".", "get", "(", "'fetcher'", ",", "{", "}", ")", "webui_fetcher", "=", "ctx", ".", "invoke", "(", "fetcher", ",", "async_mode", "=", "False", ",", "get_object", "=", "True", ",", "no_input", "=", "True", ",", "*", "*", "fetcher_config", ")", "app", ".", "config", "[", "'fetch'", "]", "=", "lambda", "x", ":", "webui_fetcher", ".", "fetch", "(", "x", ")", "if", "isinstance", "(", "scheduler_rpc", ",", "six", ".", "string_types", ")", ":", "scheduler_rpc", "=", "connect_rpc", "(", "ctx", ",", "None", ",", "scheduler_rpc", ")", "if", "scheduler_rpc", "is", "None", "and", "os", ".", "environ", ".", "get", "(", "'SCHEDULER_NAME'", ")", ":", "app", ".", "config", "[", "'scheduler_rpc'", "]", "=", "connect_rpc", "(", "ctx", ",", "None", ",", "'http://%s/'", "%", "(", "os", ".", "environ", "[", "'SCHEDULER_PORT_23333_TCP'", "]", "[", "len", "(", "'tcp://'", ")", ":", "]", ")", ")", "elif", "scheduler_rpc", "is", "None", ":", "app", ".", "config", "[", "'scheduler_rpc'", "]", "=", "connect_rpc", "(", "ctx", ",", "None", ",", "'http://127.0.0.1:23333/'", ")", "else", ":", "app", ".", "config", "[", "'scheduler_rpc'", "]", "=", "scheduler_rpc", "app", ".", "debug", "=", "g", ".", "debug", "g", ".", "instances", ".", "append", "(", "app", ")", "if", "g", ".", "get", "(", "'testing_mode'", ")", "or", "get_object", ":", "return", "app", "app", ".", "run", "(", "host", "=", "host", ",", "port", "=", "port", ")" ]
Run WebUI
[ "Run", "WebUI" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L337-L393
train
binux/pyspider
pyspider/run.py
phantomjs
def phantomjs(ctx, phantomjs_path, port, auto_restart, args): """ Run phantomjs fetcher if phantomjs is installed. """ args = args or ctx.default_map and ctx.default_map.get('args', []) import subprocess g = ctx.obj _quit = [] phantomjs_fetcher = os.path.join( os.path.dirname(pyspider.__file__), 'fetcher/phantomjs_fetcher.js') cmd = [phantomjs_path, # this may cause memory leak: https://github.com/ariya/phantomjs/issues/12903 #'--load-images=false', '--ssl-protocol=any', '--disk-cache=true'] + list(args or []) + [phantomjs_fetcher, str(port)] try: _phantomjs = subprocess.Popen(cmd) except OSError: logging.warning('phantomjs not found, continue running without it.') return None def quit(*args, **kwargs): _quit.append(1) _phantomjs.kill() _phantomjs.wait() logging.info('phantomjs exited.') if not g.get('phantomjs_proxy'): g['phantomjs_proxy'] = '127.0.0.1:%s' % port phantomjs = utils.ObjectDict(port=port, quit=quit) g.instances.append(phantomjs) if g.get('testing_mode'): return phantomjs while True: _phantomjs.wait() if _quit or not auto_restart: break _phantomjs = subprocess.Popen(cmd)
python
def phantomjs(ctx, phantomjs_path, port, auto_restart, args): """ Run phantomjs fetcher if phantomjs is installed. """ args = args or ctx.default_map and ctx.default_map.get('args', []) import subprocess g = ctx.obj _quit = [] phantomjs_fetcher = os.path.join( os.path.dirname(pyspider.__file__), 'fetcher/phantomjs_fetcher.js') cmd = [phantomjs_path, # this may cause memory leak: https://github.com/ariya/phantomjs/issues/12903 #'--load-images=false', '--ssl-protocol=any', '--disk-cache=true'] + list(args or []) + [phantomjs_fetcher, str(port)] try: _phantomjs = subprocess.Popen(cmd) except OSError: logging.warning('phantomjs not found, continue running without it.') return None def quit(*args, **kwargs): _quit.append(1) _phantomjs.kill() _phantomjs.wait() logging.info('phantomjs exited.') if not g.get('phantomjs_proxy'): g['phantomjs_proxy'] = '127.0.0.1:%s' % port phantomjs = utils.ObjectDict(port=port, quit=quit) g.instances.append(phantomjs) if g.get('testing_mode'): return phantomjs while True: _phantomjs.wait() if _quit or not auto_restart: break _phantomjs = subprocess.Popen(cmd)
[ "def", "phantomjs", "(", "ctx", ",", "phantomjs_path", ",", "port", ",", "auto_restart", ",", "args", ")", ":", "args", "=", "args", "or", "ctx", ".", "default_map", "and", "ctx", ".", "default_map", ".", "get", "(", "'args'", ",", "[", "]", ")", "import", "subprocess", "g", "=", "ctx", ".", "obj", "_quit", "=", "[", "]", "phantomjs_fetcher", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "pyspider", ".", "__file__", ")", ",", "'fetcher/phantomjs_fetcher.js'", ")", "cmd", "=", "[", "phantomjs_path", ",", "# this may cause memory leak: https://github.com/ariya/phantomjs/issues/12903", "#'--load-images=false',", "'--ssl-protocol=any'", ",", "'--disk-cache=true'", "]", "+", "list", "(", "args", "or", "[", "]", ")", "+", "[", "phantomjs_fetcher", ",", "str", "(", "port", ")", "]", "try", ":", "_phantomjs", "=", "subprocess", ".", "Popen", "(", "cmd", ")", "except", "OSError", ":", "logging", ".", "warning", "(", "'phantomjs not found, continue running without it.'", ")", "return", "None", "def", "quit", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_quit", ".", "append", "(", "1", ")", "_phantomjs", ".", "kill", "(", ")", "_phantomjs", ".", "wait", "(", ")", "logging", ".", "info", "(", "'phantomjs exited.'", ")", "if", "not", "g", ".", "get", "(", "'phantomjs_proxy'", ")", ":", "g", "[", "'phantomjs_proxy'", "]", "=", "'127.0.0.1:%s'", "%", "port", "phantomjs", "=", "utils", ".", "ObjectDict", "(", "port", "=", "port", ",", "quit", "=", "quit", ")", "g", ".", "instances", ".", "append", "(", "phantomjs", ")", "if", "g", ".", "get", "(", "'testing_mode'", ")", ":", "return", "phantomjs", "while", "True", ":", "_phantomjs", ".", "wait", "(", ")", "if", "_quit", "or", "not", "auto_restart", ":", "break", "_phantomjs", "=", "subprocess", ".", "Popen", "(", "cmd", ")" ]
Run phantomjs fetcher if phantomjs is installed.
[ "Run", "phantomjs", "fetcher", "if", "phantomjs", "is", "installed", "." ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L402-L443
train
binux/pyspider
pyspider/run.py
puppeteer
def puppeteer(ctx, port, auto_restart, args): """ Run puppeteer fetcher if puppeteer is installed. """ import subprocess g = ctx.obj _quit = [] puppeteer_fetcher = os.path.join( os.path.dirname(pyspider.__file__), 'fetcher/puppeteer_fetcher.js') cmd = ['node', puppeteer_fetcher, str(port)] try: _puppeteer = subprocess.Popen(cmd) except OSError: logging.warning('puppeteer not found, continue running without it.') return None def quit(*args, **kwargs): _quit.append(1) _puppeteer.kill() _puppeteer.wait() logging.info('puppeteer exited.') if not g.get('puppeteer_proxy'): g['puppeteer_proxy'] = '127.0.0.1:%s' % port puppeteer = utils.ObjectDict(port=port, quit=quit) g.instances.append(puppeteer) if g.get('testing_mode'): return puppeteer while True: _puppeteer.wait() if _quit or not auto_restart: break _puppeteer = subprocess.Popen(cmd)
python
def puppeteer(ctx, port, auto_restart, args): """ Run puppeteer fetcher if puppeteer is installed. """ import subprocess g = ctx.obj _quit = [] puppeteer_fetcher = os.path.join( os.path.dirname(pyspider.__file__), 'fetcher/puppeteer_fetcher.js') cmd = ['node', puppeteer_fetcher, str(port)] try: _puppeteer = subprocess.Popen(cmd) except OSError: logging.warning('puppeteer not found, continue running without it.') return None def quit(*args, **kwargs): _quit.append(1) _puppeteer.kill() _puppeteer.wait() logging.info('puppeteer exited.') if not g.get('puppeteer_proxy'): g['puppeteer_proxy'] = '127.0.0.1:%s' % port puppeteer = utils.ObjectDict(port=port, quit=quit) g.instances.append(puppeteer) if g.get('testing_mode'): return puppeteer while True: _puppeteer.wait() if _quit or not auto_restart: break _puppeteer = subprocess.Popen(cmd)
[ "def", "puppeteer", "(", "ctx", ",", "port", ",", "auto_restart", ",", "args", ")", ":", "import", "subprocess", "g", "=", "ctx", ".", "obj", "_quit", "=", "[", "]", "puppeteer_fetcher", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "pyspider", ".", "__file__", ")", ",", "'fetcher/puppeteer_fetcher.js'", ")", "cmd", "=", "[", "'node'", ",", "puppeteer_fetcher", ",", "str", "(", "port", ")", "]", "try", ":", "_puppeteer", "=", "subprocess", ".", "Popen", "(", "cmd", ")", "except", "OSError", ":", "logging", ".", "warning", "(", "'puppeteer not found, continue running without it.'", ")", "return", "None", "def", "quit", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_quit", ".", "append", "(", "1", ")", "_puppeteer", ".", "kill", "(", ")", "_puppeteer", ".", "wait", "(", ")", "logging", ".", "info", "(", "'puppeteer exited.'", ")", "if", "not", "g", ".", "get", "(", "'puppeteer_proxy'", ")", ":", "g", "[", "'puppeteer_proxy'", "]", "=", "'127.0.0.1:%s'", "%", "port", "puppeteer", "=", "utils", ".", "ObjectDict", "(", "port", "=", "port", ",", "quit", "=", "quit", ")", "g", ".", "instances", ".", "append", "(", "puppeteer", ")", "if", "g", ".", "get", "(", "'testing_mode'", ")", ":", "return", "puppeteer", "while", "True", ":", "_puppeteer", ".", "wait", "(", ")", "if", "_quit", "or", "not", "auto_restart", ":", "break", "_puppeteer", "=", "subprocess", ".", "Popen", "(", "cmd", ")" ]
Run puppeteer fetcher if puppeteer is installed.
[ "Run", "puppeteer", "fetcher", "if", "puppeteer", "is", "installed", "." ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L450-L486
train
binux/pyspider
pyspider/run.py
all
def all(ctx, fetcher_num, processor_num, result_worker_num, run_in): """ Run all the components in subprocess or thread """ ctx.obj['debug'] = False g = ctx.obj # FIXME: py34 cannot run components with threads if run_in == 'subprocess' and os.name != 'nt': run_in = utils.run_in_subprocess else: run_in = utils.run_in_thread threads = [] try: # phantomjs if not g.get('phantomjs_proxy'): phantomjs_config = g.config.get('phantomjs', {}) phantomjs_config.setdefault('auto_restart', True) threads.append(run_in(ctx.invoke, phantomjs, **phantomjs_config)) time.sleep(2) if threads[-1].is_alive() and not g.get('phantomjs_proxy'): g['phantomjs_proxy'] = '127.0.0.1:%s' % phantomjs_config.get('port', 25555) # puppeteer if not g.get('puppeteer_proxy'): puppeteer_config = g.config.get('puppeteer', {}) puppeteer_config.setdefault('auto_restart', True) threads.append(run_in(ctx.invoke, puppeteer, **puppeteer_config)) time.sleep(2) if threads[-1].is_alive() and not g.get('puppeteer_proxy'): g['puppeteer_proxy'] = '127.0.0.1:%s' % puppeteer_config.get('port', 22222) # result worker result_worker_config = g.config.get('result_worker', {}) for i in range(result_worker_num): threads.append(run_in(ctx.invoke, result_worker, **result_worker_config)) # processor processor_config = g.config.get('processor', {}) for i in range(processor_num): threads.append(run_in(ctx.invoke, processor, **processor_config)) # fetcher fetcher_config = g.config.get('fetcher', {}) fetcher_config.setdefault('xmlrpc_host', '127.0.0.1') for i in range(fetcher_num): threads.append(run_in(ctx.invoke, fetcher, **fetcher_config)) # scheduler scheduler_config = g.config.get('scheduler', {}) scheduler_config.setdefault('xmlrpc_host', '127.0.0.1') threads.append(run_in(ctx.invoke, scheduler, **scheduler_config)) # running webui in main thread to make it exitable webui_config = g.config.get('webui', {}) webui_config.setdefault('scheduler_rpc', 'http://127.0.0.1:%s/' % g.config.get('scheduler', {}).get('xmlrpc_port', 23333)) ctx.invoke(webui, **webui_config) finally: # exit components run in threading for each in g.instances: each.quit() # exit components run in subprocess for each in threads: if not each.is_alive(): continue if hasattr(each, 'terminate'): each.terminate() each.join()
python
def all(ctx, fetcher_num, processor_num, result_worker_num, run_in): """ Run all the components in subprocess or thread """ ctx.obj['debug'] = False g = ctx.obj # FIXME: py34 cannot run components with threads if run_in == 'subprocess' and os.name != 'nt': run_in = utils.run_in_subprocess else: run_in = utils.run_in_thread threads = [] try: # phantomjs if not g.get('phantomjs_proxy'): phantomjs_config = g.config.get('phantomjs', {}) phantomjs_config.setdefault('auto_restart', True) threads.append(run_in(ctx.invoke, phantomjs, **phantomjs_config)) time.sleep(2) if threads[-1].is_alive() and not g.get('phantomjs_proxy'): g['phantomjs_proxy'] = '127.0.0.1:%s' % phantomjs_config.get('port', 25555) # puppeteer if not g.get('puppeteer_proxy'): puppeteer_config = g.config.get('puppeteer', {}) puppeteer_config.setdefault('auto_restart', True) threads.append(run_in(ctx.invoke, puppeteer, **puppeteer_config)) time.sleep(2) if threads[-1].is_alive() and not g.get('puppeteer_proxy'): g['puppeteer_proxy'] = '127.0.0.1:%s' % puppeteer_config.get('port', 22222) # result worker result_worker_config = g.config.get('result_worker', {}) for i in range(result_worker_num): threads.append(run_in(ctx.invoke, result_worker, **result_worker_config)) # processor processor_config = g.config.get('processor', {}) for i in range(processor_num): threads.append(run_in(ctx.invoke, processor, **processor_config)) # fetcher fetcher_config = g.config.get('fetcher', {}) fetcher_config.setdefault('xmlrpc_host', '127.0.0.1') for i in range(fetcher_num): threads.append(run_in(ctx.invoke, fetcher, **fetcher_config)) # scheduler scheduler_config = g.config.get('scheduler', {}) scheduler_config.setdefault('xmlrpc_host', '127.0.0.1') threads.append(run_in(ctx.invoke, scheduler, **scheduler_config)) # running webui in main thread to make it exitable webui_config = g.config.get('webui', {}) webui_config.setdefault('scheduler_rpc', 'http://127.0.0.1:%s/' % g.config.get('scheduler', {}).get('xmlrpc_port', 23333)) ctx.invoke(webui, **webui_config) finally: # exit components run in threading for each in g.instances: each.quit() # exit components run in subprocess for each in threads: if not each.is_alive(): continue if hasattr(each, 'terminate'): each.terminate() each.join()
[ "def", "all", "(", "ctx", ",", "fetcher_num", ",", "processor_num", ",", "result_worker_num", ",", "run_in", ")", ":", "ctx", ".", "obj", "[", "'debug'", "]", "=", "False", "g", "=", "ctx", ".", "obj", "# FIXME: py34 cannot run components with threads", "if", "run_in", "==", "'subprocess'", "and", "os", ".", "name", "!=", "'nt'", ":", "run_in", "=", "utils", ".", "run_in_subprocess", "else", ":", "run_in", "=", "utils", ".", "run_in_thread", "threads", "=", "[", "]", "try", ":", "# phantomjs", "if", "not", "g", ".", "get", "(", "'phantomjs_proxy'", ")", ":", "phantomjs_config", "=", "g", ".", "config", ".", "get", "(", "'phantomjs'", ",", "{", "}", ")", "phantomjs_config", ".", "setdefault", "(", "'auto_restart'", ",", "True", ")", "threads", ".", "append", "(", "run_in", "(", "ctx", ".", "invoke", ",", "phantomjs", ",", "*", "*", "phantomjs_config", ")", ")", "time", ".", "sleep", "(", "2", ")", "if", "threads", "[", "-", "1", "]", ".", "is_alive", "(", ")", "and", "not", "g", ".", "get", "(", "'phantomjs_proxy'", ")", ":", "g", "[", "'phantomjs_proxy'", "]", "=", "'127.0.0.1:%s'", "%", "phantomjs_config", ".", "get", "(", "'port'", ",", "25555", ")", "# puppeteer", "if", "not", "g", ".", "get", "(", "'puppeteer_proxy'", ")", ":", "puppeteer_config", "=", "g", ".", "config", ".", "get", "(", "'puppeteer'", ",", "{", "}", ")", "puppeteer_config", ".", "setdefault", "(", "'auto_restart'", ",", "True", ")", "threads", ".", "append", "(", "run_in", "(", "ctx", ".", "invoke", ",", "puppeteer", ",", "*", "*", "puppeteer_config", ")", ")", "time", ".", "sleep", "(", "2", ")", "if", "threads", "[", "-", "1", "]", ".", "is_alive", "(", ")", "and", "not", "g", ".", "get", "(", "'puppeteer_proxy'", ")", ":", "g", "[", "'puppeteer_proxy'", "]", "=", "'127.0.0.1:%s'", "%", "puppeteer_config", ".", "get", "(", "'port'", ",", "22222", ")", "# result worker", "result_worker_config", "=", "g", ".", "config", ".", "get", "(", "'result_worker'", ",", "{", "}", ")", "for", "i", "in", "range", "(", "result_worker_num", ")", ":", "threads", ".", "append", "(", "run_in", "(", "ctx", ".", "invoke", ",", "result_worker", ",", "*", "*", "result_worker_config", ")", ")", "# processor", "processor_config", "=", "g", ".", "config", ".", "get", "(", "'processor'", ",", "{", "}", ")", "for", "i", "in", "range", "(", "processor_num", ")", ":", "threads", ".", "append", "(", "run_in", "(", "ctx", ".", "invoke", ",", "processor", ",", "*", "*", "processor_config", ")", ")", "# fetcher", "fetcher_config", "=", "g", ".", "config", ".", "get", "(", "'fetcher'", ",", "{", "}", ")", "fetcher_config", ".", "setdefault", "(", "'xmlrpc_host'", ",", "'127.0.0.1'", ")", "for", "i", "in", "range", "(", "fetcher_num", ")", ":", "threads", ".", "append", "(", "run_in", "(", "ctx", ".", "invoke", ",", "fetcher", ",", "*", "*", "fetcher_config", ")", ")", "# scheduler", "scheduler_config", "=", "g", ".", "config", ".", "get", "(", "'scheduler'", ",", "{", "}", ")", "scheduler_config", ".", "setdefault", "(", "'xmlrpc_host'", ",", "'127.0.0.1'", ")", "threads", ".", "append", "(", "run_in", "(", "ctx", ".", "invoke", ",", "scheduler", ",", "*", "*", "scheduler_config", ")", ")", "# running webui in main thread to make it exitable", "webui_config", "=", "g", ".", "config", ".", "get", "(", "'webui'", ",", "{", "}", ")", "webui_config", ".", "setdefault", "(", "'scheduler_rpc'", ",", "'http://127.0.0.1:%s/'", "%", "g", ".", "config", ".", "get", "(", "'scheduler'", ",", "{", "}", ")", ".", "get", "(", "'xmlrpc_port'", ",", "23333", ")", ")", "ctx", ".", "invoke", "(", "webui", ",", "*", "*", "webui_config", ")", "finally", ":", "# exit components run in threading", "for", "each", "in", "g", ".", "instances", ":", "each", ".", "quit", "(", ")", "# exit components run in subprocess", "for", "each", "in", "threads", ":", "if", "not", "each", ".", "is_alive", "(", ")", ":", "continue", "if", "hasattr", "(", "each", ",", "'terminate'", ")", ":", "each", ".", "terminate", "(", ")", "each", ".", "join", "(", ")" ]
Run all the components in subprocess or thread
[ "Run", "all", "the", "components", "in", "subprocess", "or", "thread" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L498-L570
train
binux/pyspider
pyspider/run.py
bench
def bench(ctx, fetcher_num, processor_num, result_worker_num, run_in, total, show, taskdb_bench, message_queue_bench, all_bench): """ Run Benchmark test. In bench mode, in-memory sqlite database is used instead of on-disk sqlite database. """ from pyspider.libs import bench from pyspider.webui import bench_test # flake8: noqa ctx.obj['debug'] = False g = ctx.obj if result_worker_num == 0: g['processor2result'] = None if run_in == 'subprocess' and os.name != 'nt': run_in = utils.run_in_subprocess else: run_in = utils.run_in_thread all_test = not taskdb_bench and not message_queue_bench and not all_bench # test taskdb if all_test or taskdb_bench: bench.bench_test_taskdb(g.taskdb) # test message queue if all_test or message_queue_bench: bench.bench_test_message_queue(g.scheduler2fetcher) # test all if not all_test and not all_bench: return project_name = 'bench' def clear_project(): g.taskdb.drop(project_name) g.resultdb.drop(project_name) clear_project() # disable log logging.getLogger().setLevel(logging.ERROR) logging.getLogger('scheduler').setLevel(logging.ERROR) logging.getLogger('fetcher').setLevel(logging.ERROR) logging.getLogger('processor').setLevel(logging.ERROR) logging.getLogger('result').setLevel(logging.ERROR) logging.getLogger('webui').setLevel(logging.ERROR) logging.getLogger('werkzeug').setLevel(logging.ERROR) try: threads = [] # result worker result_worker_config = g.config.get('result_worker', {}) for i in range(result_worker_num): threads.append(run_in(ctx.invoke, result_worker, result_cls='pyspider.libs.bench.BenchResultWorker', **result_worker_config)) # processor processor_config = g.config.get('processor', {}) for i in range(processor_num): threads.append(run_in(ctx.invoke, processor, processor_cls='pyspider.libs.bench.BenchProcessor', **processor_config)) # fetcher fetcher_config = g.config.get('fetcher', {}) fetcher_config.setdefault('xmlrpc_host', '127.0.0.1') for i in range(fetcher_num): threads.append(run_in(ctx.invoke, fetcher, fetcher_cls='pyspider.libs.bench.BenchFetcher', **fetcher_config)) # webui webui_config = g.config.get('webui', {}) webui_config.setdefault('scheduler_rpc', 'http://127.0.0.1:%s/' % g.config.get('scheduler', {}).get('xmlrpc_port', 23333)) threads.append(run_in(ctx.invoke, webui, **webui_config)) # scheduler scheduler_config = g.config.get('scheduler', {}) scheduler_config.setdefault('xmlrpc_host', '127.0.0.1') scheduler_config.setdefault('xmlrpc_port', 23333) threads.append(run_in(ctx.invoke, scheduler, scheduler_cls='pyspider.libs.bench.BenchScheduler', **scheduler_config)) scheduler_rpc = connect_rpc(ctx, None, 'http://%(xmlrpc_host)s:%(xmlrpc_port)s/' % scheduler_config) for _ in range(20): if utils.check_port_open(23333): break time.sleep(1) scheduler_rpc.newtask({ "project": project_name, "taskid": "on_start", "url": "data:,on_start", "fetch": { "save": {"total": total, "show": show} }, "process": { "callback": "on_start", }, }) # wait bench test finished while True: time.sleep(1) if scheduler_rpc.size() == 0: break finally: # exit components run in threading for each in g.instances: each.quit() # exit components run in subprocess for each in threads: if hasattr(each, 'terminate'): each.terminate() each.join(1) clear_project()
python
def bench(ctx, fetcher_num, processor_num, result_worker_num, run_in, total, show, taskdb_bench, message_queue_bench, all_bench): """ Run Benchmark test. In bench mode, in-memory sqlite database is used instead of on-disk sqlite database. """ from pyspider.libs import bench from pyspider.webui import bench_test # flake8: noqa ctx.obj['debug'] = False g = ctx.obj if result_worker_num == 0: g['processor2result'] = None if run_in == 'subprocess' and os.name != 'nt': run_in = utils.run_in_subprocess else: run_in = utils.run_in_thread all_test = not taskdb_bench and not message_queue_bench and not all_bench # test taskdb if all_test or taskdb_bench: bench.bench_test_taskdb(g.taskdb) # test message queue if all_test or message_queue_bench: bench.bench_test_message_queue(g.scheduler2fetcher) # test all if not all_test and not all_bench: return project_name = 'bench' def clear_project(): g.taskdb.drop(project_name) g.resultdb.drop(project_name) clear_project() # disable log logging.getLogger().setLevel(logging.ERROR) logging.getLogger('scheduler').setLevel(logging.ERROR) logging.getLogger('fetcher').setLevel(logging.ERROR) logging.getLogger('processor').setLevel(logging.ERROR) logging.getLogger('result').setLevel(logging.ERROR) logging.getLogger('webui').setLevel(logging.ERROR) logging.getLogger('werkzeug').setLevel(logging.ERROR) try: threads = [] # result worker result_worker_config = g.config.get('result_worker', {}) for i in range(result_worker_num): threads.append(run_in(ctx.invoke, result_worker, result_cls='pyspider.libs.bench.BenchResultWorker', **result_worker_config)) # processor processor_config = g.config.get('processor', {}) for i in range(processor_num): threads.append(run_in(ctx.invoke, processor, processor_cls='pyspider.libs.bench.BenchProcessor', **processor_config)) # fetcher fetcher_config = g.config.get('fetcher', {}) fetcher_config.setdefault('xmlrpc_host', '127.0.0.1') for i in range(fetcher_num): threads.append(run_in(ctx.invoke, fetcher, fetcher_cls='pyspider.libs.bench.BenchFetcher', **fetcher_config)) # webui webui_config = g.config.get('webui', {}) webui_config.setdefault('scheduler_rpc', 'http://127.0.0.1:%s/' % g.config.get('scheduler', {}).get('xmlrpc_port', 23333)) threads.append(run_in(ctx.invoke, webui, **webui_config)) # scheduler scheduler_config = g.config.get('scheduler', {}) scheduler_config.setdefault('xmlrpc_host', '127.0.0.1') scheduler_config.setdefault('xmlrpc_port', 23333) threads.append(run_in(ctx.invoke, scheduler, scheduler_cls='pyspider.libs.bench.BenchScheduler', **scheduler_config)) scheduler_rpc = connect_rpc(ctx, None, 'http://%(xmlrpc_host)s:%(xmlrpc_port)s/' % scheduler_config) for _ in range(20): if utils.check_port_open(23333): break time.sleep(1) scheduler_rpc.newtask({ "project": project_name, "taskid": "on_start", "url": "data:,on_start", "fetch": { "save": {"total": total, "show": show} }, "process": { "callback": "on_start", }, }) # wait bench test finished while True: time.sleep(1) if scheduler_rpc.size() == 0: break finally: # exit components run in threading for each in g.instances: each.quit() # exit components run in subprocess for each in threads: if hasattr(each, 'terminate'): each.terminate() each.join(1) clear_project()
[ "def", "bench", "(", "ctx", ",", "fetcher_num", ",", "processor_num", ",", "result_worker_num", ",", "run_in", ",", "total", ",", "show", ",", "taskdb_bench", ",", "message_queue_bench", ",", "all_bench", ")", ":", "from", "pyspider", ".", "libs", "import", "bench", "from", "pyspider", ".", "webui", "import", "bench_test", "# flake8: noqa", "ctx", ".", "obj", "[", "'debug'", "]", "=", "False", "g", "=", "ctx", ".", "obj", "if", "result_worker_num", "==", "0", ":", "g", "[", "'processor2result'", "]", "=", "None", "if", "run_in", "==", "'subprocess'", "and", "os", ".", "name", "!=", "'nt'", ":", "run_in", "=", "utils", ".", "run_in_subprocess", "else", ":", "run_in", "=", "utils", ".", "run_in_thread", "all_test", "=", "not", "taskdb_bench", "and", "not", "message_queue_bench", "and", "not", "all_bench", "# test taskdb", "if", "all_test", "or", "taskdb_bench", ":", "bench", ".", "bench_test_taskdb", "(", "g", ".", "taskdb", ")", "# test message queue", "if", "all_test", "or", "message_queue_bench", ":", "bench", ".", "bench_test_message_queue", "(", "g", ".", "scheduler2fetcher", ")", "# test all", "if", "not", "all_test", "and", "not", "all_bench", ":", "return", "project_name", "=", "'bench'", "def", "clear_project", "(", ")", ":", "g", ".", "taskdb", ".", "drop", "(", "project_name", ")", "g", ".", "resultdb", ".", "drop", "(", "project_name", ")", "clear_project", "(", ")", "# disable log", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "logging", ".", "getLogger", "(", "'scheduler'", ")", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "logging", ".", "getLogger", "(", "'fetcher'", ")", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "logging", ".", "getLogger", "(", "'processor'", ")", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "logging", ".", "getLogger", "(", "'result'", ")", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "logging", ".", "getLogger", "(", "'webui'", ")", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "logging", ".", "getLogger", "(", "'werkzeug'", ")", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "try", ":", "threads", "=", "[", "]", "# result worker", "result_worker_config", "=", "g", ".", "config", ".", "get", "(", "'result_worker'", ",", "{", "}", ")", "for", "i", "in", "range", "(", "result_worker_num", ")", ":", "threads", ".", "append", "(", "run_in", "(", "ctx", ".", "invoke", ",", "result_worker", ",", "result_cls", "=", "'pyspider.libs.bench.BenchResultWorker'", ",", "*", "*", "result_worker_config", ")", ")", "# processor", "processor_config", "=", "g", ".", "config", ".", "get", "(", "'processor'", ",", "{", "}", ")", "for", "i", "in", "range", "(", "processor_num", ")", ":", "threads", ".", "append", "(", "run_in", "(", "ctx", ".", "invoke", ",", "processor", ",", "processor_cls", "=", "'pyspider.libs.bench.BenchProcessor'", ",", "*", "*", "processor_config", ")", ")", "# fetcher", "fetcher_config", "=", "g", ".", "config", ".", "get", "(", "'fetcher'", ",", "{", "}", ")", "fetcher_config", ".", "setdefault", "(", "'xmlrpc_host'", ",", "'127.0.0.1'", ")", "for", "i", "in", "range", "(", "fetcher_num", ")", ":", "threads", ".", "append", "(", "run_in", "(", "ctx", ".", "invoke", ",", "fetcher", ",", "fetcher_cls", "=", "'pyspider.libs.bench.BenchFetcher'", ",", "*", "*", "fetcher_config", ")", ")", "# webui", "webui_config", "=", "g", ".", "config", ".", "get", "(", "'webui'", ",", "{", "}", ")", "webui_config", ".", "setdefault", "(", "'scheduler_rpc'", ",", "'http://127.0.0.1:%s/'", "%", "g", ".", "config", ".", "get", "(", "'scheduler'", ",", "{", "}", ")", ".", "get", "(", "'xmlrpc_port'", ",", "23333", ")", ")", "threads", ".", "append", "(", "run_in", "(", "ctx", ".", "invoke", ",", "webui", ",", "*", "*", "webui_config", ")", ")", "# scheduler", "scheduler_config", "=", "g", ".", "config", ".", "get", "(", "'scheduler'", ",", "{", "}", ")", "scheduler_config", ".", "setdefault", "(", "'xmlrpc_host'", ",", "'127.0.0.1'", ")", "scheduler_config", ".", "setdefault", "(", "'xmlrpc_port'", ",", "23333", ")", "threads", ".", "append", "(", "run_in", "(", "ctx", ".", "invoke", ",", "scheduler", ",", "scheduler_cls", "=", "'pyspider.libs.bench.BenchScheduler'", ",", "*", "*", "scheduler_config", ")", ")", "scheduler_rpc", "=", "connect_rpc", "(", "ctx", ",", "None", ",", "'http://%(xmlrpc_host)s:%(xmlrpc_port)s/'", "%", "scheduler_config", ")", "for", "_", "in", "range", "(", "20", ")", ":", "if", "utils", ".", "check_port_open", "(", "23333", ")", ":", "break", "time", ".", "sleep", "(", "1", ")", "scheduler_rpc", ".", "newtask", "(", "{", "\"project\"", ":", "project_name", ",", "\"taskid\"", ":", "\"on_start\"", ",", "\"url\"", ":", "\"data:,on_start\"", ",", "\"fetch\"", ":", "{", "\"save\"", ":", "{", "\"total\"", ":", "total", ",", "\"show\"", ":", "show", "}", "}", ",", "\"process\"", ":", "{", "\"callback\"", ":", "\"on_start\"", ",", "}", ",", "}", ")", "# wait bench test finished", "while", "True", ":", "time", ".", "sleep", "(", "1", ")", "if", "scheduler_rpc", ".", "size", "(", ")", "==", "0", ":", "break", "finally", ":", "# exit components run in threading", "for", "each", "in", "g", ".", "instances", ":", "each", ".", "quit", "(", ")", "# exit components run in subprocess", "for", "each", "in", "threads", ":", "if", "hasattr", "(", "each", ",", "'terminate'", ")", ":", "each", ".", "terminate", "(", ")", "each", ".", "join", "(", "1", ")", "clear_project", "(", ")" ]
Run Benchmark test. In bench mode, in-memory sqlite database is used instead of on-disk sqlite database.
[ "Run", "Benchmark", "test", ".", "In", "bench", "mode", "in", "-", "memory", "sqlite", "database", "is", "used", "instead", "of", "on", "-", "disk", "sqlite", "database", "." ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L589-L711
train
binux/pyspider
pyspider/run.py
one
def one(ctx, interactive, enable_phantomjs, enable_puppeteer, scripts): """ One mode not only means all-in-one, it runs every thing in one process over tornado.ioloop, for debug purpose """ ctx.obj['debug'] = False g = ctx.obj g['testing_mode'] = True if scripts: from pyspider.database.local.projectdb import ProjectDB g['projectdb'] = ProjectDB(scripts) if g.get('is_taskdb_default'): g['taskdb'] = connect_database('sqlite+taskdb://') if g.get('is_resultdb_default'): g['resultdb'] = None if enable_phantomjs: phantomjs_config = g.config.get('phantomjs', {}) phantomjs_obj = ctx.invoke(phantomjs, **phantomjs_config) if phantomjs_obj: g.setdefault('phantomjs_proxy', '127.0.0.1:%s' % phantomjs_obj.port) else: phantomjs_obj = None if enable_puppeteer: puppeteer_config = g.config.get('puppeteer', {}) puppeteer_obj = ctx.invoke(puppeteer, **puppeteer_config) if puppeteer_obj: g.setdefault('puppeteer_proxy', '127.0.0.1:%s' % puppeteer.port) else: puppeteer_obj = None result_worker_config = g.config.get('result_worker', {}) if g.resultdb is None: result_worker_config.setdefault('result_cls', 'pyspider.result.OneResultWorker') result_worker_obj = ctx.invoke(result_worker, **result_worker_config) processor_config = g.config.get('processor', {}) processor_config.setdefault('enable_stdout_capture', False) processor_obj = ctx.invoke(processor, **processor_config) fetcher_config = g.config.get('fetcher', {}) fetcher_config.setdefault('xmlrpc', False) fetcher_obj = ctx.invoke(fetcher, **fetcher_config) scheduler_config = g.config.get('scheduler', {}) scheduler_config.setdefault('xmlrpc', False) scheduler_config.setdefault('scheduler_cls', 'pyspider.scheduler.OneScheduler') scheduler_obj = ctx.invoke(scheduler, **scheduler_config) scheduler_obj.init_one(ioloop=fetcher_obj.ioloop, fetcher=fetcher_obj, processor=processor_obj, result_worker=result_worker_obj, interactive=interactive) if scripts: for project in g.projectdb.projects: scheduler_obj.trigger_on_start(project) try: scheduler_obj.run() finally: scheduler_obj.quit() if phantomjs_obj: phantomjs_obj.quit() if puppeteer_obj: puppeteer_obj.quit()
python
def one(ctx, interactive, enable_phantomjs, enable_puppeteer, scripts): """ One mode not only means all-in-one, it runs every thing in one process over tornado.ioloop, for debug purpose """ ctx.obj['debug'] = False g = ctx.obj g['testing_mode'] = True if scripts: from pyspider.database.local.projectdb import ProjectDB g['projectdb'] = ProjectDB(scripts) if g.get('is_taskdb_default'): g['taskdb'] = connect_database('sqlite+taskdb://') if g.get('is_resultdb_default'): g['resultdb'] = None if enable_phantomjs: phantomjs_config = g.config.get('phantomjs', {}) phantomjs_obj = ctx.invoke(phantomjs, **phantomjs_config) if phantomjs_obj: g.setdefault('phantomjs_proxy', '127.0.0.1:%s' % phantomjs_obj.port) else: phantomjs_obj = None if enable_puppeteer: puppeteer_config = g.config.get('puppeteer', {}) puppeteer_obj = ctx.invoke(puppeteer, **puppeteer_config) if puppeteer_obj: g.setdefault('puppeteer_proxy', '127.0.0.1:%s' % puppeteer.port) else: puppeteer_obj = None result_worker_config = g.config.get('result_worker', {}) if g.resultdb is None: result_worker_config.setdefault('result_cls', 'pyspider.result.OneResultWorker') result_worker_obj = ctx.invoke(result_worker, **result_worker_config) processor_config = g.config.get('processor', {}) processor_config.setdefault('enable_stdout_capture', False) processor_obj = ctx.invoke(processor, **processor_config) fetcher_config = g.config.get('fetcher', {}) fetcher_config.setdefault('xmlrpc', False) fetcher_obj = ctx.invoke(fetcher, **fetcher_config) scheduler_config = g.config.get('scheduler', {}) scheduler_config.setdefault('xmlrpc', False) scheduler_config.setdefault('scheduler_cls', 'pyspider.scheduler.OneScheduler') scheduler_obj = ctx.invoke(scheduler, **scheduler_config) scheduler_obj.init_one(ioloop=fetcher_obj.ioloop, fetcher=fetcher_obj, processor=processor_obj, result_worker=result_worker_obj, interactive=interactive) if scripts: for project in g.projectdb.projects: scheduler_obj.trigger_on_start(project) try: scheduler_obj.run() finally: scheduler_obj.quit() if phantomjs_obj: phantomjs_obj.quit() if puppeteer_obj: puppeteer_obj.quit()
[ "def", "one", "(", "ctx", ",", "interactive", ",", "enable_phantomjs", ",", "enable_puppeteer", ",", "scripts", ")", ":", "ctx", ".", "obj", "[", "'debug'", "]", "=", "False", "g", "=", "ctx", ".", "obj", "g", "[", "'testing_mode'", "]", "=", "True", "if", "scripts", ":", "from", "pyspider", ".", "database", ".", "local", ".", "projectdb", "import", "ProjectDB", "g", "[", "'projectdb'", "]", "=", "ProjectDB", "(", "scripts", ")", "if", "g", ".", "get", "(", "'is_taskdb_default'", ")", ":", "g", "[", "'taskdb'", "]", "=", "connect_database", "(", "'sqlite+taskdb://'", ")", "if", "g", ".", "get", "(", "'is_resultdb_default'", ")", ":", "g", "[", "'resultdb'", "]", "=", "None", "if", "enable_phantomjs", ":", "phantomjs_config", "=", "g", ".", "config", ".", "get", "(", "'phantomjs'", ",", "{", "}", ")", "phantomjs_obj", "=", "ctx", ".", "invoke", "(", "phantomjs", ",", "*", "*", "phantomjs_config", ")", "if", "phantomjs_obj", ":", "g", ".", "setdefault", "(", "'phantomjs_proxy'", ",", "'127.0.0.1:%s'", "%", "phantomjs_obj", ".", "port", ")", "else", ":", "phantomjs_obj", "=", "None", "if", "enable_puppeteer", ":", "puppeteer_config", "=", "g", ".", "config", ".", "get", "(", "'puppeteer'", ",", "{", "}", ")", "puppeteer_obj", "=", "ctx", ".", "invoke", "(", "puppeteer", ",", "*", "*", "puppeteer_config", ")", "if", "puppeteer_obj", ":", "g", ".", "setdefault", "(", "'puppeteer_proxy'", ",", "'127.0.0.1:%s'", "%", "puppeteer", ".", "port", ")", "else", ":", "puppeteer_obj", "=", "None", "result_worker_config", "=", "g", ".", "config", ".", "get", "(", "'result_worker'", ",", "{", "}", ")", "if", "g", ".", "resultdb", "is", "None", ":", "result_worker_config", ".", "setdefault", "(", "'result_cls'", ",", "'pyspider.result.OneResultWorker'", ")", "result_worker_obj", "=", "ctx", ".", "invoke", "(", "result_worker", ",", "*", "*", "result_worker_config", ")", "processor_config", "=", "g", ".", "config", ".", "get", "(", "'processor'", ",", "{", "}", ")", "processor_config", ".", "setdefault", "(", "'enable_stdout_capture'", ",", "False", ")", "processor_obj", "=", "ctx", ".", "invoke", "(", "processor", ",", "*", "*", "processor_config", ")", "fetcher_config", "=", "g", ".", "config", ".", "get", "(", "'fetcher'", ",", "{", "}", ")", "fetcher_config", ".", "setdefault", "(", "'xmlrpc'", ",", "False", ")", "fetcher_obj", "=", "ctx", ".", "invoke", "(", "fetcher", ",", "*", "*", "fetcher_config", ")", "scheduler_config", "=", "g", ".", "config", ".", "get", "(", "'scheduler'", ",", "{", "}", ")", "scheduler_config", ".", "setdefault", "(", "'xmlrpc'", ",", "False", ")", "scheduler_config", ".", "setdefault", "(", "'scheduler_cls'", ",", "'pyspider.scheduler.OneScheduler'", ")", "scheduler_obj", "=", "ctx", ".", "invoke", "(", "scheduler", ",", "*", "*", "scheduler_config", ")", "scheduler_obj", ".", "init_one", "(", "ioloop", "=", "fetcher_obj", ".", "ioloop", ",", "fetcher", "=", "fetcher_obj", ",", "processor", "=", "processor_obj", ",", "result_worker", "=", "result_worker_obj", ",", "interactive", "=", "interactive", ")", "if", "scripts", ":", "for", "project", "in", "g", ".", "projectdb", ".", "projects", ":", "scheduler_obj", ".", "trigger_on_start", "(", "project", ")", "try", ":", "scheduler_obj", ".", "run", "(", ")", "finally", ":", "scheduler_obj", ".", "quit", "(", ")", "if", "phantomjs_obj", ":", "phantomjs_obj", ".", "quit", "(", ")", "if", "puppeteer_obj", ":", "puppeteer_obj", ".", "quit", "(", ")" ]
One mode not only means all-in-one, it runs every thing in one process over tornado.ioloop, for debug purpose
[ "One", "mode", "not", "only", "means", "all", "-", "in", "-", "one", "it", "runs", "every", "thing", "in", "one", "process", "over", "tornado", ".", "ioloop", "for", "debug", "purpose" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L723-L793
train
binux/pyspider
pyspider/run.py
send_message
def send_message(ctx, scheduler_rpc, project, message): """ Send Message to project from command line """ if isinstance(scheduler_rpc, six.string_types): scheduler_rpc = connect_rpc(ctx, None, scheduler_rpc) if scheduler_rpc is None and os.environ.get('SCHEDULER_NAME'): scheduler_rpc = connect_rpc(ctx, None, 'http://%s/' % ( os.environ['SCHEDULER_PORT_23333_TCP'][len('tcp://'):])) if scheduler_rpc is None: scheduler_rpc = connect_rpc(ctx, None, 'http://127.0.0.1:23333/') return scheduler_rpc.send_task({ 'taskid': utils.md5string('data:,on_message'), 'project': project, 'url': 'data:,on_message', 'fetch': { 'save': ('__command__', message), }, 'process': { 'callback': '_on_message', } })
python
def send_message(ctx, scheduler_rpc, project, message): """ Send Message to project from command line """ if isinstance(scheduler_rpc, six.string_types): scheduler_rpc = connect_rpc(ctx, None, scheduler_rpc) if scheduler_rpc is None and os.environ.get('SCHEDULER_NAME'): scheduler_rpc = connect_rpc(ctx, None, 'http://%s/' % ( os.environ['SCHEDULER_PORT_23333_TCP'][len('tcp://'):])) if scheduler_rpc is None: scheduler_rpc = connect_rpc(ctx, None, 'http://127.0.0.1:23333/') return scheduler_rpc.send_task({ 'taskid': utils.md5string('data:,on_message'), 'project': project, 'url': 'data:,on_message', 'fetch': { 'save': ('__command__', message), }, 'process': { 'callback': '_on_message', } })
[ "def", "send_message", "(", "ctx", ",", "scheduler_rpc", ",", "project", ",", "message", ")", ":", "if", "isinstance", "(", "scheduler_rpc", ",", "six", ".", "string_types", ")", ":", "scheduler_rpc", "=", "connect_rpc", "(", "ctx", ",", "None", ",", "scheduler_rpc", ")", "if", "scheduler_rpc", "is", "None", "and", "os", ".", "environ", ".", "get", "(", "'SCHEDULER_NAME'", ")", ":", "scheduler_rpc", "=", "connect_rpc", "(", "ctx", ",", "None", ",", "'http://%s/'", "%", "(", "os", ".", "environ", "[", "'SCHEDULER_PORT_23333_TCP'", "]", "[", "len", "(", "'tcp://'", ")", ":", "]", ")", ")", "if", "scheduler_rpc", "is", "None", ":", "scheduler_rpc", "=", "connect_rpc", "(", "ctx", ",", "None", ",", "'http://127.0.0.1:23333/'", ")", "return", "scheduler_rpc", ".", "send_task", "(", "{", "'taskid'", ":", "utils", ".", "md5string", "(", "'data:,on_message'", ")", ",", "'project'", ":", "project", ",", "'url'", ":", "'data:,on_message'", ",", "'fetch'", ":", "{", "'save'", ":", "(", "'__command__'", ",", "message", ")", ",", "}", ",", "'process'", ":", "{", "'callback'", ":", "'_on_message'", ",", "}", "}", ")" ]
Send Message to project from command line
[ "Send", "Message", "to", "project", "from", "command", "line" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L801-L823
train
binux/pyspider
pyspider/libs/pprint.py
pprint
def pprint(object, stream=None, indent=1, width=80, depth=None): """Pretty-print a Python object to a stream [default is sys.stdout].""" printer = PrettyPrinter( stream=stream, indent=indent, width=width, depth=depth) printer.pprint(object)
python
def pprint(object, stream=None, indent=1, width=80, depth=None): """Pretty-print a Python object to a stream [default is sys.stdout].""" printer = PrettyPrinter( stream=stream, indent=indent, width=width, depth=depth) printer.pprint(object)
[ "def", "pprint", "(", "object", ",", "stream", "=", "None", ",", "indent", "=", "1", ",", "width", "=", "80", ",", "depth", "=", "None", ")", ":", "printer", "=", "PrettyPrinter", "(", "stream", "=", "stream", ",", "indent", "=", "indent", ",", "width", "=", "width", ",", "depth", "=", "depth", ")", "printer", ".", "pprint", "(", "object", ")" ]
Pretty-print a Python object to a stream [default is sys.stdout].
[ "Pretty", "-", "print", "a", "Python", "object", "to", "a", "stream", "[", "default", "is", "sys", ".", "stdout", "]", "." ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/pprint.py#L54-L58
train
binux/pyspider
pyspider/libs/pprint.py
pformat
def pformat(object, indent=1, width=80, depth=None): """Format a Python object into a pretty-printed representation.""" return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
python
def pformat(object, indent=1, width=80, depth=None): """Format a Python object into a pretty-printed representation.""" return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
[ "def", "pformat", "(", "object", ",", "indent", "=", "1", ",", "width", "=", "80", ",", "depth", "=", "None", ")", ":", "return", "PrettyPrinter", "(", "indent", "=", "indent", ",", "width", "=", "width", ",", "depth", "=", "depth", ")", ".", "pformat", "(", "object", ")" ]
Format a Python object into a pretty-printed representation.
[ "Format", "a", "Python", "object", "into", "a", "pretty", "-", "printed", "representation", "." ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/pprint.py#L61-L63
train
binux/pyspider
pyspider/libs/pprint.py
PrettyPrinter.format
def format(self, object, context, maxlevels, level): """Format object for a specific context, returning a string and flags indicating whether the representation is 'readable' and whether the object represents a recursive construct. """ return _safe_repr(object, context, maxlevels, level)
python
def format(self, object, context, maxlevels, level): """Format object for a specific context, returning a string and flags indicating whether the representation is 'readable' and whether the object represents a recursive construct. """ return _safe_repr(object, context, maxlevels, level)
[ "def", "format", "(", "self", ",", "object", ",", "context", ",", "maxlevels", ",", "level", ")", ":", "return", "_safe_repr", "(", "object", ",", "context", ",", "maxlevels", ",", "level", ")" ]
Format object for a specific context, returning a string and flags indicating whether the representation is 'readable' and whether the object represents a recursive construct.
[ "Format", "object", "for", "a", "specific", "context", "returning", "a", "string", "and", "flags", "indicating", "whether", "the", "representation", "is", "readable", "and", "whether", "the", "object", "represents", "a", "recursive", "construct", "." ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/pprint.py#L243-L248
train
binux/pyspider
pyspider/result/result_worker.py
ResultWorker.on_result
def on_result(self, task, result): '''Called every result''' if not result: return if 'taskid' in task and 'project' in task and 'url' in task: logger.info('result %s:%s %s -> %.30r' % ( task['project'], task['taskid'], task['url'], result)) return self.resultdb.save( project=task['project'], taskid=task['taskid'], url=task['url'], result=result ) else: logger.warning('result UNKNOW -> %.30r' % result) return
python
def on_result(self, task, result): '''Called every result''' if not result: return if 'taskid' in task and 'project' in task and 'url' in task: logger.info('result %s:%s %s -> %.30r' % ( task['project'], task['taskid'], task['url'], result)) return self.resultdb.save( project=task['project'], taskid=task['taskid'], url=task['url'], result=result ) else: logger.warning('result UNKNOW -> %.30r' % result) return
[ "def", "on_result", "(", "self", ",", "task", ",", "result", ")", ":", "if", "not", "result", ":", "return", "if", "'taskid'", "in", "task", "and", "'project'", "in", "task", "and", "'url'", "in", "task", ":", "logger", ".", "info", "(", "'result %s:%s %s -> %.30r'", "%", "(", "task", "[", "'project'", "]", ",", "task", "[", "'taskid'", "]", ",", "task", "[", "'url'", "]", ",", "result", ")", ")", "return", "self", ".", "resultdb", ".", "save", "(", "project", "=", "task", "[", "'project'", "]", ",", "taskid", "=", "task", "[", "'taskid'", "]", ",", "url", "=", "task", "[", "'url'", "]", ",", "result", "=", "result", ")", "else", ":", "logger", ".", "warning", "(", "'result UNKNOW -> %.30r'", "%", "result", ")", "return" ]
Called every result
[ "Called", "every", "result" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/result/result_worker.py#L27-L42
train
binux/pyspider
pyspider/result/result_worker.py
ResultWorker.run
def run(self): '''Run loop''' logger.info("result_worker starting...") while not self._quit: try: task, result = self.inqueue.get(timeout=1) self.on_result(task, result) except Queue.Empty as e: continue except KeyboardInterrupt: break except AssertionError as e: logger.error(e) continue except Exception as e: logger.exception(e) continue logger.info("result_worker exiting...")
python
def run(self): '''Run loop''' logger.info("result_worker starting...") while not self._quit: try: task, result = self.inqueue.get(timeout=1) self.on_result(task, result) except Queue.Empty as e: continue except KeyboardInterrupt: break except AssertionError as e: logger.error(e) continue except Exception as e: logger.exception(e) continue logger.info("result_worker exiting...")
[ "def", "run", "(", "self", ")", ":", "logger", ".", "info", "(", "\"result_worker starting...\"", ")", "while", "not", "self", ".", "_quit", ":", "try", ":", "task", ",", "result", "=", "self", ".", "inqueue", ".", "get", "(", "timeout", "=", "1", ")", "self", ".", "on_result", "(", "task", ",", "result", ")", "except", "Queue", ".", "Empty", "as", "e", ":", "continue", "except", "KeyboardInterrupt", ":", "break", "except", "AssertionError", "as", "e", ":", "logger", ".", "error", "(", "e", ")", "continue", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "e", ")", "continue", "logger", ".", "info", "(", "\"result_worker exiting...\"", ")" ]
Run loop
[ "Run", "loop" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/result/result_worker.py#L47-L66
train
binux/pyspider
pyspider/result/result_worker.py
OneResultWorker.on_result
def on_result(self, task, result): '''Called every result''' if not result: return if 'taskid' in task and 'project' in task and 'url' in task: logger.info('result %s:%s %s -> %.30r' % ( task['project'], task['taskid'], task['url'], result)) print(json.dumps({ 'taskid': task['taskid'], 'project': task['project'], 'url': task['url'], 'result': result, 'updatetime': time.time() })) else: logger.warning('result UNKNOW -> %.30r' % result) return
python
def on_result(self, task, result): '''Called every result''' if not result: return if 'taskid' in task and 'project' in task and 'url' in task: logger.info('result %s:%s %s -> %.30r' % ( task['project'], task['taskid'], task['url'], result)) print(json.dumps({ 'taskid': task['taskid'], 'project': task['project'], 'url': task['url'], 'result': result, 'updatetime': time.time() })) else: logger.warning('result UNKNOW -> %.30r' % result) return
[ "def", "on_result", "(", "self", ",", "task", ",", "result", ")", ":", "if", "not", "result", ":", "return", "if", "'taskid'", "in", "task", "and", "'project'", "in", "task", "and", "'url'", "in", "task", ":", "logger", ".", "info", "(", "'result %s:%s %s -> %.30r'", "%", "(", "task", "[", "'project'", "]", ",", "task", "[", "'taskid'", "]", ",", "task", "[", "'url'", "]", ",", "result", ")", ")", "print", "(", "json", ".", "dumps", "(", "{", "'taskid'", ":", "task", "[", "'taskid'", "]", ",", "'project'", ":", "task", "[", "'project'", "]", ",", "'url'", ":", "task", "[", "'url'", "]", ",", "'result'", ":", "result", ",", "'updatetime'", ":", "time", ".", "time", "(", ")", "}", ")", ")", "else", ":", "logger", ".", "warning", "(", "'result UNKNOW -> %.30r'", "%", "result", ")", "return" ]
Called every result
[ "Called", "every", "result" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/result/result_worker.py#L71-L87
train
binux/pyspider
pyspider/scheduler/token_bucket.py
Bucket.get
def get(self): '''Get the number of tokens in bucket''' now = time.time() if self.bucket >= self.burst: self.last_update = now return self.bucket bucket = self.rate * (now - self.last_update) self.mutex.acquire() if bucket > 1: self.bucket += bucket if self.bucket > self.burst: self.bucket = self.burst self.last_update = now self.mutex.release() return self.bucket
python
def get(self): '''Get the number of tokens in bucket''' now = time.time() if self.bucket >= self.burst: self.last_update = now return self.bucket bucket = self.rate * (now - self.last_update) self.mutex.acquire() if bucket > 1: self.bucket += bucket if self.bucket > self.burst: self.bucket = self.burst self.last_update = now self.mutex.release() return self.bucket
[ "def", "get", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "if", "self", ".", "bucket", ">=", "self", ".", "burst", ":", "self", ".", "last_update", "=", "now", "return", "self", ".", "bucket", "bucket", "=", "self", ".", "rate", "*", "(", "now", "-", "self", ".", "last_update", ")", "self", ".", "mutex", ".", "acquire", "(", ")", "if", "bucket", ">", "1", ":", "self", ".", "bucket", "+=", "bucket", "if", "self", ".", "bucket", ">", "self", ".", "burst", ":", "self", ".", "bucket", "=", "self", ".", "burst", "self", ".", "last_update", "=", "now", "self", ".", "mutex", ".", "release", "(", ")", "return", "self", ".", "bucket" ]
Get the number of tokens in bucket
[ "Get", "the", "number", "of", "tokens", "in", "bucket" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/token_bucket.py#L33-L47
train
binux/pyspider
tools/migrate.py
migrate
def migrate(pool, from_connection, to_connection): """ Migrate tool for pyspider """ f = connect_database(from_connection) t = connect_database(to_connection) if isinstance(f, ProjectDB): for each in f.get_all(): each = unicode_obj(each) logging.info("projectdb: %s", each['name']) t.drop(each['name']) t.insert(each['name'], each) elif isinstance(f, TaskDB): pool = Pool(pool) pool.map( lambda x, f=from_connection, t=to_connection: taskdb_migrating(x, f, t), f.projects) elif isinstance(f, ResultDB): pool = Pool(pool) pool.map( lambda x, f=from_connection, t=to_connection: resultdb_migrating(x, f, t), f.projects)
python
def migrate(pool, from_connection, to_connection): """ Migrate tool for pyspider """ f = connect_database(from_connection) t = connect_database(to_connection) if isinstance(f, ProjectDB): for each in f.get_all(): each = unicode_obj(each) logging.info("projectdb: %s", each['name']) t.drop(each['name']) t.insert(each['name'], each) elif isinstance(f, TaskDB): pool = Pool(pool) pool.map( lambda x, f=from_connection, t=to_connection: taskdb_migrating(x, f, t), f.projects) elif isinstance(f, ResultDB): pool = Pool(pool) pool.map( lambda x, f=from_connection, t=to_connection: resultdb_migrating(x, f, t), f.projects)
[ "def", "migrate", "(", "pool", ",", "from_connection", ",", "to_connection", ")", ":", "f", "=", "connect_database", "(", "from_connection", ")", "t", "=", "connect_database", "(", "to_connection", ")", "if", "isinstance", "(", "f", ",", "ProjectDB", ")", ":", "for", "each", "in", "f", ".", "get_all", "(", ")", ":", "each", "=", "unicode_obj", "(", "each", ")", "logging", ".", "info", "(", "\"projectdb: %s\"", ",", "each", "[", "'name'", "]", ")", "t", ".", "drop", "(", "each", "[", "'name'", "]", ")", "t", ".", "insert", "(", "each", "[", "'name'", "]", ",", "each", ")", "elif", "isinstance", "(", "f", ",", "TaskDB", ")", ":", "pool", "=", "Pool", "(", "pool", ")", "pool", ".", "map", "(", "lambda", "x", ",", "f", "=", "from_connection", ",", "t", "=", "to_connection", ":", "taskdb_migrating", "(", "x", ",", "f", ",", "t", ")", ",", "f", ".", "projects", ")", "elif", "isinstance", "(", "f", ",", "ResultDB", ")", ":", "pool", "=", "Pool", "(", "pool", ")", "pool", ".", "map", "(", "lambda", "x", ",", "f", "=", "from_connection", ",", "t", "=", "to_connection", ":", "resultdb_migrating", "(", "x", ",", "f", ",", "t", ")", ",", "f", ".", "projects", ")" ]
Migrate tool for pyspider
[ "Migrate", "tool", "for", "pyspider" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/tools/migrate.py#L43-L65
train
binux/pyspider
pyspider/libs/dataurl.py
encode
def encode(data, mime_type='', charset='utf-8', base64=True): """ Encode data to DataURL """ if isinstance(data, six.text_type): data = data.encode(charset) else: charset = None if base64: data = utils.text(b64encode(data)) else: data = utils.text(quote(data)) result = ['data:', ] if mime_type: result.append(mime_type) if charset: result.append(';charset=') result.append(charset) if base64: result.append(';base64') result.append(',') result.append(data) return ''.join(result)
python
def encode(data, mime_type='', charset='utf-8', base64=True): """ Encode data to DataURL """ if isinstance(data, six.text_type): data = data.encode(charset) else: charset = None if base64: data = utils.text(b64encode(data)) else: data = utils.text(quote(data)) result = ['data:', ] if mime_type: result.append(mime_type) if charset: result.append(';charset=') result.append(charset) if base64: result.append(';base64') result.append(',') result.append(data) return ''.join(result)
[ "def", "encode", "(", "data", ",", "mime_type", "=", "''", ",", "charset", "=", "'utf-8'", ",", "base64", "=", "True", ")", ":", "if", "isinstance", "(", "data", ",", "six", ".", "text_type", ")", ":", "data", "=", "data", ".", "encode", "(", "charset", ")", "else", ":", "charset", "=", "None", "if", "base64", ":", "data", "=", "utils", ".", "text", "(", "b64encode", "(", "data", ")", ")", "else", ":", "data", "=", "utils", ".", "text", "(", "quote", "(", "data", ")", ")", "result", "=", "[", "'data:'", ",", "]", "if", "mime_type", ":", "result", ".", "append", "(", "mime_type", ")", "if", "charset", ":", "result", ".", "append", "(", "';charset='", ")", "result", ".", "append", "(", "charset", ")", "if", "base64", ":", "result", ".", "append", "(", "';base64'", ")", "result", ".", "append", "(", "','", ")", "result", ".", "append", "(", "data", ")", "return", "''", ".", "join", "(", "result", ")" ]
Encode data to DataURL
[ "Encode", "data", "to", "DataURL" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/dataurl.py#L14-L38
train
binux/pyspider
pyspider/libs/dataurl.py
decode
def decode(data_url): """ Decode DataURL data """ metadata, data = data_url.rsplit(',', 1) _, metadata = metadata.split('data:', 1) parts = metadata.split(';') if parts[-1] == 'base64': data = b64decode(data) else: data = unquote(data) for part in parts: if part.startswith("charset="): data = data.decode(part[8:]) return data
python
def decode(data_url): """ Decode DataURL data """ metadata, data = data_url.rsplit(',', 1) _, metadata = metadata.split('data:', 1) parts = metadata.split(';') if parts[-1] == 'base64': data = b64decode(data) else: data = unquote(data) for part in parts: if part.startswith("charset="): data = data.decode(part[8:]) return data
[ "def", "decode", "(", "data_url", ")", ":", "metadata", ",", "data", "=", "data_url", ".", "rsplit", "(", "','", ",", "1", ")", "_", ",", "metadata", "=", "metadata", ".", "split", "(", "'data:'", ",", "1", ")", "parts", "=", "metadata", ".", "split", "(", "';'", ")", "if", "parts", "[", "-", "1", "]", "==", "'base64'", ":", "data", "=", "b64decode", "(", "data", ")", "else", ":", "data", "=", "unquote", "(", "data", ")", "for", "part", "in", "parts", ":", "if", "part", ".", "startswith", "(", "\"charset=\"", ")", ":", "data", "=", "data", ".", "decode", "(", "part", "[", "8", ":", "]", ")", "return", "data" ]
Decode DataURL data
[ "Decode", "DataURL", "data" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/dataurl.py#L41-L56
train
binux/pyspider
pyspider/libs/url.py
_build_url
def _build_url(url, _params): """Build the actual URL to use.""" # Support for unicode domain names and paths. scheme, netloc, path, params, query, fragment = urlparse(url) netloc = netloc.encode('idna').decode('utf-8') if not path: path = '/' if six.PY2: if isinstance(scheme, six.text_type): scheme = scheme.encode('utf-8') if isinstance(netloc, six.text_type): netloc = netloc.encode('utf-8') if isinstance(path, six.text_type): path = path.encode('utf-8') if isinstance(params, six.text_type): params = params.encode('utf-8') if isinstance(query, six.text_type): query = query.encode('utf-8') if isinstance(fragment, six.text_type): fragment = fragment.encode('utf-8') enc_params = _encode_params(_params) if enc_params: if query: query = '%s&%s' % (query, enc_params) else: query = enc_params url = (urlunparse([scheme, netloc, path, params, query, fragment])) return url
python
def _build_url(url, _params): """Build the actual URL to use.""" # Support for unicode domain names and paths. scheme, netloc, path, params, query, fragment = urlparse(url) netloc = netloc.encode('idna').decode('utf-8') if not path: path = '/' if six.PY2: if isinstance(scheme, six.text_type): scheme = scheme.encode('utf-8') if isinstance(netloc, six.text_type): netloc = netloc.encode('utf-8') if isinstance(path, six.text_type): path = path.encode('utf-8') if isinstance(params, six.text_type): params = params.encode('utf-8') if isinstance(query, six.text_type): query = query.encode('utf-8') if isinstance(fragment, six.text_type): fragment = fragment.encode('utf-8') enc_params = _encode_params(_params) if enc_params: if query: query = '%s&%s' % (query, enc_params) else: query = enc_params url = (urlunparse([scheme, netloc, path, params, query, fragment])) return url
[ "def", "_build_url", "(", "url", ",", "_params", ")", ":", "# Support for unicode domain names and paths.", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "url", ")", "netloc", "=", "netloc", ".", "encode", "(", "'idna'", ")", ".", "decode", "(", "'utf-8'", ")", "if", "not", "path", ":", "path", "=", "'/'", "if", "six", ".", "PY2", ":", "if", "isinstance", "(", "scheme", ",", "six", ".", "text_type", ")", ":", "scheme", "=", "scheme", ".", "encode", "(", "'utf-8'", ")", "if", "isinstance", "(", "netloc", ",", "six", ".", "text_type", ")", ":", "netloc", "=", "netloc", ".", "encode", "(", "'utf-8'", ")", "if", "isinstance", "(", "path", ",", "six", ".", "text_type", ")", ":", "path", "=", "path", ".", "encode", "(", "'utf-8'", ")", "if", "isinstance", "(", "params", ",", "six", ".", "text_type", ")", ":", "params", "=", "params", ".", "encode", "(", "'utf-8'", ")", "if", "isinstance", "(", "query", ",", "six", ".", "text_type", ")", ":", "query", "=", "query", ".", "encode", "(", "'utf-8'", ")", "if", "isinstance", "(", "fragment", ",", "six", ".", "text_type", ")", ":", "fragment", "=", "fragment", ".", "encode", "(", "'utf-8'", ")", "enc_params", "=", "_encode_params", "(", "_params", ")", "if", "enc_params", ":", "if", "query", ":", "query", "=", "'%s&%s'", "%", "(", "query", ",", "enc_params", ")", "else", ":", "query", "=", "enc_params", "url", "=", "(", "urlunparse", "(", "[", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "]", ")", ")", "return", "url" ]
Build the actual URL to use.
[ "Build", "the", "actual", "URL", "to", "use", "." ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/url.py#L29-L59
train
binux/pyspider
pyspider/libs/url.py
quote_chinese
def quote_chinese(url, encodeing="utf-8"): """Quote non-ascii characters""" if isinstance(url, six.text_type): return quote_chinese(url.encode(encodeing)) if six.PY3: res = [six.int2byte(b).decode('latin-1') if b < 128 else '%%%02X' % b for b in url] else: res = [b if ord(b) < 128 else '%%%02X' % ord(b) for b in url] return "".join(res)
python
def quote_chinese(url, encodeing="utf-8"): """Quote non-ascii characters""" if isinstance(url, six.text_type): return quote_chinese(url.encode(encodeing)) if six.PY3: res = [six.int2byte(b).decode('latin-1') if b < 128 else '%%%02X' % b for b in url] else: res = [b if ord(b) < 128 else '%%%02X' % ord(b) for b in url] return "".join(res)
[ "def", "quote_chinese", "(", "url", ",", "encodeing", "=", "\"utf-8\"", ")", ":", "if", "isinstance", "(", "url", ",", "six", ".", "text_type", ")", ":", "return", "quote_chinese", "(", "url", ".", "encode", "(", "encodeing", ")", ")", "if", "six", ".", "PY3", ":", "res", "=", "[", "six", ".", "int2byte", "(", "b", ")", ".", "decode", "(", "'latin-1'", ")", "if", "b", "<", "128", "else", "'%%%02X'", "%", "b", "for", "b", "in", "url", "]", "else", ":", "res", "=", "[", "b", "if", "ord", "(", "b", ")", "<", "128", "else", "'%%%02X'", "%", "ord", "(", "b", ")", "for", "b", "in", "url", "]", "return", "\"\"", ".", "join", "(", "res", ")" ]
Quote non-ascii characters
[ "Quote", "non", "-", "ascii", "characters" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/url.py#L62-L70
train
lanpa/tensorboardX
examples/demo_caffe2.py
DownloadResource
def DownloadResource(url, path): '''Downloads resources from s3 by url and unzips them to the provided path''' import requests from six import BytesIO import zipfile print("Downloading... {} to {}".format(url, path)) r = requests.get(url, stream=True) z = zipfile.ZipFile(BytesIO(r.content)) z.extractall(path) print("Completed download and extraction.")
python
def DownloadResource(url, path): '''Downloads resources from s3 by url and unzips them to the provided path''' import requests from six import BytesIO import zipfile print("Downloading... {} to {}".format(url, path)) r = requests.get(url, stream=True) z = zipfile.ZipFile(BytesIO(r.content)) z.extractall(path) print("Completed download and extraction.")
[ "def", "DownloadResource", "(", "url", ",", "path", ")", ":", "import", "requests", "from", "six", "import", "BytesIO", "import", "zipfile", "print", "(", "\"Downloading... {} to {}\"", ".", "format", "(", "url", ",", "path", ")", ")", "r", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "z", "=", "zipfile", ".", "ZipFile", "(", "BytesIO", "(", "r", ".", "content", ")", ")", "z", ".", "extractall", "(", "path", ")", "print", "(", "\"Completed download and extraction.\"", ")" ]
Downloads resources from s3 by url and unzips them to the provided path
[ "Downloads", "resources", "from", "s3", "by", "url", "and", "unzips", "them", "to", "the", "provided", "path" ]
0bf6c07d97b0745654fd9fab8ee3261ec707f253
https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L28-L37
train
lanpa/tensorboardX
examples/demo_caffe2.py
AddLeNetModel
def AddLeNetModel(model, data): ''' This part is the standard LeNet model: from data to the softmax prediction. For each convolutional layer we specify dim_in - number of input channels and dim_out - number or output channels. Also each Conv and MaxPool layer changes the image size. For example, kernel of size 5 reduces each side of an image by 4. While when we have kernel and stride sizes equal 2 in a MaxPool layer, it divides each side in half. ''' # Image size: 28 x 28 -> 24 x 24 conv1 = brew.conv(model, data, 'conv1', dim_in=1, dim_out=20, kernel=5) # Image size: 24 x 24 -> 12 x 12 pool1 = brew.max_pool(model, conv1, 'pool1', kernel=2, stride=2) # Image size: 12 x 12 -> 8 x 8 conv2 = brew.conv(model, pool1, 'conv2', dim_in=20, dim_out=100, kernel=5) # Image size: 8 x 8 -> 4 x 4 pool2 = brew.max_pool(model, conv2, 'pool2', kernel=2, stride=2) # 50 * 4 * 4 stands for dim_out from previous layer multiplied by the # image size fc3 = brew.fc(model, pool2, 'fc3', dim_in=100 * 4 * 4, dim_out=500) relu = brew.relu(model, fc3, fc3) pred = brew.fc(model, relu, 'pred', 500, 10) softmax = brew.softmax(model, pred, 'softmax') return softmax
python
def AddLeNetModel(model, data): ''' This part is the standard LeNet model: from data to the softmax prediction. For each convolutional layer we specify dim_in - number of input channels and dim_out - number or output channels. Also each Conv and MaxPool layer changes the image size. For example, kernel of size 5 reduces each side of an image by 4. While when we have kernel and stride sizes equal 2 in a MaxPool layer, it divides each side in half. ''' # Image size: 28 x 28 -> 24 x 24 conv1 = brew.conv(model, data, 'conv1', dim_in=1, dim_out=20, kernel=5) # Image size: 24 x 24 -> 12 x 12 pool1 = brew.max_pool(model, conv1, 'pool1', kernel=2, stride=2) # Image size: 12 x 12 -> 8 x 8 conv2 = brew.conv(model, pool1, 'conv2', dim_in=20, dim_out=100, kernel=5) # Image size: 8 x 8 -> 4 x 4 pool2 = brew.max_pool(model, conv2, 'pool2', kernel=2, stride=2) # 50 * 4 * 4 stands for dim_out from previous layer multiplied by the # image size fc3 = brew.fc(model, pool2, 'fc3', dim_in=100 * 4 * 4, dim_out=500) relu = brew.relu(model, fc3, fc3) pred = brew.fc(model, relu, 'pred', 500, 10) softmax = brew.softmax(model, pred, 'softmax') return softmax
[ "def", "AddLeNetModel", "(", "model", ",", "data", ")", ":", "# Image size: 28 x 28 -> 24 x 24", "conv1", "=", "brew", ".", "conv", "(", "model", ",", "data", ",", "'conv1'", ",", "dim_in", "=", "1", ",", "dim_out", "=", "20", ",", "kernel", "=", "5", ")", "# Image size: 24 x 24 -> 12 x 12", "pool1", "=", "brew", ".", "max_pool", "(", "model", ",", "conv1", ",", "'pool1'", ",", "kernel", "=", "2", ",", "stride", "=", "2", ")", "# Image size: 12 x 12 -> 8 x 8", "conv2", "=", "brew", ".", "conv", "(", "model", ",", "pool1", ",", "'conv2'", ",", "dim_in", "=", "20", ",", "dim_out", "=", "100", ",", "kernel", "=", "5", ")", "# Image size: 8 x 8 -> 4 x 4", "pool2", "=", "brew", ".", "max_pool", "(", "model", ",", "conv2", ",", "'pool2'", ",", "kernel", "=", "2", ",", "stride", "=", "2", ")", "# 50 * 4 * 4 stands for dim_out from previous layer multiplied by the", "# image size", "fc3", "=", "brew", ".", "fc", "(", "model", ",", "pool2", ",", "'fc3'", ",", "dim_in", "=", "100", "*", "4", "*", "4", ",", "dim_out", "=", "500", ")", "relu", "=", "brew", ".", "relu", "(", "model", ",", "fc3", ",", "fc3", ")", "pred", "=", "brew", ".", "fc", "(", "model", ",", "relu", ",", "'pred'", ",", "500", ",", "10", ")", "softmax", "=", "brew", ".", "softmax", "(", "model", ",", "pred", ",", "'softmax'", ")", "return", "softmax" ]
This part is the standard LeNet model: from data to the softmax prediction. For each convolutional layer we specify dim_in - number of input channels and dim_out - number or output channels. Also each Conv and MaxPool layer changes the image size. For example, kernel of size 5 reduces each side of an image by 4. While when we have kernel and stride sizes equal 2 in a MaxPool layer, it divides each side in half.
[ "This", "part", "is", "the", "standard", "LeNet", "model", ":", "from", "data", "to", "the", "softmax", "prediction", "." ]
0bf6c07d97b0745654fd9fab8ee3261ec707f253
https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L102-L127
train
lanpa/tensorboardX
examples/demo_caffe2.py
AddAccuracy
def AddAccuracy(model, softmax, label): """Adds an accuracy op to the model""" accuracy = brew.accuracy(model, [softmax, label], "accuracy") return accuracy
python
def AddAccuracy(model, softmax, label): """Adds an accuracy op to the model""" accuracy = brew.accuracy(model, [softmax, label], "accuracy") return accuracy
[ "def", "AddAccuracy", "(", "model", ",", "softmax", ",", "label", ")", ":", "accuracy", "=", "brew", ".", "accuracy", "(", "model", ",", "[", "softmax", ",", "label", "]", ",", "\"accuracy\"", ")", "return", "accuracy" ]
Adds an accuracy op to the model
[ "Adds", "an", "accuracy", "op", "to", "the", "model" ]
0bf6c07d97b0745654fd9fab8ee3261ec707f253
https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L130-L133
train
lanpa/tensorboardX
examples/demo_caffe2.py
AddTrainingOperators
def AddTrainingOperators(model, softmax, label): """Adds training operators to the model.""" xent = model.LabelCrossEntropy([softmax, label], 'xent') # compute the expected loss loss = model.AveragedLoss(xent, "loss") # track the accuracy of the model AddAccuracy(model, softmax, label) # use the average loss we just computed to add gradient operators to the # model model.AddGradientOperators([loss]) # do a simple stochastic gradient descent ITER = brew.iter(model, "iter") # set the learning rate schedule LR = model.LearningRate( ITER, "LR", base_lr=-0.1, policy="step", stepsize=1, gamma=0.999) # ONE is a constant value that is used in the gradient update. We only need # to create it once, so it is explicitly placed in param_init_net. ONE = model.param_init_net.ConstantFill([], "ONE", shape=[1], value=1.0) # Now, for each parameter, we do the gradient updates. for param in model.params: # Note how we get the gradient of each parameter - ModelHelper keeps # track of that. param_grad = model.param_to_grad[param] # The update is a simple weighted sum: param = param + param_grad * LR model.WeightedSum([param, ONE, param_grad, LR], param)
python
def AddTrainingOperators(model, softmax, label): """Adds training operators to the model.""" xent = model.LabelCrossEntropy([softmax, label], 'xent') # compute the expected loss loss = model.AveragedLoss(xent, "loss") # track the accuracy of the model AddAccuracy(model, softmax, label) # use the average loss we just computed to add gradient operators to the # model model.AddGradientOperators([loss]) # do a simple stochastic gradient descent ITER = brew.iter(model, "iter") # set the learning rate schedule LR = model.LearningRate( ITER, "LR", base_lr=-0.1, policy="step", stepsize=1, gamma=0.999) # ONE is a constant value that is used in the gradient update. We only need # to create it once, so it is explicitly placed in param_init_net. ONE = model.param_init_net.ConstantFill([], "ONE", shape=[1], value=1.0) # Now, for each parameter, we do the gradient updates. for param in model.params: # Note how we get the gradient of each parameter - ModelHelper keeps # track of that. param_grad = model.param_to_grad[param] # The update is a simple weighted sum: param = param + param_grad * LR model.WeightedSum([param, ONE, param_grad, LR], param)
[ "def", "AddTrainingOperators", "(", "model", ",", "softmax", ",", "label", ")", ":", "xent", "=", "model", ".", "LabelCrossEntropy", "(", "[", "softmax", ",", "label", "]", ",", "'xent'", ")", "# compute the expected loss", "loss", "=", "model", ".", "AveragedLoss", "(", "xent", ",", "\"loss\"", ")", "# track the accuracy of the model", "AddAccuracy", "(", "model", ",", "softmax", ",", "label", ")", "# use the average loss we just computed to add gradient operators to the", "# model", "model", ".", "AddGradientOperators", "(", "[", "loss", "]", ")", "# do a simple stochastic gradient descent", "ITER", "=", "brew", ".", "iter", "(", "model", ",", "\"iter\"", ")", "# set the learning rate schedule", "LR", "=", "model", ".", "LearningRate", "(", "ITER", ",", "\"LR\"", ",", "base_lr", "=", "-", "0.1", ",", "policy", "=", "\"step\"", ",", "stepsize", "=", "1", ",", "gamma", "=", "0.999", ")", "# ONE is a constant value that is used in the gradient update. We only need", "# to create it once, so it is explicitly placed in param_init_net.", "ONE", "=", "model", ".", "param_init_net", ".", "ConstantFill", "(", "[", "]", ",", "\"ONE\"", ",", "shape", "=", "[", "1", "]", ",", "value", "=", "1.0", ")", "# Now, for each parameter, we do the gradient updates.", "for", "param", "in", "model", ".", "params", ":", "# Note how we get the gradient of each parameter - ModelHelper keeps", "# track of that.", "param_grad", "=", "model", ".", "param_to_grad", "[", "param", "]", "# The update is a simple weighted sum: param = param + param_grad * LR", "model", ".", "WeightedSum", "(", "[", "param", ",", "ONE", ",", "param_grad", ",", "LR", "]", ",", "param", ")" ]
Adds training operators to the model.
[ "Adds", "training", "operators", "to", "the", "model", "." ]
0bf6c07d97b0745654fd9fab8ee3261ec707f253
https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L136-L160
train
lanpa/tensorboardX
examples/demo_caffe2.py
AddBookkeepingOperators
def AddBookkeepingOperators(model): """This adds a few bookkeeping operators that we can inspect later. These operators do not affect the training procedure: they only collect statistics and prints them to file or to logs. """ # Print basically prints out the content of the blob. to_file=1 routes the # printed output to a file. The file is going to be stored under # root_folder/[blob name] model.Print('accuracy', [], to_file=1) model.Print('loss', [], to_file=1) # Summarizes the parameters. Different from Print, Summarize gives some # statistics of the parameter, such as mean, std, min and max. for param in model.params: model.Summarize(param, [], to_file=1) model.Summarize(model.param_to_grad[param], [], to_file=1)
python
def AddBookkeepingOperators(model): """This adds a few bookkeeping operators that we can inspect later. These operators do not affect the training procedure: they only collect statistics and prints them to file or to logs. """ # Print basically prints out the content of the blob. to_file=1 routes the # printed output to a file. The file is going to be stored under # root_folder/[blob name] model.Print('accuracy', [], to_file=1) model.Print('loss', [], to_file=1) # Summarizes the parameters. Different from Print, Summarize gives some # statistics of the parameter, such as mean, std, min and max. for param in model.params: model.Summarize(param, [], to_file=1) model.Summarize(model.param_to_grad[param], [], to_file=1)
[ "def", "AddBookkeepingOperators", "(", "model", ")", ":", "# Print basically prints out the content of the blob. to_file=1 routes the", "# printed output to a file. The file is going to be stored under", "# root_folder/[blob name]", "model", ".", "Print", "(", "'accuracy'", ",", "[", "]", ",", "to_file", "=", "1", ")", "model", ".", "Print", "(", "'loss'", ",", "[", "]", ",", "to_file", "=", "1", ")", "# Summarizes the parameters. Different from Print, Summarize gives some", "# statistics of the parameter, such as mean, std, min and max.", "for", "param", "in", "model", ".", "params", ":", "model", ".", "Summarize", "(", "param", ",", "[", "]", ",", "to_file", "=", "1", ")", "model", ".", "Summarize", "(", "model", ".", "param_to_grad", "[", "param", "]", ",", "[", "]", ",", "to_file", "=", "1", ")" ]
This adds a few bookkeeping operators that we can inspect later. These operators do not affect the training procedure: they only collect statistics and prints them to file or to logs.
[ "This", "adds", "a", "few", "bookkeeping", "operators", "that", "we", "can", "inspect", "later", "." ]
0bf6c07d97b0745654fd9fab8ee3261ec707f253
https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L163-L178
train
lanpa/tensorboardX
examples/chainer/plain_logger/net.py
VAE.get_loss_func
def get_loss_func(self, C=1.0, k=1): """Get loss function of VAE. The loss value is equal to ELBO (Evidence Lower Bound) multiplied by -1. Args: C (int): Usually this is 1.0. Can be changed to control the second term of ELBO bound, which works as regularization. k (int): Number of Monte Carlo samples used in encoded vector. """ def lf(x): mu, ln_var = self.encode(x) batchsize = len(mu.data) # reconstruction loss rec_loss = 0 for l in six.moves.range(k): z = F.gaussian(mu, ln_var) rec_loss += F.bernoulli_nll(x, self.decode(z, sigmoid=False)) \ / (k * batchsize) self.rec_loss = rec_loss self.loss = self.rec_loss + \ C * gaussian_kl_divergence(mu, ln_var) / batchsize return self.loss return lf
python
def get_loss_func(self, C=1.0, k=1): """Get loss function of VAE. The loss value is equal to ELBO (Evidence Lower Bound) multiplied by -1. Args: C (int): Usually this is 1.0. Can be changed to control the second term of ELBO bound, which works as regularization. k (int): Number of Monte Carlo samples used in encoded vector. """ def lf(x): mu, ln_var = self.encode(x) batchsize = len(mu.data) # reconstruction loss rec_loss = 0 for l in six.moves.range(k): z = F.gaussian(mu, ln_var) rec_loss += F.bernoulli_nll(x, self.decode(z, sigmoid=False)) \ / (k * batchsize) self.rec_loss = rec_loss self.loss = self.rec_loss + \ C * gaussian_kl_divergence(mu, ln_var) / batchsize return self.loss return lf
[ "def", "get_loss_func", "(", "self", ",", "C", "=", "1.0", ",", "k", "=", "1", ")", ":", "def", "lf", "(", "x", ")", ":", "mu", ",", "ln_var", "=", "self", ".", "encode", "(", "x", ")", "batchsize", "=", "len", "(", "mu", ".", "data", ")", "# reconstruction loss", "rec_loss", "=", "0", "for", "l", "in", "six", ".", "moves", ".", "range", "(", "k", ")", ":", "z", "=", "F", ".", "gaussian", "(", "mu", ",", "ln_var", ")", "rec_loss", "+=", "F", ".", "bernoulli_nll", "(", "x", ",", "self", ".", "decode", "(", "z", ",", "sigmoid", "=", "False", ")", ")", "/", "(", "k", "*", "batchsize", ")", "self", ".", "rec_loss", "=", "rec_loss", "self", ".", "loss", "=", "self", ".", "rec_loss", "+", "C", "*", "gaussian_kl_divergence", "(", "mu", ",", "ln_var", ")", "/", "batchsize", "return", "self", ".", "loss", "return", "lf" ]
Get loss function of VAE. The loss value is equal to ELBO (Evidence Lower Bound) multiplied by -1. Args: C (int): Usually this is 1.0. Can be changed to control the second term of ELBO bound, which works as regularization. k (int): Number of Monte Carlo samples used in encoded vector.
[ "Get", "loss", "function", "of", "VAE", "." ]
0bf6c07d97b0745654fd9fab8ee3261ec707f253
https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/chainer/plain_logger/net.py#L41-L65
train
keras-rl/keras-rl
rl/core.py
Agent.fit
def fit(self, env, nb_steps, action_repetition=1, callbacks=None, verbose=1, visualize=False, nb_max_start_steps=0, start_step_policy=None, log_interval=10000, nb_max_episode_steps=None): """Trains the agent on the given environment. # Arguments env: (`Env` instance): Environment that the agent interacts with. See [Env](#env) for details. nb_steps (integer): Number of training steps to be performed. action_repetition (integer): Number of times the agent repeats the same action without observing the environment again. Setting this to a value > 1 can be useful if a single action only has a very small effect on the environment. callbacks (list of `keras.callbacks.Callback` or `rl.callbacks.Callback` instances): List of callbacks to apply during training. See [callbacks](/callbacks) for details. verbose (integer): 0 for no logging, 1 for interval logging (compare `log_interval`), 2 for episode logging visualize (boolean): If `True`, the environment is visualized during training. However, this is likely going to slow down training significantly and is thus intended to be a debugging instrument. nb_max_start_steps (integer): Number of maximum steps that the agent performs at the beginning of each episode using `start_step_policy`. Notice that this is an upper limit since the exact number of steps to be performed is sampled uniformly from [0, max_start_steps] at the beginning of each episode. start_step_policy (`lambda observation: action`): The policy to follow if `nb_max_start_steps` > 0. If set to `None`, a random action is performed. log_interval (integer): If `verbose` = 1, the number of steps that are considered to be an interval. nb_max_episode_steps (integer): Number of steps per episode that the agent performs before automatically resetting the environment. Set to `None` if each episode should run (potentially indefinitely) until the environment signals a terminal state. # Returns A `keras.callbacks.History` instance that recorded the entire training process. """ if not self.compiled: raise RuntimeError('Your tried to fit your agent but it hasn\'t been compiled yet. Please call `compile()` before `fit()`.') if action_repetition < 1: raise ValueError('action_repetition must be >= 1, is {}'.format(action_repetition)) self.training = True callbacks = [] if not callbacks else callbacks[:] if verbose == 1: callbacks += [TrainIntervalLogger(interval=log_interval)] elif verbose > 1: callbacks += [TrainEpisodeLogger()] if visualize: callbacks += [Visualizer()] history = History() callbacks += [history] callbacks = CallbackList(callbacks) if hasattr(callbacks, 'set_model'): callbacks.set_model(self) else: callbacks._set_model(self) callbacks._set_env(env) params = { 'nb_steps': nb_steps, } if hasattr(callbacks, 'set_params'): callbacks.set_params(params) else: callbacks._set_params(params) self._on_train_begin() callbacks.on_train_begin() episode = np.int16(0) self.step = np.int16(0) observation = None episode_reward = None episode_step = None did_abort = False try: while self.step < nb_steps: if observation is None: # start of a new episode callbacks.on_episode_begin(episode) episode_step = np.int16(0) episode_reward = np.float32(0) # Obtain the initial observation by resetting the environment. self.reset_states() observation = deepcopy(env.reset()) if self.processor is not None: observation = self.processor.process_observation(observation) assert observation is not None # Perform random starts at beginning of episode and do not record them into the experience. # This slightly changes the start position between games. nb_random_start_steps = 0 if nb_max_start_steps == 0 else np.random.randint(nb_max_start_steps) for _ in range(nb_random_start_steps): if start_step_policy is None: action = env.action_space.sample() else: action = start_step_policy(observation) if self.processor is not None: action = self.processor.process_action(action) callbacks.on_action_begin(action) observation, reward, done, info = env.step(action) observation = deepcopy(observation) if self.processor is not None: observation, reward, done, info = self.processor.process_step(observation, reward, done, info) callbacks.on_action_end(action) if done: warnings.warn('Env ended before {} random steps could be performed at the start. You should probably lower the `nb_max_start_steps` parameter.'.format(nb_random_start_steps)) observation = deepcopy(env.reset()) if self.processor is not None: observation = self.processor.process_observation(observation) break # At this point, we expect to be fully initialized. assert episode_reward is not None assert episode_step is not None assert observation is not None # Run a single step. callbacks.on_step_begin(episode_step) # This is were all of the work happens. We first perceive and compute the action # (forward step) and then use the reward to improve (backward step). action = self.forward(observation) if self.processor is not None: action = self.processor.process_action(action) reward = np.float32(0) accumulated_info = {} done = False for _ in range(action_repetition): callbacks.on_action_begin(action) observation, r, done, info = env.step(action) observation = deepcopy(observation) if self.processor is not None: observation, r, done, info = self.processor.process_step(observation, r, done, info) for key, value in info.items(): if not np.isreal(value): continue if key not in accumulated_info: accumulated_info[key] = np.zeros_like(value) accumulated_info[key] += value callbacks.on_action_end(action) reward += r if done: break if nb_max_episode_steps and episode_step >= nb_max_episode_steps - 1: # Force a terminal state. done = True metrics = self.backward(reward, terminal=done) episode_reward += reward step_logs = { 'action': action, 'observation': observation, 'reward': reward, 'metrics': metrics, 'episode': episode, 'info': accumulated_info, } callbacks.on_step_end(episode_step, step_logs) episode_step += 1 self.step += 1 if done: # We are in a terminal state but the agent hasn't yet seen it. We therefore # perform one more forward-backward call and simply ignore the action before # resetting the environment. We need to pass in `terminal=False` here since # the *next* state, that is the state of the newly reset environment, is # always non-terminal by convention. self.forward(observation) self.backward(0., terminal=False) # This episode is finished, report and reset. episode_logs = { 'episode_reward': episode_reward, 'nb_episode_steps': episode_step, 'nb_steps': self.step, } callbacks.on_episode_end(episode, episode_logs) episode += 1 observation = None episode_step = None episode_reward = None except KeyboardInterrupt: # We catch keyboard interrupts here so that training can be be safely aborted. # This is so common that we've built this right into this function, which ensures that # the `on_train_end` method is properly called. did_abort = True callbacks.on_train_end(logs={'did_abort': did_abort}) self._on_train_end() return history
python
def fit(self, env, nb_steps, action_repetition=1, callbacks=None, verbose=1, visualize=False, nb_max_start_steps=0, start_step_policy=None, log_interval=10000, nb_max_episode_steps=None): """Trains the agent on the given environment. # Arguments env: (`Env` instance): Environment that the agent interacts with. See [Env](#env) for details. nb_steps (integer): Number of training steps to be performed. action_repetition (integer): Number of times the agent repeats the same action without observing the environment again. Setting this to a value > 1 can be useful if a single action only has a very small effect on the environment. callbacks (list of `keras.callbacks.Callback` or `rl.callbacks.Callback` instances): List of callbacks to apply during training. See [callbacks](/callbacks) for details. verbose (integer): 0 for no logging, 1 for interval logging (compare `log_interval`), 2 for episode logging visualize (boolean): If `True`, the environment is visualized during training. However, this is likely going to slow down training significantly and is thus intended to be a debugging instrument. nb_max_start_steps (integer): Number of maximum steps that the agent performs at the beginning of each episode using `start_step_policy`. Notice that this is an upper limit since the exact number of steps to be performed is sampled uniformly from [0, max_start_steps] at the beginning of each episode. start_step_policy (`lambda observation: action`): The policy to follow if `nb_max_start_steps` > 0. If set to `None`, a random action is performed. log_interval (integer): If `verbose` = 1, the number of steps that are considered to be an interval. nb_max_episode_steps (integer): Number of steps per episode that the agent performs before automatically resetting the environment. Set to `None` if each episode should run (potentially indefinitely) until the environment signals a terminal state. # Returns A `keras.callbacks.History` instance that recorded the entire training process. """ if not self.compiled: raise RuntimeError('Your tried to fit your agent but it hasn\'t been compiled yet. Please call `compile()` before `fit()`.') if action_repetition < 1: raise ValueError('action_repetition must be >= 1, is {}'.format(action_repetition)) self.training = True callbacks = [] if not callbacks else callbacks[:] if verbose == 1: callbacks += [TrainIntervalLogger(interval=log_interval)] elif verbose > 1: callbacks += [TrainEpisodeLogger()] if visualize: callbacks += [Visualizer()] history = History() callbacks += [history] callbacks = CallbackList(callbacks) if hasattr(callbacks, 'set_model'): callbacks.set_model(self) else: callbacks._set_model(self) callbacks._set_env(env) params = { 'nb_steps': nb_steps, } if hasattr(callbacks, 'set_params'): callbacks.set_params(params) else: callbacks._set_params(params) self._on_train_begin() callbacks.on_train_begin() episode = np.int16(0) self.step = np.int16(0) observation = None episode_reward = None episode_step = None did_abort = False try: while self.step < nb_steps: if observation is None: # start of a new episode callbacks.on_episode_begin(episode) episode_step = np.int16(0) episode_reward = np.float32(0) # Obtain the initial observation by resetting the environment. self.reset_states() observation = deepcopy(env.reset()) if self.processor is not None: observation = self.processor.process_observation(observation) assert observation is not None # Perform random starts at beginning of episode and do not record them into the experience. # This slightly changes the start position between games. nb_random_start_steps = 0 if nb_max_start_steps == 0 else np.random.randint(nb_max_start_steps) for _ in range(nb_random_start_steps): if start_step_policy is None: action = env.action_space.sample() else: action = start_step_policy(observation) if self.processor is not None: action = self.processor.process_action(action) callbacks.on_action_begin(action) observation, reward, done, info = env.step(action) observation = deepcopy(observation) if self.processor is not None: observation, reward, done, info = self.processor.process_step(observation, reward, done, info) callbacks.on_action_end(action) if done: warnings.warn('Env ended before {} random steps could be performed at the start. You should probably lower the `nb_max_start_steps` parameter.'.format(nb_random_start_steps)) observation = deepcopy(env.reset()) if self.processor is not None: observation = self.processor.process_observation(observation) break # At this point, we expect to be fully initialized. assert episode_reward is not None assert episode_step is not None assert observation is not None # Run a single step. callbacks.on_step_begin(episode_step) # This is were all of the work happens. We first perceive and compute the action # (forward step) and then use the reward to improve (backward step). action = self.forward(observation) if self.processor is not None: action = self.processor.process_action(action) reward = np.float32(0) accumulated_info = {} done = False for _ in range(action_repetition): callbacks.on_action_begin(action) observation, r, done, info = env.step(action) observation = deepcopy(observation) if self.processor is not None: observation, r, done, info = self.processor.process_step(observation, r, done, info) for key, value in info.items(): if not np.isreal(value): continue if key not in accumulated_info: accumulated_info[key] = np.zeros_like(value) accumulated_info[key] += value callbacks.on_action_end(action) reward += r if done: break if nb_max_episode_steps and episode_step >= nb_max_episode_steps - 1: # Force a terminal state. done = True metrics = self.backward(reward, terminal=done) episode_reward += reward step_logs = { 'action': action, 'observation': observation, 'reward': reward, 'metrics': metrics, 'episode': episode, 'info': accumulated_info, } callbacks.on_step_end(episode_step, step_logs) episode_step += 1 self.step += 1 if done: # We are in a terminal state but the agent hasn't yet seen it. We therefore # perform one more forward-backward call and simply ignore the action before # resetting the environment. We need to pass in `terminal=False` here since # the *next* state, that is the state of the newly reset environment, is # always non-terminal by convention. self.forward(observation) self.backward(0., terminal=False) # This episode is finished, report and reset. episode_logs = { 'episode_reward': episode_reward, 'nb_episode_steps': episode_step, 'nb_steps': self.step, } callbacks.on_episode_end(episode, episode_logs) episode += 1 observation = None episode_step = None episode_reward = None except KeyboardInterrupt: # We catch keyboard interrupts here so that training can be be safely aborted. # This is so common that we've built this right into this function, which ensures that # the `on_train_end` method is properly called. did_abort = True callbacks.on_train_end(logs={'did_abort': did_abort}) self._on_train_end() return history
[ "def", "fit", "(", "self", ",", "env", ",", "nb_steps", ",", "action_repetition", "=", "1", ",", "callbacks", "=", "None", ",", "verbose", "=", "1", ",", "visualize", "=", "False", ",", "nb_max_start_steps", "=", "0", ",", "start_step_policy", "=", "None", ",", "log_interval", "=", "10000", ",", "nb_max_episode_steps", "=", "None", ")", ":", "if", "not", "self", ".", "compiled", ":", "raise", "RuntimeError", "(", "'Your tried to fit your agent but it hasn\\'t been compiled yet. Please call `compile()` before `fit()`.'", ")", "if", "action_repetition", "<", "1", ":", "raise", "ValueError", "(", "'action_repetition must be >= 1, is {}'", ".", "format", "(", "action_repetition", ")", ")", "self", ".", "training", "=", "True", "callbacks", "=", "[", "]", "if", "not", "callbacks", "else", "callbacks", "[", ":", "]", "if", "verbose", "==", "1", ":", "callbacks", "+=", "[", "TrainIntervalLogger", "(", "interval", "=", "log_interval", ")", "]", "elif", "verbose", ">", "1", ":", "callbacks", "+=", "[", "TrainEpisodeLogger", "(", ")", "]", "if", "visualize", ":", "callbacks", "+=", "[", "Visualizer", "(", ")", "]", "history", "=", "History", "(", ")", "callbacks", "+=", "[", "history", "]", "callbacks", "=", "CallbackList", "(", "callbacks", ")", "if", "hasattr", "(", "callbacks", ",", "'set_model'", ")", ":", "callbacks", ".", "set_model", "(", "self", ")", "else", ":", "callbacks", ".", "_set_model", "(", "self", ")", "callbacks", ".", "_set_env", "(", "env", ")", "params", "=", "{", "'nb_steps'", ":", "nb_steps", ",", "}", "if", "hasattr", "(", "callbacks", ",", "'set_params'", ")", ":", "callbacks", ".", "set_params", "(", "params", ")", "else", ":", "callbacks", ".", "_set_params", "(", "params", ")", "self", ".", "_on_train_begin", "(", ")", "callbacks", ".", "on_train_begin", "(", ")", "episode", "=", "np", ".", "int16", "(", "0", ")", "self", ".", "step", "=", "np", ".", "int16", "(", "0", ")", "observation", "=", "None", "episode_reward", "=", "None", "episode_step", "=", "None", "did_abort", "=", "False", "try", ":", "while", "self", ".", "step", "<", "nb_steps", ":", "if", "observation", "is", "None", ":", "# start of a new episode", "callbacks", ".", "on_episode_begin", "(", "episode", ")", "episode_step", "=", "np", ".", "int16", "(", "0", ")", "episode_reward", "=", "np", ".", "float32", "(", "0", ")", "# Obtain the initial observation by resetting the environment.", "self", ".", "reset_states", "(", ")", "observation", "=", "deepcopy", "(", "env", ".", "reset", "(", ")", ")", "if", "self", ".", "processor", "is", "not", "None", ":", "observation", "=", "self", ".", "processor", ".", "process_observation", "(", "observation", ")", "assert", "observation", "is", "not", "None", "# Perform random starts at beginning of episode and do not record them into the experience.", "# This slightly changes the start position between games.", "nb_random_start_steps", "=", "0", "if", "nb_max_start_steps", "==", "0", "else", "np", ".", "random", ".", "randint", "(", "nb_max_start_steps", ")", "for", "_", "in", "range", "(", "nb_random_start_steps", ")", ":", "if", "start_step_policy", "is", "None", ":", "action", "=", "env", ".", "action_space", ".", "sample", "(", ")", "else", ":", "action", "=", "start_step_policy", "(", "observation", ")", "if", "self", ".", "processor", "is", "not", "None", ":", "action", "=", "self", ".", "processor", ".", "process_action", "(", "action", ")", "callbacks", ".", "on_action_begin", "(", "action", ")", "observation", ",", "reward", ",", "done", ",", "info", "=", "env", ".", "step", "(", "action", ")", "observation", "=", "deepcopy", "(", "observation", ")", "if", "self", ".", "processor", "is", "not", "None", ":", "observation", ",", "reward", ",", "done", ",", "info", "=", "self", ".", "processor", ".", "process_step", "(", "observation", ",", "reward", ",", "done", ",", "info", ")", "callbacks", ".", "on_action_end", "(", "action", ")", "if", "done", ":", "warnings", ".", "warn", "(", "'Env ended before {} random steps could be performed at the start. You should probably lower the `nb_max_start_steps` parameter.'", ".", "format", "(", "nb_random_start_steps", ")", ")", "observation", "=", "deepcopy", "(", "env", ".", "reset", "(", ")", ")", "if", "self", ".", "processor", "is", "not", "None", ":", "observation", "=", "self", ".", "processor", ".", "process_observation", "(", "observation", ")", "break", "# At this point, we expect to be fully initialized.", "assert", "episode_reward", "is", "not", "None", "assert", "episode_step", "is", "not", "None", "assert", "observation", "is", "not", "None", "# Run a single step.", "callbacks", ".", "on_step_begin", "(", "episode_step", ")", "# This is were all of the work happens. We first perceive and compute the action", "# (forward step) and then use the reward to improve (backward step).", "action", "=", "self", ".", "forward", "(", "observation", ")", "if", "self", ".", "processor", "is", "not", "None", ":", "action", "=", "self", ".", "processor", ".", "process_action", "(", "action", ")", "reward", "=", "np", ".", "float32", "(", "0", ")", "accumulated_info", "=", "{", "}", "done", "=", "False", "for", "_", "in", "range", "(", "action_repetition", ")", ":", "callbacks", ".", "on_action_begin", "(", "action", ")", "observation", ",", "r", ",", "done", ",", "info", "=", "env", ".", "step", "(", "action", ")", "observation", "=", "deepcopy", "(", "observation", ")", "if", "self", ".", "processor", "is", "not", "None", ":", "observation", ",", "r", ",", "done", ",", "info", "=", "self", ".", "processor", ".", "process_step", "(", "observation", ",", "r", ",", "done", ",", "info", ")", "for", "key", ",", "value", "in", "info", ".", "items", "(", ")", ":", "if", "not", "np", ".", "isreal", "(", "value", ")", ":", "continue", "if", "key", "not", "in", "accumulated_info", ":", "accumulated_info", "[", "key", "]", "=", "np", ".", "zeros_like", "(", "value", ")", "accumulated_info", "[", "key", "]", "+=", "value", "callbacks", ".", "on_action_end", "(", "action", ")", "reward", "+=", "r", "if", "done", ":", "break", "if", "nb_max_episode_steps", "and", "episode_step", ">=", "nb_max_episode_steps", "-", "1", ":", "# Force a terminal state.", "done", "=", "True", "metrics", "=", "self", ".", "backward", "(", "reward", ",", "terminal", "=", "done", ")", "episode_reward", "+=", "reward", "step_logs", "=", "{", "'action'", ":", "action", ",", "'observation'", ":", "observation", ",", "'reward'", ":", "reward", ",", "'metrics'", ":", "metrics", ",", "'episode'", ":", "episode", ",", "'info'", ":", "accumulated_info", ",", "}", "callbacks", ".", "on_step_end", "(", "episode_step", ",", "step_logs", ")", "episode_step", "+=", "1", "self", ".", "step", "+=", "1", "if", "done", ":", "# We are in a terminal state but the agent hasn't yet seen it. We therefore", "# perform one more forward-backward call and simply ignore the action before", "# resetting the environment. We need to pass in `terminal=False` here since", "# the *next* state, that is the state of the newly reset environment, is", "# always non-terminal by convention.", "self", ".", "forward", "(", "observation", ")", "self", ".", "backward", "(", "0.", ",", "terminal", "=", "False", ")", "# This episode is finished, report and reset.", "episode_logs", "=", "{", "'episode_reward'", ":", "episode_reward", ",", "'nb_episode_steps'", ":", "episode_step", ",", "'nb_steps'", ":", "self", ".", "step", ",", "}", "callbacks", ".", "on_episode_end", "(", "episode", ",", "episode_logs", ")", "episode", "+=", "1", "observation", "=", "None", "episode_step", "=", "None", "episode_reward", "=", "None", "except", "KeyboardInterrupt", ":", "# We catch keyboard interrupts here so that training can be be safely aborted.", "# This is so common that we've built this right into this function, which ensures that", "# the `on_train_end` method is properly called.", "did_abort", "=", "True", "callbacks", ".", "on_train_end", "(", "logs", "=", "{", "'did_abort'", ":", "did_abort", "}", ")", "self", ".", "_on_train_end", "(", ")", "return", "history" ]
Trains the agent on the given environment. # Arguments env: (`Env` instance): Environment that the agent interacts with. See [Env](#env) for details. nb_steps (integer): Number of training steps to be performed. action_repetition (integer): Number of times the agent repeats the same action without observing the environment again. Setting this to a value > 1 can be useful if a single action only has a very small effect on the environment. callbacks (list of `keras.callbacks.Callback` or `rl.callbacks.Callback` instances): List of callbacks to apply during training. See [callbacks](/callbacks) for details. verbose (integer): 0 for no logging, 1 for interval logging (compare `log_interval`), 2 for episode logging visualize (boolean): If `True`, the environment is visualized during training. However, this is likely going to slow down training significantly and is thus intended to be a debugging instrument. nb_max_start_steps (integer): Number of maximum steps that the agent performs at the beginning of each episode using `start_step_policy`. Notice that this is an upper limit since the exact number of steps to be performed is sampled uniformly from [0, max_start_steps] at the beginning of each episode. start_step_policy (`lambda observation: action`): The policy to follow if `nb_max_start_steps` > 0. If set to `None`, a random action is performed. log_interval (integer): If `verbose` = 1, the number of steps that are considered to be an interval. nb_max_episode_steps (integer): Number of steps per episode that the agent performs before automatically resetting the environment. Set to `None` if each episode should run (potentially indefinitely) until the environment signals a terminal state. # Returns A `keras.callbacks.History` instance that recorded the entire training process.
[ "Trains", "the", "agent", "on", "the", "given", "environment", "." ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/core.py#L53-L238
train
keras-rl/keras-rl
rl/core.py
Processor.process_step
def process_step(self, observation, reward, done, info): """Processes an entire step by applying the processor to the observation, reward, and info arguments. # Arguments observation (object): An observation as obtained by the environment. reward (float): A reward as obtained by the environment. done (boolean): `True` if the environment is in a terminal state, `False` otherwise. info (dict): The debug info dictionary as obtained by the environment. # Returns The tupel (observation, reward, done, reward) with with all elements after being processed. """ observation = self.process_observation(observation) reward = self.process_reward(reward) info = self.process_info(info) return observation, reward, done, info
python
def process_step(self, observation, reward, done, info): """Processes an entire step by applying the processor to the observation, reward, and info arguments. # Arguments observation (object): An observation as obtained by the environment. reward (float): A reward as obtained by the environment. done (boolean): `True` if the environment is in a terminal state, `False` otherwise. info (dict): The debug info dictionary as obtained by the environment. # Returns The tupel (observation, reward, done, reward) with with all elements after being processed. """ observation = self.process_observation(observation) reward = self.process_reward(reward) info = self.process_info(info) return observation, reward, done, info
[ "def", "process_step", "(", "self", ",", "observation", ",", "reward", ",", "done", ",", "info", ")", ":", "observation", "=", "self", ".", "process_observation", "(", "observation", ")", "reward", "=", "self", ".", "process_reward", "(", "reward", ")", "info", "=", "self", ".", "process_info", "(", "info", ")", "return", "observation", ",", "reward", ",", "done", ",", "info" ]
Processes an entire step by applying the processor to the observation, reward, and info arguments. # Arguments observation (object): An observation as obtained by the environment. reward (float): A reward as obtained by the environment. done (boolean): `True` if the environment is in a terminal state, `False` otherwise. info (dict): The debug info dictionary as obtained by the environment. # Returns The tupel (observation, reward, done, reward) with with all elements after being processed.
[ "Processes", "an", "entire", "step", "by", "applying", "the", "processor", "to", "the", "observation", "reward", "and", "info", "arguments", "." ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/core.py#L511-L526
train
keras-rl/keras-rl
rl/policy.py
LinearAnnealedPolicy.get_current_value
def get_current_value(self): """Return current annealing value # Returns Value to use in annealing """ if self.agent.training: # Linear annealed: f(x) = ax + b. a = -float(self.value_max - self.value_min) / float(self.nb_steps) b = float(self.value_max) value = max(self.value_min, a * float(self.agent.step) + b) else: value = self.value_test return value
python
def get_current_value(self): """Return current annealing value # Returns Value to use in annealing """ if self.agent.training: # Linear annealed: f(x) = ax + b. a = -float(self.value_max - self.value_min) / float(self.nb_steps) b = float(self.value_max) value = max(self.value_min, a * float(self.agent.step) + b) else: value = self.value_test return value
[ "def", "get_current_value", "(", "self", ")", ":", "if", "self", ".", "agent", ".", "training", ":", "# Linear annealed: f(x) = ax + b.", "a", "=", "-", "float", "(", "self", ".", "value_max", "-", "self", ".", "value_min", ")", "/", "float", "(", "self", ".", "nb_steps", ")", "b", "=", "float", "(", "self", ".", "value_max", ")", "value", "=", "max", "(", "self", ".", "value_min", ",", "a", "*", "float", "(", "self", ".", "agent", ".", "step", ")", "+", "b", ")", "else", ":", "value", "=", "self", ".", "value_test", "return", "value" ]
Return current annealing value # Returns Value to use in annealing
[ "Return", "current", "annealing", "value" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L62-L75
train
keras-rl/keras-rl
rl/policy.py
LinearAnnealedPolicy.select_action
def select_action(self, **kwargs): """Choose an action to perform # Returns Action to take (int) """ setattr(self.inner_policy, self.attr, self.get_current_value()) return self.inner_policy.select_action(**kwargs)
python
def select_action(self, **kwargs): """Choose an action to perform # Returns Action to take (int) """ setattr(self.inner_policy, self.attr, self.get_current_value()) return self.inner_policy.select_action(**kwargs)
[ "def", "select_action", "(", "self", ",", "*", "*", "kwargs", ")", ":", "setattr", "(", "self", ".", "inner_policy", ",", "self", ".", "attr", ",", "self", ".", "get_current_value", "(", ")", ")", "return", "self", ".", "inner_policy", ".", "select_action", "(", "*", "*", "kwargs", ")" ]
Choose an action to perform # Returns Action to take (int)
[ "Choose", "an", "action", "to", "perform" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L77-L84
train
keras-rl/keras-rl
rl/policy.py
LinearAnnealedPolicy.get_config
def get_config(self): """Return configurations of LinearAnnealedPolicy # Returns Dict of config """ config = super(LinearAnnealedPolicy, self).get_config() config['attr'] = self.attr config['value_max'] = self.value_max config['value_min'] = self.value_min config['value_test'] = self.value_test config['nb_steps'] = self.nb_steps config['inner_policy'] = get_object_config(self.inner_policy) return config
python
def get_config(self): """Return configurations of LinearAnnealedPolicy # Returns Dict of config """ config = super(LinearAnnealedPolicy, self).get_config() config['attr'] = self.attr config['value_max'] = self.value_max config['value_min'] = self.value_min config['value_test'] = self.value_test config['nb_steps'] = self.nb_steps config['inner_policy'] = get_object_config(self.inner_policy) return config
[ "def", "get_config", "(", "self", ")", ":", "config", "=", "super", "(", "LinearAnnealedPolicy", ",", "self", ")", ".", "get_config", "(", ")", "config", "[", "'attr'", "]", "=", "self", ".", "attr", "config", "[", "'value_max'", "]", "=", "self", ".", "value_max", "config", "[", "'value_min'", "]", "=", "self", ".", "value_min", "config", "[", "'value_test'", "]", "=", "self", ".", "value_test", "config", "[", "'nb_steps'", "]", "=", "self", ".", "nb_steps", "config", "[", "'inner_policy'", "]", "=", "get_object_config", "(", "self", ".", "inner_policy", ")", "return", "config" ]
Return configurations of LinearAnnealedPolicy # Returns Dict of config
[ "Return", "configurations", "of", "LinearAnnealedPolicy" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L105-L118
train
keras-rl/keras-rl
rl/policy.py
SoftmaxPolicy.select_action
def select_action(self, nb_actions, probs): """Return the selected action # Arguments probs (np.ndarray) : Probabilty for each action # Returns action """ action = np.random.choice(range(nb_actions), p=probs) return action
python
def select_action(self, nb_actions, probs): """Return the selected action # Arguments probs (np.ndarray) : Probabilty for each action # Returns action """ action = np.random.choice(range(nb_actions), p=probs) return action
[ "def", "select_action", "(", "self", ",", "nb_actions", ",", "probs", ")", ":", "action", "=", "np", ".", "random", ".", "choice", "(", "range", "(", "nb_actions", ")", ",", "p", "=", "probs", ")", "return", "action" ]
Return the selected action # Arguments probs (np.ndarray) : Probabilty for each action # Returns action
[ "Return", "the", "selected", "action" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L128-L139
train
keras-rl/keras-rl
rl/policy.py
EpsGreedyQPolicy.select_action
def select_action(self, q_values): """Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action """ assert q_values.ndim == 1 nb_actions = q_values.shape[0] if np.random.uniform() < self.eps: action = np.random.randint(0, nb_actions) else: action = np.argmax(q_values) return action
python
def select_action(self, q_values): """Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action """ assert q_values.ndim == 1 nb_actions = q_values.shape[0] if np.random.uniform() < self.eps: action = np.random.randint(0, nb_actions) else: action = np.argmax(q_values) return action
[ "def", "select_action", "(", "self", ",", "q_values", ")", ":", "assert", "q_values", ".", "ndim", "==", "1", "nb_actions", "=", "q_values", ".", "shape", "[", "0", "]", "if", "np", ".", "random", ".", "uniform", "(", ")", "<", "self", ".", "eps", ":", "action", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "nb_actions", ")", "else", ":", "action", "=", "np", ".", "argmax", "(", "q_values", ")", "return", "action" ]
Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action
[ "Return", "the", "selected", "action" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L153-L169
train
keras-rl/keras-rl
rl/policy.py
EpsGreedyQPolicy.get_config
def get_config(self): """Return configurations of EpsGreedyQPolicy # Returns Dict of config """ config = super(EpsGreedyQPolicy, self).get_config() config['eps'] = self.eps return config
python
def get_config(self): """Return configurations of EpsGreedyQPolicy # Returns Dict of config """ config = super(EpsGreedyQPolicy, self).get_config() config['eps'] = self.eps return config
[ "def", "get_config", "(", "self", ")", ":", "config", "=", "super", "(", "EpsGreedyQPolicy", ",", "self", ")", ".", "get_config", "(", ")", "config", "[", "'eps'", "]", "=", "self", ".", "eps", "return", "config" ]
Return configurations of EpsGreedyQPolicy # Returns Dict of config
[ "Return", "configurations", "of", "EpsGreedyQPolicy" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L171-L179
train
keras-rl/keras-rl
rl/policy.py
GreedyQPolicy.select_action
def select_action(self, q_values): """Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action """ assert q_values.ndim == 1 action = np.argmax(q_values) return action
python
def select_action(self, q_values): """Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action """ assert q_values.ndim == 1 action = np.argmax(q_values) return action
[ "def", "select_action", "(", "self", ",", "q_values", ")", ":", "assert", "q_values", ".", "ndim", "==", "1", "action", "=", "np", ".", "argmax", "(", "q_values", ")", "return", "action" ]
Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action
[ "Return", "the", "selected", "action" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L187-L198
train
keras-rl/keras-rl
rl/policy.py
BoltzmannQPolicy.get_config
def get_config(self): """Return configurations of BoltzmannQPolicy # Returns Dict of config """ config = super(BoltzmannQPolicy, self).get_config() config['tau'] = self.tau config['clip'] = self.clip return config
python
def get_config(self): """Return configurations of BoltzmannQPolicy # Returns Dict of config """ config = super(BoltzmannQPolicy, self).get_config() config['tau'] = self.tau config['clip'] = self.clip return config
[ "def", "get_config", "(", "self", ")", ":", "config", "=", "super", "(", "BoltzmannQPolicy", ",", "self", ")", ".", "get_config", "(", ")", "config", "[", "'tau'", "]", "=", "self", ".", "tau", "config", "[", "'clip'", "]", "=", "self", ".", "clip", "return", "config" ]
Return configurations of BoltzmannQPolicy # Returns Dict of config
[ "Return", "configurations", "of", "BoltzmannQPolicy" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L230-L239
train
keras-rl/keras-rl
rl/policy.py
MaxBoltzmannQPolicy.select_action
def select_action(self, q_values): """Return the selected action The selected action follows the BoltzmannQPolicy with probability epsilon or return the Greedy Policy with probability (1 - epsilon) # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action """ assert q_values.ndim == 1 q_values = q_values.astype('float64') nb_actions = q_values.shape[0] if np.random.uniform() < self.eps: exp_values = np.exp(np.clip(q_values / self.tau, self.clip[0], self.clip[1])) probs = exp_values / np.sum(exp_values) action = np.random.choice(range(nb_actions), p=probs) else: action = np.argmax(q_values) return action
python
def select_action(self, q_values): """Return the selected action The selected action follows the BoltzmannQPolicy with probability epsilon or return the Greedy Policy with probability (1 - epsilon) # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action """ assert q_values.ndim == 1 q_values = q_values.astype('float64') nb_actions = q_values.shape[0] if np.random.uniform() < self.eps: exp_values = np.exp(np.clip(q_values / self.tau, self.clip[0], self.clip[1])) probs = exp_values / np.sum(exp_values) action = np.random.choice(range(nb_actions), p=probs) else: action = np.argmax(q_values) return action
[ "def", "select_action", "(", "self", ",", "q_values", ")", ":", "assert", "q_values", ".", "ndim", "==", "1", "q_values", "=", "q_values", ".", "astype", "(", "'float64'", ")", "nb_actions", "=", "q_values", ".", "shape", "[", "0", "]", "if", "np", ".", "random", ".", "uniform", "(", ")", "<", "self", ".", "eps", ":", "exp_values", "=", "np", ".", "exp", "(", "np", ".", "clip", "(", "q_values", "/", "self", ".", "tau", ",", "self", ".", "clip", "[", "0", "]", ",", "self", ".", "clip", "[", "1", "]", ")", ")", "probs", "=", "exp_values", "/", "np", ".", "sum", "(", "exp_values", ")", "action", "=", "np", ".", "random", ".", "choice", "(", "range", "(", "nb_actions", ")", ",", "p", "=", "probs", ")", "else", ":", "action", "=", "np", ".", "argmax", "(", "q_values", ")", "return", "action" ]
Return the selected action The selected action follows the BoltzmannQPolicy with probability epsilon or return the Greedy Policy with probability (1 - epsilon) # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action
[ "Return", "the", "selected", "action", "The", "selected", "action", "follows", "the", "BoltzmannQPolicy", "with", "probability", "epsilon", "or", "return", "the", "Greedy", "Policy", "with", "probability", "(", "1", "-", "epsilon", ")" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L257-L278
train
keras-rl/keras-rl
rl/policy.py
MaxBoltzmannQPolicy.get_config
def get_config(self): """Return configurations of MaxBoltzmannQPolicy # Returns Dict of config """ config = super(MaxBoltzmannQPolicy, self).get_config() config['eps'] = self.eps config['tau'] = self.tau config['clip'] = self.clip return config
python
def get_config(self): """Return configurations of MaxBoltzmannQPolicy # Returns Dict of config """ config = super(MaxBoltzmannQPolicy, self).get_config() config['eps'] = self.eps config['tau'] = self.tau config['clip'] = self.clip return config
[ "def", "get_config", "(", "self", ")", ":", "config", "=", "super", "(", "MaxBoltzmannQPolicy", ",", "self", ")", ".", "get_config", "(", ")", "config", "[", "'eps'", "]", "=", "self", ".", "eps", "config", "[", "'tau'", "]", "=", "self", ".", "tau", "config", "[", "'clip'", "]", "=", "self", ".", "clip", "return", "config" ]
Return configurations of MaxBoltzmannQPolicy # Returns Dict of config
[ "Return", "configurations", "of", "MaxBoltzmannQPolicy" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L280-L290
train
keras-rl/keras-rl
rl/policy.py
BoltzmannGumbelQPolicy.select_action
def select_action(self, q_values): """Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action """ # We can't use BGE during testing, since we don't have access to the # action_counts at the end of training. assert self.agent.training, "BoltzmannGumbelQPolicy should only be used for training, not testing" assert q_values.ndim == 1, q_values.ndim q_values = q_values.astype('float64') # If we are starting training, we should reset the action_counts. # Otherwise, action_counts should already be initialized, since we # always do so when we begin training. if self.agent.step == 0: self.action_counts = np.ones(q_values.shape) assert self.action_counts is not None, self.agent.step assert self.action_counts.shape == q_values.shape, (self.action_counts.shape, q_values.shape) beta = self.C/np.sqrt(self.action_counts) Z = np.random.gumbel(size=q_values.shape) perturbation = beta * Z perturbed_q_values = q_values + perturbation action = np.argmax(perturbed_q_values) self.action_counts[action] += 1 return action
python
def select_action(self, q_values): """Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action """ # We can't use BGE during testing, since we don't have access to the # action_counts at the end of training. assert self.agent.training, "BoltzmannGumbelQPolicy should only be used for training, not testing" assert q_values.ndim == 1, q_values.ndim q_values = q_values.astype('float64') # If we are starting training, we should reset the action_counts. # Otherwise, action_counts should already be initialized, since we # always do so when we begin training. if self.agent.step == 0: self.action_counts = np.ones(q_values.shape) assert self.action_counts is not None, self.agent.step assert self.action_counts.shape == q_values.shape, (self.action_counts.shape, q_values.shape) beta = self.C/np.sqrt(self.action_counts) Z = np.random.gumbel(size=q_values.shape) perturbation = beta * Z perturbed_q_values = q_values + perturbation action = np.argmax(perturbed_q_values) self.action_counts[action] += 1 return action
[ "def", "select_action", "(", "self", ",", "q_values", ")", ":", "# We can't use BGE during testing, since we don't have access to the", "# action_counts at the end of training.", "assert", "self", ".", "agent", ".", "training", ",", "\"BoltzmannGumbelQPolicy should only be used for training, not testing\"", "assert", "q_values", ".", "ndim", "==", "1", ",", "q_values", ".", "ndim", "q_values", "=", "q_values", ".", "astype", "(", "'float64'", ")", "# If we are starting training, we should reset the action_counts.", "# Otherwise, action_counts should already be initialized, since we", "# always do so when we begin training.", "if", "self", ".", "agent", ".", "step", "==", "0", ":", "self", ".", "action_counts", "=", "np", ".", "ones", "(", "q_values", ".", "shape", ")", "assert", "self", ".", "action_counts", "is", "not", "None", ",", "self", ".", "agent", ".", "step", "assert", "self", ".", "action_counts", ".", "shape", "==", "q_values", ".", "shape", ",", "(", "self", ".", "action_counts", ".", "shape", ",", "q_values", ".", "shape", ")", "beta", "=", "self", ".", "C", "/", "np", ".", "sqrt", "(", "self", ".", "action_counts", ")", "Z", "=", "np", ".", "random", ".", "gumbel", "(", "size", "=", "q_values", ".", "shape", ")", "perturbation", "=", "beta", "*", "Z", "perturbed_q_values", "=", "q_values", "+", "perturbation", "action", "=", "np", ".", "argmax", "(", "perturbed_q_values", ")", "self", ".", "action_counts", "[", "action", "]", "+=", "1", "return", "action" ]
Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action
[ "Return", "the", "selected", "action" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L314-L346
train
keras-rl/keras-rl
rl/policy.py
BoltzmannGumbelQPolicy.get_config
def get_config(self): """Return configurations of BoltzmannGumbelQPolicy # Returns Dict of config """ config = super(BoltzmannGumbelQPolicy, self).get_config() config['C'] = self.C return config
python
def get_config(self): """Return configurations of BoltzmannGumbelQPolicy # Returns Dict of config """ config = super(BoltzmannGumbelQPolicy, self).get_config() config['C'] = self.C return config
[ "def", "get_config", "(", "self", ")", ":", "config", "=", "super", "(", "BoltzmannGumbelQPolicy", ",", "self", ")", ".", "get_config", "(", ")", "config", "[", "'C'", "]", "=", "self", ".", "C", "return", "config" ]
Return configurations of BoltzmannGumbelQPolicy # Returns Dict of config
[ "Return", "configurations", "of", "BoltzmannGumbelQPolicy" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L348-L356
train
keras-rl/keras-rl
rl/callbacks.py
CallbackList._set_env
def _set_env(self, env): """ Set environment for each callback in callbackList """ for callback in self.callbacks: if callable(getattr(callback, '_set_env', None)): callback._set_env(env)
python
def _set_env(self, env): """ Set environment for each callback in callbackList """ for callback in self.callbacks: if callable(getattr(callback, '_set_env', None)): callback._set_env(env)
[ "def", "_set_env", "(", "self", ",", "env", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "if", "callable", "(", "getattr", "(", "callback", ",", "'_set_env'", ",", "None", ")", ")", ":", "callback", ".", "_set_env", "(", "env", ")" ]
Set environment for each callback in callbackList
[ "Set", "environment", "for", "each", "callback", "in", "callbackList" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L45-L49
train
keras-rl/keras-rl
rl/callbacks.py
CallbackList.on_episode_begin
def on_episode_begin(self, episode, logs={}): """ Called at beginning of each episode for each callback in callbackList""" for callback in self.callbacks: # Check if callback supports the more appropriate `on_episode_begin` callback. # If not, fall back to `on_epoch_begin` to be compatible with built-in Keras callbacks. if callable(getattr(callback, 'on_episode_begin', None)): callback.on_episode_begin(episode, logs=logs) else: callback.on_epoch_begin(episode, logs=logs)
python
def on_episode_begin(self, episode, logs={}): """ Called at beginning of each episode for each callback in callbackList""" for callback in self.callbacks: # Check if callback supports the more appropriate `on_episode_begin` callback. # If not, fall back to `on_epoch_begin` to be compatible with built-in Keras callbacks. if callable(getattr(callback, 'on_episode_begin', None)): callback.on_episode_begin(episode, logs=logs) else: callback.on_epoch_begin(episode, logs=logs)
[ "def", "on_episode_begin", "(", "self", ",", "episode", ",", "logs", "=", "{", "}", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "# Check if callback supports the more appropriate `on_episode_begin` callback.", "# If not, fall back to `on_epoch_begin` to be compatible with built-in Keras callbacks.", "if", "callable", "(", "getattr", "(", "callback", ",", "'on_episode_begin'", ",", "None", ")", ")", ":", "callback", ".", "on_episode_begin", "(", "episode", ",", "logs", "=", "logs", ")", "else", ":", "callback", ".", "on_epoch_begin", "(", "episode", ",", "logs", "=", "logs", ")" ]
Called at beginning of each episode for each callback in callbackList
[ "Called", "at", "beginning", "of", "each", "episode", "for", "each", "callback", "in", "callbackList" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L51-L59
train
keras-rl/keras-rl
rl/callbacks.py
CallbackList.on_episode_end
def on_episode_end(self, episode, logs={}): """ Called at end of each episode for each callback in callbackList""" for callback in self.callbacks: # Check if callback supports the more appropriate `on_episode_end` callback. # If not, fall back to `on_epoch_end` to be compatible with built-in Keras callbacks. if callable(getattr(callback, 'on_episode_end', None)): callback.on_episode_end(episode, logs=logs) else: callback.on_epoch_end(episode, logs=logs)
python
def on_episode_end(self, episode, logs={}): """ Called at end of each episode for each callback in callbackList""" for callback in self.callbacks: # Check if callback supports the more appropriate `on_episode_end` callback. # If not, fall back to `on_epoch_end` to be compatible with built-in Keras callbacks. if callable(getattr(callback, 'on_episode_end', None)): callback.on_episode_end(episode, logs=logs) else: callback.on_epoch_end(episode, logs=logs)
[ "def", "on_episode_end", "(", "self", ",", "episode", ",", "logs", "=", "{", "}", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "# Check if callback supports the more appropriate `on_episode_end` callback.", "# If not, fall back to `on_epoch_end` to be compatible with built-in Keras callbacks.", "if", "callable", "(", "getattr", "(", "callback", ",", "'on_episode_end'", ",", "None", ")", ")", ":", "callback", ".", "on_episode_end", "(", "episode", ",", "logs", "=", "logs", ")", "else", ":", "callback", ".", "on_epoch_end", "(", "episode", ",", "logs", "=", "logs", ")" ]
Called at end of each episode for each callback in callbackList
[ "Called", "at", "end", "of", "each", "episode", "for", "each", "callback", "in", "callbackList" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L61-L69
train
keras-rl/keras-rl
rl/callbacks.py
CallbackList.on_step_begin
def on_step_begin(self, step, logs={}): """ Called at beginning of each step for each callback in callbackList""" for callback in self.callbacks: # Check if callback supports the more appropriate `on_step_begin` callback. # If not, fall back to `on_batch_begin` to be compatible with built-in Keras callbacks. if callable(getattr(callback, 'on_step_begin', None)): callback.on_step_begin(step, logs=logs) else: callback.on_batch_begin(step, logs=logs)
python
def on_step_begin(self, step, logs={}): """ Called at beginning of each step for each callback in callbackList""" for callback in self.callbacks: # Check if callback supports the more appropriate `on_step_begin` callback. # If not, fall back to `on_batch_begin` to be compatible with built-in Keras callbacks. if callable(getattr(callback, 'on_step_begin', None)): callback.on_step_begin(step, logs=logs) else: callback.on_batch_begin(step, logs=logs)
[ "def", "on_step_begin", "(", "self", ",", "step", ",", "logs", "=", "{", "}", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "# Check if callback supports the more appropriate `on_step_begin` callback.", "# If not, fall back to `on_batch_begin` to be compatible with built-in Keras callbacks.", "if", "callable", "(", "getattr", "(", "callback", ",", "'on_step_begin'", ",", "None", ")", ")", ":", "callback", ".", "on_step_begin", "(", "step", ",", "logs", "=", "logs", ")", "else", ":", "callback", ".", "on_batch_begin", "(", "step", ",", "logs", "=", "logs", ")" ]
Called at beginning of each step for each callback in callbackList
[ "Called", "at", "beginning", "of", "each", "step", "for", "each", "callback", "in", "callbackList" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L71-L79
train
keras-rl/keras-rl
rl/callbacks.py
CallbackList.on_step_end
def on_step_end(self, step, logs={}): """ Called at end of each step for each callback in callbackList""" for callback in self.callbacks: # Check if callback supports the more appropriate `on_step_end` callback. # If not, fall back to `on_batch_end` to be compatible with built-in Keras callbacks. if callable(getattr(callback, 'on_step_end', None)): callback.on_step_end(step, logs=logs) else: callback.on_batch_end(step, logs=logs)
python
def on_step_end(self, step, logs={}): """ Called at end of each step for each callback in callbackList""" for callback in self.callbacks: # Check if callback supports the more appropriate `on_step_end` callback. # If not, fall back to `on_batch_end` to be compatible with built-in Keras callbacks. if callable(getattr(callback, 'on_step_end', None)): callback.on_step_end(step, logs=logs) else: callback.on_batch_end(step, logs=logs)
[ "def", "on_step_end", "(", "self", ",", "step", ",", "logs", "=", "{", "}", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "# Check if callback supports the more appropriate `on_step_end` callback.", "# If not, fall back to `on_batch_end` to be compatible with built-in Keras callbacks.", "if", "callable", "(", "getattr", "(", "callback", ",", "'on_step_end'", ",", "None", ")", ")", ":", "callback", ".", "on_step_end", "(", "step", ",", "logs", "=", "logs", ")", "else", ":", "callback", ".", "on_batch_end", "(", "step", ",", "logs", "=", "logs", ")" ]
Called at end of each step for each callback in callbackList
[ "Called", "at", "end", "of", "each", "step", "for", "each", "callback", "in", "callbackList" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L81-L89
train
keras-rl/keras-rl
rl/callbacks.py
CallbackList.on_action_begin
def on_action_begin(self, action, logs={}): """ Called at beginning of each action for each callback in callbackList""" for callback in self.callbacks: if callable(getattr(callback, 'on_action_begin', None)): callback.on_action_begin(action, logs=logs)
python
def on_action_begin(self, action, logs={}): """ Called at beginning of each action for each callback in callbackList""" for callback in self.callbacks: if callable(getattr(callback, 'on_action_begin', None)): callback.on_action_begin(action, logs=logs)
[ "def", "on_action_begin", "(", "self", ",", "action", ",", "logs", "=", "{", "}", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "if", "callable", "(", "getattr", "(", "callback", ",", "'on_action_begin'", ",", "None", ")", ")", ":", "callback", ".", "on_action_begin", "(", "action", ",", "logs", "=", "logs", ")" ]
Called at beginning of each action for each callback in callbackList
[ "Called", "at", "beginning", "of", "each", "action", "for", "each", "callback", "in", "callbackList" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L91-L95
train
keras-rl/keras-rl
rl/callbacks.py
CallbackList.on_action_end
def on_action_end(self, action, logs={}): """ Called at end of each action for each callback in callbackList""" for callback in self.callbacks: if callable(getattr(callback, 'on_action_end', None)): callback.on_action_end(action, logs=logs)
python
def on_action_end(self, action, logs={}): """ Called at end of each action for each callback in callbackList""" for callback in self.callbacks: if callable(getattr(callback, 'on_action_end', None)): callback.on_action_end(action, logs=logs)
[ "def", "on_action_end", "(", "self", ",", "action", ",", "logs", "=", "{", "}", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "if", "callable", "(", "getattr", "(", "callback", ",", "'on_action_end'", ",", "None", ")", ")", ":", "callback", ".", "on_action_end", "(", "action", ",", "logs", "=", "logs", ")" ]
Called at end of each action for each callback in callbackList
[ "Called", "at", "end", "of", "each", "action", "for", "each", "callback", "in", "callbackList" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L97-L101
train
keras-rl/keras-rl
rl/callbacks.py
TrainEpisodeLogger.on_train_begin
def on_train_begin(self, logs): """ Print training values at beginning of training """ self.train_start = timeit.default_timer() self.metrics_names = self.model.metrics_names print('Training for {} steps ...'.format(self.params['nb_steps']))
python
def on_train_begin(self, logs): """ Print training values at beginning of training """ self.train_start = timeit.default_timer() self.metrics_names = self.model.metrics_names print('Training for {} steps ...'.format(self.params['nb_steps']))
[ "def", "on_train_begin", "(", "self", ",", "logs", ")", ":", "self", ".", "train_start", "=", "timeit", ".", "default_timer", "(", ")", "self", ".", "metrics_names", "=", "self", ".", "model", ".", "metrics_names", "print", "(", "'Training for {} steps ...'", ".", "format", "(", "self", ".", "params", "[", "'nb_steps'", "]", ")", ")" ]
Print training values at beginning of training
[ "Print", "training", "values", "at", "beginning", "of", "training" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L133-L137
train
keras-rl/keras-rl
rl/callbacks.py
TrainEpisodeLogger.on_train_end
def on_train_end(self, logs): """ Print training time at end of training """ duration = timeit.default_timer() - self.train_start print('done, took {:.3f} seconds'.format(duration))
python
def on_train_end(self, logs): """ Print training time at end of training """ duration = timeit.default_timer() - self.train_start print('done, took {:.3f} seconds'.format(duration))
[ "def", "on_train_end", "(", "self", ",", "logs", ")", ":", "duration", "=", "timeit", ".", "default_timer", "(", ")", "-", "self", ".", "train_start", "print", "(", "'done, took {:.3f} seconds'", ".", "format", "(", "duration", ")", ")" ]
Print training time at end of training
[ "Print", "training", "time", "at", "end", "of", "training" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L139-L142
train
keras-rl/keras-rl
rl/callbacks.py
TrainEpisodeLogger.on_episode_begin
def on_episode_begin(self, episode, logs): """ Reset environment variables at beginning of each episode """ self.episode_start[episode] = timeit.default_timer() self.observations[episode] = [] self.rewards[episode] = [] self.actions[episode] = [] self.metrics[episode] = []
python
def on_episode_begin(self, episode, logs): """ Reset environment variables at beginning of each episode """ self.episode_start[episode] = timeit.default_timer() self.observations[episode] = [] self.rewards[episode] = [] self.actions[episode] = [] self.metrics[episode] = []
[ "def", "on_episode_begin", "(", "self", ",", "episode", ",", "logs", ")", ":", "self", ".", "episode_start", "[", "episode", "]", "=", "timeit", ".", "default_timer", "(", ")", "self", ".", "observations", "[", "episode", "]", "=", "[", "]", "self", ".", "rewards", "[", "episode", "]", "=", "[", "]", "self", ".", "actions", "[", "episode", "]", "=", "[", "]", "self", ".", "metrics", "[", "episode", "]", "=", "[", "]" ]
Reset environment variables at beginning of each episode
[ "Reset", "environment", "variables", "at", "beginning", "of", "each", "episode" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L144-L150
train
keras-rl/keras-rl
rl/callbacks.py
TrainEpisodeLogger.on_episode_end
def on_episode_end(self, episode, logs): """ Compute and print training statistics of the episode when done """ duration = timeit.default_timer() - self.episode_start[episode] episode_steps = len(self.observations[episode]) # Format all metrics. metrics = np.array(self.metrics[episode]) metrics_template = '' metrics_variables = [] with warnings.catch_warnings(): warnings.filterwarnings('error') for idx, name in enumerate(self.metrics_names): if idx > 0: metrics_template += ', ' try: value = np.nanmean(metrics[:, idx]) metrics_template += '{}: {:f}' except Warning: value = '--' metrics_template += '{}: {}' metrics_variables += [name, value] metrics_text = metrics_template.format(*metrics_variables) nb_step_digits = str(int(np.ceil(np.log10(self.params['nb_steps']))) + 1) template = '{step: ' + nb_step_digits + 'd}/{nb_steps}: episode: {episode}, duration: {duration:.3f}s, episode steps: {episode_steps}, steps per second: {sps:.0f}, episode reward: {episode_reward:.3f}, mean reward: {reward_mean:.3f} [{reward_min:.3f}, {reward_max:.3f}], mean action: {action_mean:.3f} [{action_min:.3f}, {action_max:.3f}], mean observation: {obs_mean:.3f} [{obs_min:.3f}, {obs_max:.3f}], {metrics}' variables = { 'step': self.step, 'nb_steps': self.params['nb_steps'], 'episode': episode + 1, 'duration': duration, 'episode_steps': episode_steps, 'sps': float(episode_steps) / duration, 'episode_reward': np.sum(self.rewards[episode]), 'reward_mean': np.mean(self.rewards[episode]), 'reward_min': np.min(self.rewards[episode]), 'reward_max': np.max(self.rewards[episode]), 'action_mean': np.mean(self.actions[episode]), 'action_min': np.min(self.actions[episode]), 'action_max': np.max(self.actions[episode]), 'obs_mean': np.mean(self.observations[episode]), 'obs_min': np.min(self.observations[episode]), 'obs_max': np.max(self.observations[episode]), 'metrics': metrics_text, } print(template.format(**variables)) # Free up resources. del self.episode_start[episode] del self.observations[episode] del self.rewards[episode] del self.actions[episode] del self.metrics[episode]
python
def on_episode_end(self, episode, logs): """ Compute and print training statistics of the episode when done """ duration = timeit.default_timer() - self.episode_start[episode] episode_steps = len(self.observations[episode]) # Format all metrics. metrics = np.array(self.metrics[episode]) metrics_template = '' metrics_variables = [] with warnings.catch_warnings(): warnings.filterwarnings('error') for idx, name in enumerate(self.metrics_names): if idx > 0: metrics_template += ', ' try: value = np.nanmean(metrics[:, idx]) metrics_template += '{}: {:f}' except Warning: value = '--' metrics_template += '{}: {}' metrics_variables += [name, value] metrics_text = metrics_template.format(*metrics_variables) nb_step_digits = str(int(np.ceil(np.log10(self.params['nb_steps']))) + 1) template = '{step: ' + nb_step_digits + 'd}/{nb_steps}: episode: {episode}, duration: {duration:.3f}s, episode steps: {episode_steps}, steps per second: {sps:.0f}, episode reward: {episode_reward:.3f}, mean reward: {reward_mean:.3f} [{reward_min:.3f}, {reward_max:.3f}], mean action: {action_mean:.3f} [{action_min:.3f}, {action_max:.3f}], mean observation: {obs_mean:.3f} [{obs_min:.3f}, {obs_max:.3f}], {metrics}' variables = { 'step': self.step, 'nb_steps': self.params['nb_steps'], 'episode': episode + 1, 'duration': duration, 'episode_steps': episode_steps, 'sps': float(episode_steps) / duration, 'episode_reward': np.sum(self.rewards[episode]), 'reward_mean': np.mean(self.rewards[episode]), 'reward_min': np.min(self.rewards[episode]), 'reward_max': np.max(self.rewards[episode]), 'action_mean': np.mean(self.actions[episode]), 'action_min': np.min(self.actions[episode]), 'action_max': np.max(self.actions[episode]), 'obs_mean': np.mean(self.observations[episode]), 'obs_min': np.min(self.observations[episode]), 'obs_max': np.max(self.observations[episode]), 'metrics': metrics_text, } print(template.format(**variables)) # Free up resources. del self.episode_start[episode] del self.observations[episode] del self.rewards[episode] del self.actions[episode] del self.metrics[episode]
[ "def", "on_episode_end", "(", "self", ",", "episode", ",", "logs", ")", ":", "duration", "=", "timeit", ".", "default_timer", "(", ")", "-", "self", ".", "episode_start", "[", "episode", "]", "episode_steps", "=", "len", "(", "self", ".", "observations", "[", "episode", "]", ")", "# Format all metrics.", "metrics", "=", "np", ".", "array", "(", "self", ".", "metrics", "[", "episode", "]", ")", "metrics_template", "=", "''", "metrics_variables", "=", "[", "]", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "filterwarnings", "(", "'error'", ")", "for", "idx", ",", "name", "in", "enumerate", "(", "self", ".", "metrics_names", ")", ":", "if", "idx", ">", "0", ":", "metrics_template", "+=", "', '", "try", ":", "value", "=", "np", ".", "nanmean", "(", "metrics", "[", ":", ",", "idx", "]", ")", "metrics_template", "+=", "'{}: {:f}'", "except", "Warning", ":", "value", "=", "'--'", "metrics_template", "+=", "'{}: {}'", "metrics_variables", "+=", "[", "name", ",", "value", "]", "metrics_text", "=", "metrics_template", ".", "format", "(", "*", "metrics_variables", ")", "nb_step_digits", "=", "str", "(", "int", "(", "np", ".", "ceil", "(", "np", ".", "log10", "(", "self", ".", "params", "[", "'nb_steps'", "]", ")", ")", ")", "+", "1", ")", "template", "=", "'{step: '", "+", "nb_step_digits", "+", "'d}/{nb_steps}: episode: {episode}, duration: {duration:.3f}s, episode steps: {episode_steps}, steps per second: {sps:.0f}, episode reward: {episode_reward:.3f}, mean reward: {reward_mean:.3f} [{reward_min:.3f}, {reward_max:.3f}], mean action: {action_mean:.3f} [{action_min:.3f}, {action_max:.3f}], mean observation: {obs_mean:.3f} [{obs_min:.3f}, {obs_max:.3f}], {metrics}'", "variables", "=", "{", "'step'", ":", "self", ".", "step", ",", "'nb_steps'", ":", "self", ".", "params", "[", "'nb_steps'", "]", ",", "'episode'", ":", "episode", "+", "1", ",", "'duration'", ":", "duration", ",", "'episode_steps'", ":", "episode_steps", ",", "'sps'", ":", "float", "(", "episode_steps", ")", "/", "duration", ",", "'episode_reward'", ":", "np", ".", "sum", "(", "self", ".", "rewards", "[", "episode", "]", ")", ",", "'reward_mean'", ":", "np", ".", "mean", "(", "self", ".", "rewards", "[", "episode", "]", ")", ",", "'reward_min'", ":", "np", ".", "min", "(", "self", ".", "rewards", "[", "episode", "]", ")", ",", "'reward_max'", ":", "np", ".", "max", "(", "self", ".", "rewards", "[", "episode", "]", ")", ",", "'action_mean'", ":", "np", ".", "mean", "(", "self", ".", "actions", "[", "episode", "]", ")", ",", "'action_min'", ":", "np", ".", "min", "(", "self", ".", "actions", "[", "episode", "]", ")", ",", "'action_max'", ":", "np", ".", "max", "(", "self", ".", "actions", "[", "episode", "]", ")", ",", "'obs_mean'", ":", "np", ".", "mean", "(", "self", ".", "observations", "[", "episode", "]", ")", ",", "'obs_min'", ":", "np", ".", "min", "(", "self", ".", "observations", "[", "episode", "]", ")", ",", "'obs_max'", ":", "np", ".", "max", "(", "self", ".", "observations", "[", "episode", "]", ")", ",", "'metrics'", ":", "metrics_text", ",", "}", "print", "(", "template", ".", "format", "(", "*", "*", "variables", ")", ")", "# Free up resources.", "del", "self", ".", "episode_start", "[", "episode", "]", "del", "self", ".", "observations", "[", "episode", "]", "del", "self", ".", "rewards", "[", "episode", "]", "del", "self", ".", "actions", "[", "episode", "]", "del", "self", ".", "metrics", "[", "episode", "]" ]
Compute and print training statistics of the episode when done
[ "Compute", "and", "print", "training", "statistics", "of", "the", "episode", "when", "done" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L152-L203
train
keras-rl/keras-rl
rl/callbacks.py
TrainEpisodeLogger.on_step_end
def on_step_end(self, step, logs): """ Update statistics of episode after each step """ episode = logs['episode'] self.observations[episode].append(logs['observation']) self.rewards[episode].append(logs['reward']) self.actions[episode].append(logs['action']) self.metrics[episode].append(logs['metrics']) self.step += 1
python
def on_step_end(self, step, logs): """ Update statistics of episode after each step """ episode = logs['episode'] self.observations[episode].append(logs['observation']) self.rewards[episode].append(logs['reward']) self.actions[episode].append(logs['action']) self.metrics[episode].append(logs['metrics']) self.step += 1
[ "def", "on_step_end", "(", "self", ",", "step", ",", "logs", ")", ":", "episode", "=", "logs", "[", "'episode'", "]", "self", ".", "observations", "[", "episode", "]", ".", "append", "(", "logs", "[", "'observation'", "]", ")", "self", ".", "rewards", "[", "episode", "]", ".", "append", "(", "logs", "[", "'reward'", "]", ")", "self", ".", "actions", "[", "episode", "]", ".", "append", "(", "logs", "[", "'action'", "]", ")", "self", ".", "metrics", "[", "episode", "]", ".", "append", "(", "logs", "[", "'metrics'", "]", ")", "self", ".", "step", "+=", "1" ]
Update statistics of episode after each step
[ "Update", "statistics", "of", "episode", "after", "each", "step" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L205-L212
train
keras-rl/keras-rl
rl/callbacks.py
TrainIntervalLogger.reset
def reset(self): """ Reset statistics """ self.interval_start = timeit.default_timer() self.progbar = Progbar(target=self.interval) self.metrics = [] self.infos = [] self.info_names = None self.episode_rewards = []
python
def reset(self): """ Reset statistics """ self.interval_start = timeit.default_timer() self.progbar = Progbar(target=self.interval) self.metrics = [] self.infos = [] self.info_names = None self.episode_rewards = []
[ "def", "reset", "(", "self", ")", ":", "self", ".", "interval_start", "=", "timeit", ".", "default_timer", "(", ")", "self", ".", "progbar", "=", "Progbar", "(", "target", "=", "self", ".", "interval", ")", "self", ".", "metrics", "=", "[", "]", "self", ".", "infos", "=", "[", "]", "self", ".", "info_names", "=", "None", "self", ".", "episode_rewards", "=", "[", "]" ]
Reset statistics
[ "Reset", "statistics" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L221-L228
train
keras-rl/keras-rl
rl/callbacks.py
TrainIntervalLogger.on_step_begin
def on_step_begin(self, step, logs): """ Print metrics if interval is over """ if self.step % self.interval == 0: if len(self.episode_rewards) > 0: metrics = np.array(self.metrics) assert metrics.shape == (self.interval, len(self.metrics_names)) formatted_metrics = '' if not np.isnan(metrics).all(): # not all values are means means = np.nanmean(self.metrics, axis=0) assert means.shape == (len(self.metrics_names),) for name, mean in zip(self.metrics_names, means): formatted_metrics += ' - {}: {:.3f}'.format(name, mean) formatted_infos = '' if len(self.infos) > 0: infos = np.array(self.infos) if not np.isnan(infos).all(): # not all values are means means = np.nanmean(self.infos, axis=0) assert means.shape == (len(self.info_names),) for name, mean in zip(self.info_names, means): formatted_infos += ' - {}: {:.3f}'.format(name, mean) print('{} episodes - episode_reward: {:.3f} [{:.3f}, {:.3f}]{}{}'.format(len(self.episode_rewards), np.mean(self.episode_rewards), np.min(self.episode_rewards), np.max(self.episode_rewards), formatted_metrics, formatted_infos)) print('') self.reset() print('Interval {} ({} steps performed)'.format(self.step // self.interval + 1, self.step))
python
def on_step_begin(self, step, logs): """ Print metrics if interval is over """ if self.step % self.interval == 0: if len(self.episode_rewards) > 0: metrics = np.array(self.metrics) assert metrics.shape == (self.interval, len(self.metrics_names)) formatted_metrics = '' if not np.isnan(metrics).all(): # not all values are means means = np.nanmean(self.metrics, axis=0) assert means.shape == (len(self.metrics_names),) for name, mean in zip(self.metrics_names, means): formatted_metrics += ' - {}: {:.3f}'.format(name, mean) formatted_infos = '' if len(self.infos) > 0: infos = np.array(self.infos) if not np.isnan(infos).all(): # not all values are means means = np.nanmean(self.infos, axis=0) assert means.shape == (len(self.info_names),) for name, mean in zip(self.info_names, means): formatted_infos += ' - {}: {:.3f}'.format(name, mean) print('{} episodes - episode_reward: {:.3f} [{:.3f}, {:.3f}]{}{}'.format(len(self.episode_rewards), np.mean(self.episode_rewards), np.min(self.episode_rewards), np.max(self.episode_rewards), formatted_metrics, formatted_infos)) print('') self.reset() print('Interval {} ({} steps performed)'.format(self.step // self.interval + 1, self.step))
[ "def", "on_step_begin", "(", "self", ",", "step", ",", "logs", ")", ":", "if", "self", ".", "step", "%", "self", ".", "interval", "==", "0", ":", "if", "len", "(", "self", ".", "episode_rewards", ")", ">", "0", ":", "metrics", "=", "np", ".", "array", "(", "self", ".", "metrics", ")", "assert", "metrics", ".", "shape", "==", "(", "self", ".", "interval", ",", "len", "(", "self", ".", "metrics_names", ")", ")", "formatted_metrics", "=", "''", "if", "not", "np", ".", "isnan", "(", "metrics", ")", ".", "all", "(", ")", ":", "# not all values are means", "means", "=", "np", ".", "nanmean", "(", "self", ".", "metrics", ",", "axis", "=", "0", ")", "assert", "means", ".", "shape", "==", "(", "len", "(", "self", ".", "metrics_names", ")", ",", ")", "for", "name", ",", "mean", "in", "zip", "(", "self", ".", "metrics_names", ",", "means", ")", ":", "formatted_metrics", "+=", "' - {}: {:.3f}'", ".", "format", "(", "name", ",", "mean", ")", "formatted_infos", "=", "''", "if", "len", "(", "self", ".", "infos", ")", ">", "0", ":", "infos", "=", "np", ".", "array", "(", "self", ".", "infos", ")", "if", "not", "np", ".", "isnan", "(", "infos", ")", ".", "all", "(", ")", ":", "# not all values are means", "means", "=", "np", ".", "nanmean", "(", "self", ".", "infos", ",", "axis", "=", "0", ")", "assert", "means", ".", "shape", "==", "(", "len", "(", "self", ".", "info_names", ")", ",", ")", "for", "name", ",", "mean", "in", "zip", "(", "self", ".", "info_names", ",", "means", ")", ":", "formatted_infos", "+=", "' - {}: {:.3f}'", ".", "format", "(", "name", ",", "mean", ")", "print", "(", "'{} episodes - episode_reward: {:.3f} [{:.3f}, {:.3f}]{}{}'", ".", "format", "(", "len", "(", "self", ".", "episode_rewards", ")", ",", "np", ".", "mean", "(", "self", ".", "episode_rewards", ")", ",", "np", ".", "min", "(", "self", ".", "episode_rewards", ")", ",", "np", ".", "max", "(", "self", ".", "episode_rewards", ")", ",", "formatted_metrics", ",", "formatted_infos", ")", ")", "print", "(", "''", ")", "self", ".", "reset", "(", ")", "print", "(", "'Interval {} ({} steps performed)'", ".", "format", "(", "self", ".", "step", "//", "self", ".", "interval", "+", "1", ",", "self", ".", "step", ")", ")" ]
Print metrics if interval is over
[ "Print", "metrics", "if", "interval", "is", "over" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L241-L265
train
keras-rl/keras-rl
rl/callbacks.py
TrainIntervalLogger.on_step_end
def on_step_end(self, step, logs): """ Update progression bar at the end of each step """ if self.info_names is None: self.info_names = logs['info'].keys() values = [('reward', logs['reward'])] if KERAS_VERSION > '2.1.3': self.progbar.update((self.step % self.interval) + 1, values=values) else: self.progbar.update((self.step % self.interval) + 1, values=values, force=True) self.step += 1 self.metrics.append(logs['metrics']) if len(self.info_names) > 0: self.infos.append([logs['info'][k] for k in self.info_names])
python
def on_step_end(self, step, logs): """ Update progression bar at the end of each step """ if self.info_names is None: self.info_names = logs['info'].keys() values = [('reward', logs['reward'])] if KERAS_VERSION > '2.1.3': self.progbar.update((self.step % self.interval) + 1, values=values) else: self.progbar.update((self.step % self.interval) + 1, values=values, force=True) self.step += 1 self.metrics.append(logs['metrics']) if len(self.info_names) > 0: self.infos.append([logs['info'][k] for k in self.info_names])
[ "def", "on_step_end", "(", "self", ",", "step", ",", "logs", ")", ":", "if", "self", ".", "info_names", "is", "None", ":", "self", ".", "info_names", "=", "logs", "[", "'info'", "]", ".", "keys", "(", ")", "values", "=", "[", "(", "'reward'", ",", "logs", "[", "'reward'", "]", ")", "]", "if", "KERAS_VERSION", ">", "'2.1.3'", ":", "self", ".", "progbar", ".", "update", "(", "(", "self", ".", "step", "%", "self", ".", "interval", ")", "+", "1", ",", "values", "=", "values", ")", "else", ":", "self", ".", "progbar", ".", "update", "(", "(", "self", ".", "step", "%", "self", ".", "interval", ")", "+", "1", ",", "values", "=", "values", ",", "force", "=", "True", ")", "self", ".", "step", "+=", "1", "self", ".", "metrics", ".", "append", "(", "logs", "[", "'metrics'", "]", ")", "if", "len", "(", "self", ".", "info_names", ")", ">", "0", ":", "self", ".", "infos", ".", "append", "(", "[", "logs", "[", "'info'", "]", "[", "k", "]", "for", "k", "in", "self", ".", "info_names", "]", ")" ]
Update progression bar at the end of each step
[ "Update", "progression", "bar", "at", "the", "end", "of", "each", "step" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L267-L279
train
keras-rl/keras-rl
rl/callbacks.py
FileLogger.on_episode_begin
def on_episode_begin(self, episode, logs): """ Initialize metrics at the beginning of each episode """ assert episode not in self.metrics assert episode not in self.starts self.metrics[episode] = [] self.starts[episode] = timeit.default_timer()
python
def on_episode_begin(self, episode, logs): """ Initialize metrics at the beginning of each episode """ assert episode not in self.metrics assert episode not in self.starts self.metrics[episode] = [] self.starts[episode] = timeit.default_timer()
[ "def", "on_episode_begin", "(", "self", ",", "episode", ",", "logs", ")", ":", "assert", "episode", "not", "in", "self", ".", "metrics", "assert", "episode", "not", "in", "self", ".", "starts", "self", ".", "metrics", "[", "episode", "]", "=", "[", "]", "self", ".", "starts", "[", "episode", "]", "=", "timeit", ".", "default_timer", "(", ")" ]
Initialize metrics at the beginning of each episode
[ "Initialize", "metrics", "at", "the", "beginning", "of", "each", "episode" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L305-L310
train
keras-rl/keras-rl
rl/callbacks.py
FileLogger.on_episode_end
def on_episode_end(self, episode, logs): """ Compute and print metrics at the end of each episode """ duration = timeit.default_timer() - self.starts[episode] metrics = self.metrics[episode] if np.isnan(metrics).all(): mean_metrics = np.array([np.nan for _ in self.metrics_names]) else: mean_metrics = np.nanmean(metrics, axis=0) assert len(mean_metrics) == len(self.metrics_names) data = list(zip(self.metrics_names, mean_metrics)) data += list(logs.items()) data += [('episode', episode), ('duration', duration)] for key, value in data: if key not in self.data: self.data[key] = [] self.data[key].append(value) if self.interval is not None and episode % self.interval == 0: self.save_data() # Clean up. del self.metrics[episode] del self.starts[episode]
python
def on_episode_end(self, episode, logs): """ Compute and print metrics at the end of each episode """ duration = timeit.default_timer() - self.starts[episode] metrics = self.metrics[episode] if np.isnan(metrics).all(): mean_metrics = np.array([np.nan for _ in self.metrics_names]) else: mean_metrics = np.nanmean(metrics, axis=0) assert len(mean_metrics) == len(self.metrics_names) data = list(zip(self.metrics_names, mean_metrics)) data += list(logs.items()) data += [('episode', episode), ('duration', duration)] for key, value in data: if key not in self.data: self.data[key] = [] self.data[key].append(value) if self.interval is not None and episode % self.interval == 0: self.save_data() # Clean up. del self.metrics[episode] del self.starts[episode]
[ "def", "on_episode_end", "(", "self", ",", "episode", ",", "logs", ")", ":", "duration", "=", "timeit", ".", "default_timer", "(", ")", "-", "self", ".", "starts", "[", "episode", "]", "metrics", "=", "self", ".", "metrics", "[", "episode", "]", "if", "np", ".", "isnan", "(", "metrics", ")", ".", "all", "(", ")", ":", "mean_metrics", "=", "np", ".", "array", "(", "[", "np", ".", "nan", "for", "_", "in", "self", ".", "metrics_names", "]", ")", "else", ":", "mean_metrics", "=", "np", ".", "nanmean", "(", "metrics", ",", "axis", "=", "0", ")", "assert", "len", "(", "mean_metrics", ")", "==", "len", "(", "self", ".", "metrics_names", ")", "data", "=", "list", "(", "zip", "(", "self", ".", "metrics_names", ",", "mean_metrics", ")", ")", "data", "+=", "list", "(", "logs", ".", "items", "(", ")", ")", "data", "+=", "[", "(", "'episode'", ",", "episode", ")", ",", "(", "'duration'", ",", "duration", ")", "]", "for", "key", ",", "value", "in", "data", ":", "if", "key", "not", "in", "self", ".", "data", ":", "self", ".", "data", "[", "key", "]", "=", "[", "]", "self", ".", "data", "[", "key", "]", ".", "append", "(", "value", ")", "if", "self", ".", "interval", "is", "not", "None", "and", "episode", "%", "self", ".", "interval", "==", "0", ":", "self", ".", "save_data", "(", ")", "# Clean up.", "del", "self", ".", "metrics", "[", "episode", "]", "del", "self", ".", "starts", "[", "episode", "]" ]
Compute and print metrics at the end of each episode
[ "Compute", "and", "print", "metrics", "at", "the", "end", "of", "each", "episode" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L312-L336
train
keras-rl/keras-rl
rl/callbacks.py
FileLogger.save_data
def save_data(self): """ Save metrics in a json file """ if len(self.data.keys()) == 0: return # Sort everything by episode. assert 'episode' in self.data sorted_indexes = np.argsort(self.data['episode']) sorted_data = {} for key, values in self.data.items(): assert len(self.data[key]) == len(sorted_indexes) # We convert to np.array() and then to list to convert from np datatypes to native datatypes. # This is necessary because json.dump cannot handle np.float32, for example. sorted_data[key] = np.array([self.data[key][idx] for idx in sorted_indexes]).tolist() # Overwrite already open file. We can simply seek to the beginning since the file will # grow strictly monotonously. with open(self.filepath, 'w') as f: json.dump(sorted_data, f)
python
def save_data(self): """ Save metrics in a json file """ if len(self.data.keys()) == 0: return # Sort everything by episode. assert 'episode' in self.data sorted_indexes = np.argsort(self.data['episode']) sorted_data = {} for key, values in self.data.items(): assert len(self.data[key]) == len(sorted_indexes) # We convert to np.array() and then to list to convert from np datatypes to native datatypes. # This is necessary because json.dump cannot handle np.float32, for example. sorted_data[key] = np.array([self.data[key][idx] for idx in sorted_indexes]).tolist() # Overwrite already open file. We can simply seek to the beginning since the file will # grow strictly monotonously. with open(self.filepath, 'w') as f: json.dump(sorted_data, f)
[ "def", "save_data", "(", "self", ")", ":", "if", "len", "(", "self", ".", "data", ".", "keys", "(", ")", ")", "==", "0", ":", "return", "# Sort everything by episode.", "assert", "'episode'", "in", "self", ".", "data", "sorted_indexes", "=", "np", ".", "argsort", "(", "self", ".", "data", "[", "'episode'", "]", ")", "sorted_data", "=", "{", "}", "for", "key", ",", "values", "in", "self", ".", "data", ".", "items", "(", ")", ":", "assert", "len", "(", "self", ".", "data", "[", "key", "]", ")", "==", "len", "(", "sorted_indexes", ")", "# We convert to np.array() and then to list to convert from np datatypes to native datatypes.", "# This is necessary because json.dump cannot handle np.float32, for example.", "sorted_data", "[", "key", "]", "=", "np", ".", "array", "(", "[", "self", ".", "data", "[", "key", "]", "[", "idx", "]", "for", "idx", "in", "sorted_indexes", "]", ")", ".", "tolist", "(", ")", "# Overwrite already open file. We can simply seek to the beginning since the file will", "# grow strictly monotonously.", "with", "open", "(", "self", ".", "filepath", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "sorted_data", ",", "f", ")" ]
Save metrics in a json file
[ "Save", "metrics", "in", "a", "json", "file" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L342-L360
train
keras-rl/keras-rl
rl/callbacks.py
ModelIntervalCheckpoint.on_step_end
def on_step_end(self, step, logs={}): """ Save weights at interval steps during training """ self.total_steps += 1 if self.total_steps % self.interval != 0: # Nothing to do. return filepath = self.filepath.format(step=self.total_steps, **logs) if self.verbose > 0: print('Step {}: saving model to {}'.format(self.total_steps, filepath)) self.model.save_weights(filepath, overwrite=True)
python
def on_step_end(self, step, logs={}): """ Save weights at interval steps during training """ self.total_steps += 1 if self.total_steps % self.interval != 0: # Nothing to do. return filepath = self.filepath.format(step=self.total_steps, **logs) if self.verbose > 0: print('Step {}: saving model to {}'.format(self.total_steps, filepath)) self.model.save_weights(filepath, overwrite=True)
[ "def", "on_step_end", "(", "self", ",", "step", ",", "logs", "=", "{", "}", ")", ":", "self", ".", "total_steps", "+=", "1", "if", "self", ".", "total_steps", "%", "self", ".", "interval", "!=", "0", ":", "# Nothing to do.", "return", "filepath", "=", "self", ".", "filepath", ".", "format", "(", "step", "=", "self", ".", "total_steps", ",", "*", "*", "logs", ")", "if", "self", ".", "verbose", ">", "0", ":", "print", "(", "'Step {}: saving model to {}'", ".", "format", "(", "self", ".", "total_steps", ",", "filepath", ")", ")", "self", ".", "model", ".", "save_weights", "(", "filepath", ",", "overwrite", "=", "True", ")" ]
Save weights at interval steps during training
[ "Save", "weights", "at", "interval", "steps", "during", "training" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L377-L387
train
keras-rl/keras-rl
rl/memory.py
sample_batch_indexes
def sample_batch_indexes(low, high, size): """Return a sample of (size) unique elements between low and high # Argument low (int): The minimum value for our samples high (int): The maximum value for our samples size (int): The number of samples to pick # Returns A list of samples of length size, with values between low and high """ if high - low >= size: # We have enough data. Draw without replacement, that is each index is unique in the # batch. We cannot use `np.random.choice` here because it is horribly inefficient as # the memory grows. See https://github.com/numpy/numpy/issues/2764 for a discussion. # `random.sample` does the same thing (drawing without replacement) and is way faster. try: r = xrange(low, high) except NameError: r = range(low, high) batch_idxs = random.sample(r, size) else: # Not enough data. Help ourselves with sampling from the range, but the same index # can occur multiple times. This is not good and should be avoided by picking a # large enough warm-up phase. warnings.warn('Not enough entries to sample without replacement. Consider increasing your warm-up phase to avoid oversampling!') batch_idxs = np.random.random_integers(low, high - 1, size=size) assert len(batch_idxs) == size return batch_idxs
python
def sample_batch_indexes(low, high, size): """Return a sample of (size) unique elements between low and high # Argument low (int): The minimum value for our samples high (int): The maximum value for our samples size (int): The number of samples to pick # Returns A list of samples of length size, with values between low and high """ if high - low >= size: # We have enough data. Draw without replacement, that is each index is unique in the # batch. We cannot use `np.random.choice` here because it is horribly inefficient as # the memory grows. See https://github.com/numpy/numpy/issues/2764 for a discussion. # `random.sample` does the same thing (drawing without replacement) and is way faster. try: r = xrange(low, high) except NameError: r = range(low, high) batch_idxs = random.sample(r, size) else: # Not enough data. Help ourselves with sampling from the range, but the same index # can occur multiple times. This is not good and should be avoided by picking a # large enough warm-up phase. warnings.warn('Not enough entries to sample without replacement. Consider increasing your warm-up phase to avoid oversampling!') batch_idxs = np.random.random_integers(low, high - 1, size=size) assert len(batch_idxs) == size return batch_idxs
[ "def", "sample_batch_indexes", "(", "low", ",", "high", ",", "size", ")", ":", "if", "high", "-", "low", ">=", "size", ":", "# We have enough data. Draw without replacement, that is each index is unique in the", "# batch. We cannot use `np.random.choice` here because it is horribly inefficient as", "# the memory grows. See https://github.com/numpy/numpy/issues/2764 for a discussion.", "# `random.sample` does the same thing (drawing without replacement) and is way faster.", "try", ":", "r", "=", "xrange", "(", "low", ",", "high", ")", "except", "NameError", ":", "r", "=", "range", "(", "low", ",", "high", ")", "batch_idxs", "=", "random", ".", "sample", "(", "r", ",", "size", ")", "else", ":", "# Not enough data. Help ourselves with sampling from the range, but the same index", "# can occur multiple times. This is not good and should be avoided by picking a", "# large enough warm-up phase.", "warnings", ".", "warn", "(", "'Not enough entries to sample without replacement. Consider increasing your warm-up phase to avoid oversampling!'", ")", "batch_idxs", "=", "np", ".", "random", ".", "random_integers", "(", "low", ",", "high", "-", "1", ",", "size", "=", "size", ")", "assert", "len", "(", "batch_idxs", ")", "==", "size", "return", "batch_idxs" ]
Return a sample of (size) unique elements between low and high # Argument low (int): The minimum value for our samples high (int): The maximum value for our samples size (int): The number of samples to pick # Returns A list of samples of length size, with values between low and high
[ "Return", "a", "sample", "of", "(", "size", ")", "unique", "elements", "between", "low", "and", "high" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/memory.py#L14-L42
train
keras-rl/keras-rl
rl/memory.py
zeroed_observation
def zeroed_observation(observation): """Return an array of zeros with same shape as given observation # Argument observation (list): List of observation # Return A np.ndarray of zeros with observation.shape """ if hasattr(observation, 'shape'): return np.zeros(observation.shape) elif hasattr(observation, '__iter__'): out = [] for x in observation: out.append(zeroed_observation(x)) return out else: return 0.
python
def zeroed_observation(observation): """Return an array of zeros with same shape as given observation # Argument observation (list): List of observation # Return A np.ndarray of zeros with observation.shape """ if hasattr(observation, 'shape'): return np.zeros(observation.shape) elif hasattr(observation, '__iter__'): out = [] for x in observation: out.append(zeroed_observation(x)) return out else: return 0.
[ "def", "zeroed_observation", "(", "observation", ")", ":", "if", "hasattr", "(", "observation", ",", "'shape'", ")", ":", "return", "np", ".", "zeros", "(", "observation", ".", "shape", ")", "elif", "hasattr", "(", "observation", ",", "'__iter__'", ")", ":", "out", "=", "[", "]", "for", "x", "in", "observation", ":", "out", ".", "append", "(", "zeroed_observation", "(", "x", ")", ")", "return", "out", "else", ":", "return", "0." ]
Return an array of zeros with same shape as given observation # Argument observation (list): List of observation # Return A np.ndarray of zeros with observation.shape
[ "Return", "an", "array", "of", "zeros", "with", "same", "shape", "as", "given", "observation" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/memory.py#L85-L102
train