text
stringlengths
81
112k
Start xmlrpc interface 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') applic...
Called when a new request is arrived 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) ...
Called when a crawled task is arrived 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') an...
Called when a status pack is arrived 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 pac...
Called when a task is done and success, called by `on_task_status` 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[...
Called when a task is failed, called by `on_task_status` 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 i...
Called when a task is selected to fetch & process 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']) ...
interactive mode of select tasks 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_...
Ignore not processing error in interactive mode 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 Ke...
Build project script as 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 ...
Check if project_name 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'): re...
Check projects by last update time 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: ...
Update one project from database 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)
Load project into self.projects from project info dict 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[...
get project data object, return None if not exists 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_updat...
make cookie python 3 version use this instead of getheaders 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
return a dict 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...
Increment the counter by n (default = 1) def increment(self, n=1): """ Increment the counter by n (default = 1) """ with self.count.get_lock(): self.count.value += n
Explicitly refresh one or more index, making all operations performed since the last refresh available for search. def refresh(self): """ Explicitly refresh one or more index, making all operations performed since the last refresh available for search. """ self._changed ...
Send fetch result to processor 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)
Do one 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:'): t...
Synchronization fetch, usually used in xmlrpc thread 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.Con...
A fake fetcher for dataurl 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...
HTTP fetcher 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...
Fetch with phantomjs proxy 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 ...
Run loop 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(): b...
Quit fetcher 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(...
Run xmlrpc server 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 xml...
Called after task fetched 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) ...
Dump counters as a 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) ...
Set value of a counter by counter key 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 erro...
Clear not used counters def trim(self): """Clear not used counters""" for key, value in list(iteritems(self.counters)): if value.empty(): del self.counters[key]
Dump counters as a 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 _ke...
Dump counters to file 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 F...
Load counters to file 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 ...
A powerful spider system in 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'): ...
Run Scheduler, only one scheduler is allowed. 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.o...
Run 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...
Run 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.fetcher2proces...
Run 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('tes...
Run 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 ...
Run phantomjs fetcher if phantomjs is installed. 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_...
Run puppeteer fetcher if puppeteer is installed. 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_...
Run all the components in subprocess or thread 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...
Run Benchmark test. In bench mode, in-memory sqlite database is used instead of on-disk sqlite database. 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 da...
One mode not only means all-in-one, it runs every thing in one process over tornado.ioloop, for debug purpose 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 """...
Send Message to project from command line 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.g...
Pretty-print a Python object to a stream [default is sys.stdout]. 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(...
Format a Python object into a pretty-printed representation. 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)
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. def format(self, object, context, maxlevels, level): """Format object for a specific context, returning a string ...
Called every 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'], re...
Run loop 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 ...
Called every 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'], re...
Get the number of tokens in bucket 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() ...
Migrate tool for pyspider 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) ...
Encode data to DataURL 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 =...
Decode DataURL data 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 i...
Build the actual URL to use. 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: ...
Quote non-ascii characters 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: ...
Downloads resources from s3 by url and unzips them to the provided path 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 = re...
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...
Adds an accuracy op to the model def AddAccuracy(model, softmax, label): """Adds an accuracy op to the model""" accuracy = brew.accuracy(model, [softmax, label], "accuracy") return accuracy
Adds training operators to the model. 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 AddAc...
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. def AddBookkeepingOperators(model): """This adds a few bookkeeping operators that we can inspect later. These operato...
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 ...
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 ...
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 environm...
Return current annealing value # Returns Value to use in annealing 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...
Choose an action to perform # Returns Action to take (int) 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_pol...
Return configurations of LinearAnnealedPolicy # Returns Dict of config def get_config(self): """Return configurations of LinearAnnealedPolicy # Returns Dict of config """ config = super(LinearAnnealedPolicy, self).get_config() config['attr'] = s...
Return the selected action # Arguments probs (np.ndarray) : Probabilty for each action # Returns action def select_action(self, nb_actions, probs): """Return the selected action # Arguments probs (np.ndarray) : Probabilty for each action #...
Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action def select_action(self, q_values): """Return the selected action # Arguments q_values (np.ndarray): List of the es...
Return configurations of EpsGreedyQPolicy # Returns Dict of config def get_config(self): """Return configurations of EpsGreedyQPolicy # Returns Dict of config """ config = super(EpsGreedyQPolicy, self).get_config() config['eps'] = self.eps ...
Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action def select_action(self, q_values): """Return the selected action # Arguments q_values (np.ndarray): List of the es...
Return configurations of BoltzmannQPolicy # Returns Dict of config def get_config(self): """Return configurations of BoltzmannQPolicy # Returns Dict of config """ config = super(BoltzmannQPolicy, self).get_config() config['tau'] = self.tau ...
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 ac...
Return configurations of MaxBoltzmannQPolicy # Returns Dict of config def get_config(self): """Return configurations of MaxBoltzmannQPolicy # Returns Dict of config """ config = super(MaxBoltzmannQPolicy, self).get_config() config['eps'] = self....
Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action def select_action(self, q_values): """Return the selected action # Arguments q_values (np.ndarray): List of the es...
Return configurations of BoltzmannGumbelQPolicy # Returns Dict of config def get_config(self): """Return configurations of BoltzmannGumbelQPolicy # Returns Dict of config """ config = super(BoltzmannGumbelQPolicy, self).get_config() config['C'] ...
Set environment for each callback in callbackList 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)
Called at beginning of each episode for each callback in callbackList 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_begi...
Called at end of each episode for each callback in callbackList 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. ...
Called at beginning of each step for each callback in callbackList 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. ...
Called at end of each step for each callback in callbackList 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 n...
Called at beginning of each action for each callback in callbackList 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)): ...
Called at end of each action for each callback in callbackList 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_a...
Print training values at beginning of training 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'])...
Print training time at end of training 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))
Reset environment variables at beginning of each episode 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] = [] se...
Compute and print training statistics of the episode when done 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]) ...
Update statistics of episode after each step 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...
Reset statistics 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 = []
Print metrics if interval is over 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(...
Update progression bar at the end of each step 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': ...
Initialize metrics at the beginning of each episode 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] = timei...
Compute and print metrics at the end of each episode 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(): m...
Save metrics in a json file 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 = {} ...
Save weights at interval steps during training 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(st...
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, wit...
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 def zeroed_observation(observation): """Return an array of zeros with same shape as given observation # Argument ...