desc
string
decl
string
bodies
string
'__init__: This has to be present'
def __init__(self):
self.a = 1 def XXX22(): 'XXX22: This has to be present' pass
'XXX22: This has to be present'
def XXX11():
pass
'Remove recursive references to allow garbage collector to collect this object.'
def cleanup(self):
for dict in (self.rule2func, self.rules, self.rule2name): for i in dict.keys(): dict[i] = None for i in dir(self): setattr(self, i, None)
'Disassemble a code object, returning a list of \'Token\'. The main part of this procedure is modelled after dis.disassemble().'
def disassemble(self, co, classname=None, deob=0):
rv = [] customize = {} Token = self.Token self.code = array('B', co.co_code) linestarts = list(dis.findlinestarts(co)) varnames = list(co.co_varnames) if deob: linestarts = self.deobfuscate(co, linestarts, varnames) code = self.code n = len(code) self.prev = [0] for i...
'Find the first <instr> in the block from start to end. <instr> is any python bytecode instruction or a list of opcodes If <instr> is an opcode with a target (like a jump), a target destination can be specified which must match precisely if exact is True, or if exact is False, the instruction which has a target closest...
def first_instr(self, start, end, instr, target=None, exact=True):
code = self.code assert ((start >= 0) and (end <= len(code))) try: (None in instr) except: instr = [instr] pos = None distance = len(code) for i in self.op_range(start, end): op = code[i] if (op in instr): if (target is None): retur...
'Find the last <instr> in the block from start to end. <instr> is any python bytecode instruction or a list of opcodes If <instr> is an opcode with a target (like a jump), a target destination can be specified which must match precisely if exact is True, or if exact is False, the instruction which has a target closest ...
def last_instr(self, start, end, instr, target=None, exact=True):
code = self.code if (not ((start >= 0) and (end <= len(code)))): return None try: (None in instr) except: instr = [instr] pos = None distance = len(code) for i in self.op_range(start, end): op = code[i] if (op in instr): if (target is None)...
'Find all <instr> in the block from start to end. <instr> is any python bytecode instruction or a list of opcodes If <instr> is an opcode with a target (like a jump), a target destination can be specified which must match precisely. Return a list with indexes to them or [] if none found.'
def all_instr(self, start, end, instr, target=None, include_beyond_target=False):
code = self.code assert ((start >= 0) and (end <= len(code))) try: (None in instr) except: instr = [instr] result = [] for i in self.op_range(start, end): op = code[i] if (op in instr): if (target is None): result.append(i) ...
'Find all <instr> in the block from start to end. <instr> is any python bytecode instruction or a list of opcodes If <instr> is an opcode with a target (like a jump), a target destination can be specified which must match precisely. Return a list with indexes to them or [] if none found.'
def rem_or(self, start, end, instr, target=None, include_beyond_target=False):
code = self.code assert ((start >= 0) and (end <= len(code))) try: (None in instr) except: instr = [instr] result = [] for i in self.op_range(start, end): op = code[i] if (op in instr): if (target is None): result.append(i) ...
'Return the next jump that was generated by an except SomeException: construct in a try...except...else clause or None if not found.'
def next_except_jump(self, start):
if (self.code[start] == DUP_TOP): except_match = self.first_instr(start, len(self.code), POP_JUMP_IF_FALSE) if except_match: jmp = self.prev[self.get_target(except_match)] self.ignore_if.add(except_match) self.not_continue.add(jmp) return jmp count...
'Restrict pos to parent boundaries.'
def restrict_to_parent(self, target, parent):
if (not (parent['start'] < target < parent['end'])): target = parent['end'] return target
'Detect structures and their boundaries to fix optimizied jumps in python2.3+'
def detect_structure(self, pos, op=None):
code = self.code if (op is None): op = code[pos] parent = self.structs[0] start = parent['start'] end = parent['end'] for s in self.structs: _start = s['start'] _end = s['end'] if ((_start <= pos < _end) and ((_start >= start) and (_end <= end))): star...
'Detect all offsets in a byte code which are jump targets. Return the list of offsets. This procedure is modelled after dis.findlables(), but here for each target the number of jumps are counted.'
def find_jump_targets(self, code):
hasjrel = dis.hasjrel hasjabs = dis.hasjabs n = len(code) self.structs = [{'type': 'root', 'start': 0, 'end': (n - 1)}] self.loops = [] self.fixed_jumps = {} self.ignore_if = set() self.build_stmt_indices() self.not_continue = set() self.return_end_ifs = set() targets = {} ...
'exec_stmt ::= expr exprlist DUP_TOP EXEC_STMT exec_stmt ::= expr exprlist EXEC_STMT'
def n_exec_stmt(self, node):
self.write(self.indent, 'exec ') self.preorder(node[0]) if (node[1][0] != NONE): sep = ' in ' for subnode in node[1]: self.write(sep) sep = ', ' self.preorder(subnode) self.print_() self.prune()
'prettyprint a mapexpr \'mapexpr\' is something like k = {\'a\': 1, \'b\': 42 }"'
def n_mapexpr(self, node):
p = self.prec self.prec = 100 assert (node[(-1)] == 'kvlist') node = node[(-1)] self.indentMore(INDENT_PER_LEVEL) line_seperator = (',\n' + self.indent) sep = INDENT_PER_LEVEL[:(-1)] self.write('{') for kv in node: assert (kv in ('kv', 'kv2', 'kv3')) if (kv == 'kv'): ...
'prettyprint a list or tuple'
def n_build_list(self, node):
p = self.prec self.prec = 100 lastnode = node.pop() lastnodetype = lastnode.type if lastnodetype.startswith('BUILD_LIST'): self.write('[') endchar = ']' elif lastnodetype.startswith('BUILD_TUPLE'): self.write('(') endchar = ')' elif lastnodetype.startswith('BU...
'Special handling for opcodes that take a variable number of arguments -- we add a new entry for each in TABLE_R.'
def customize(self, customize):
for (k, v) in customize.items(): if TABLE_R.has_key(k): continue op = k[:k.rfind('_')] if (op == 'CALL_FUNCTION'): TABLE_R[k] = ('%c(%P)', 0, (1, (-1), ', ', 100)) elif (op in ('CALL_FUNCTION_VAR', 'CALL_FUNCTION_VAR_KW', 'CALL_FUNCTION_KW')): i...
'If the name of the formal parameter starts with dot, it\'s a tuple parameter, like this: # def MyFunc(xx, (a,b,c), yy): # print a, b*2, c*42 In byte-code, the whole tuple is assigned to parameter \'.1\' and then the tuple gets unpacked to \'a\', \'b\' and \'c\'. Since identifiers starting wit...
def get_tuple_parameter(self, ast, name):
assert (ast == 'stmts') for i in range(len(ast)): assert (ast[i][0] == 'stmt') node = ast[i][0][0] if ((node == 'assign') and (node[0] == ASSIGN_TUPLE_PARAM(name))): del ast[i] assert (node[1] == 'designator') return (('(' + self.traverse(node[1])) + '...
'Dump function defintion, doc string, and function body.'
def make_function(self, node, isLambda, nested=1):
def build_param(ast, name, default): 'build parameters:\n - handle defaults\n - handle format tuple parameters\n '...
'Dump class definition, doc string and class body.'
def build_class(self, code):
assert (type(code) == CodeType) code = Code(code, self.scanner, self.currentclass) indent = self.indent ast = self.build_ast(code._tokens, code._customize) code._tokens = None assert (ast == 'stmts') if (ast[0][0] == NAME_MODULE): del ast[0] if (code.co_consts and (code.co_consts...
'convert AST to source code'
def gen_source(self, ast, customize, isLambda=0, returnNone=False):
rn = self.return_none self.return_none = returnNone if (len(ast) == 0): self.print_(self.indent, 'pass') else: self.customize(customize) if isLambda: self.write(self.traverse(ast, isLambda=isLambda)) else: self.print_(self.traverse(ast, isLambda=is...
'Places new Gmail notifications in the Notifier\'s queue.'
def handleEmailNotifications(self, lastDate):
emails = Gmail.fetchUnreadEmails(self.profile, since=lastDate) if emails: lastDate = Gmail.getMostRecentDate(emails) def styleEmail(e): return ('New email from %s.' % Gmail.getSender(e)) for e in emails: self.q.put(styleEmail(e)) return lastDate
'Returns a notification. Note that this function is consuming.'
def getNotification(self):
try: notif = self.q.get(block=False) return notif except Queue.Empty: return None
'Return a list of notifications in chronological order. Note that this function is consuming, so consecutive calls will yield different results.'
def getAllNotifications(self):
notifs = [] notif = self.getNotification() while notif: notifs.append(notif) notif = self.getNotification() return notifs
'Calculates a revision from phrases by using the SHA1 hash function. Arguments: phrases -- a list of phrases Returns: A revision string for given phrases.'
@classmethod def phrases_to_revision(cls, phrases):
sorted_phrases = sorted(phrases) joined_phrases = '\n'.join(sorted_phrases) sha1 = hashlib.sha1() sha1.update(joined_phrases) return sha1.hexdigest()
'Initializes a new Vocabulary instance. Optional Arguments: name -- (optional) the name of the vocabulary (Default: \'default\') path -- (optional) the path in which the vocabulary exists or will be created (Default: \'.\')'
def __init__(self, name='default', path='.'):
self.name = name self.path = os.path.abspath(os.path.join(path, self.PATH_PREFIX, name)) self._logger = logging.getLogger(__name__)
'Returns: The path of the the revision file as string'
@property def revision_file(self):
return os.path.join(self.path, 'revision')
'Checks if the vocabulary is compiled by checking if the revision file is readable. This method should be overridden by subclasses to check for class-specific additional files, too. Returns: True if the dictionary is compiled, else False'
@abstractproperty def is_compiled(self):
return os.access(self.revision_file, os.R_OK)
'Reads the compiled revision from the revision file. Returns: the revision of this vocabulary (i.e. the string inside the revision file), or None if is_compiled if False'
@property def compiled_revision(self):
if (not self.is_compiled): return None with open(self.revision_file, 'r') as f: revision = f.read().strip() self._logger.debug("compiled_revision is '%s'", revision) return revision
'Convenience method to check if this vocabulary exactly contains the phrases passed to this method. Arguments: phrases -- a list of phrases Returns: True if phrases exactly matches the phrases inside this vocabulary.'
def matches_phrases(self, phrases):
return (self.compiled_revision == self.phrases_to_revision(phrases))
'Compiles this vocabulary. If the force argument is True, compilation will be forced regardless of necessity (which means that the preliminary check if the current revision already equals the revision after compilation will be skipped). This method is not meant to be overridden by subclasses - use the _compile_vocabula...
def compile(self, phrases, force=False):
revision = self.phrases_to_revision(phrases) if ((not force) and (self.compiled_revision == revision)): self._logger.debug(('Compilation not neccessary, compiled ' + 'version matches phrases.')) return revision if (not os.path.exists(self.path)): self._logger.debug(...
'Checks if the vocabulary is compiled by checking if the revision file is readable. Returns: True if this vocabulary has been compiled, else False'
@property def is_compiled(self):
return super(self.__class__, self).is_compiled
'Does nothing (because this is a dummy class for testing purposes).'
def _compile_vocabulary(self, phrases):
pass
'Returns: The path of the the pocketsphinx languagemodel file as string'
@property def languagemodel_file(self):
return os.path.join(self.path, 'languagemodel')
'Returns: The path of the pocketsphinx dictionary file as string'
@property def dictionary_file(self):
return os.path.join(self.path, 'dictionary')
'Checks if the vocabulary is compiled by checking if the revision, languagemodel and dictionary files are readable. Returns: True if this vocabulary has been compiled, else False'
@property def is_compiled(self):
return (super(self.__class__, self).is_compiled and os.access(self.languagemodel_file, os.R_OK) and os.access(self.dictionary_file, os.R_OK))
'Convenience property to use this Vocabulary with the __init__() method of the pocketsphinx.Decoder class. Returns: A dict containing kwargs for the pocketsphinx.Decoder.__init__() method. Example: decoder = pocketsphinx.Decoder(**vocab_instance.decoder_kwargs, hmm=\'/path/to/hmm\')'
@property def decoder_kwargs(self):
return {'lm': self.languagemodel_file, 'dict': self.dictionary_file}
'Compiles the vocabulary to the Pocketsphinx format by creating a languagemodel and a dictionary. Arguments: phrases -- a list of phrases that this vocabulary will contain'
def _compile_vocabulary(self, phrases):
text = ' '.join([('<s> %s </s>' % phrase) for phrase in phrases]) self._logger.debug('Compiling languagemodel...') vocabulary = self._compile_languagemodel(text, self.languagemodel_file) self._logger.debug('Starting dictionary...') self._compile_dictionary(vocabulary, self.dictionary_...
'Compiles the languagemodel from a text. Arguments: text -- the text the languagemodel will be generated from output_file -- the path of the file this languagemodel will be written to Returns: A list of all unique words this vocabulary contains.'
def _compile_languagemodel(self, text, output_file):
with tempfile.NamedTemporaryFile(suffix='.vocab', delete=False) as f: vocab_file = f.name self._logger.debug("Creating vocab file: '%s'", vocab_file) cmuclmtk.text2vocab(text, vocab_file) self._logger.debug("Creating languagemodel file: '%s'", output_file) cmuclmtk.text2lm(...
'Compiles the dictionary from a list of words. Arguments: words -- a list of all unique words this vocabulary contains output_file -- the path of the file this dictionary will be written to'
def _compile_dictionary(self, words, output_file):
self._logger.debug('Getting phonemes for %d words...', len(words)) g2pconverter = PhonetisaurusG2P(**PhonetisaurusG2P.get_config()) phonemes = g2pconverter.translate(words) self._logger.debug("Creating dict file: '%s'", output_file) with open(output_file, 'w') as f: for ...
'Returns: The path of the the julius dfa file as string'
@property def dfa_file(self):
return os.path.join(self.path, 'dfa')
'Returns: The path of the the julius dict file as string'
@property def dict_file(self):
return os.path.join(self.path, 'dict')
'Prepare the client and music variables'
def __init__(self, server='localhost', port=6600):
self.server = server self.port = port self.client = mpd.MPDClient() self.client.timeout = None self.client.idletimeout = None self.client.connect(self.server, self.port) self.playlists = [x['playlist'] for x in self.client.listplaylists()] self.client.clear() for playlist in self.pla...
'Plays the current song or accepts a song to play. Arguments: songs -- a list of song objects playlist_name -- user-defined, something like "Love Song Playlist"'
@reconnect def play(self, songs=False, playlist_name=False):
if songs: self.client.clear() for song in songs: try: self.client.add(song.id) except: pass if playlist_name: self.client.clear() self.client.load(playlist_name) self.client.play()
'Returns the list of unique words that comprise song and artist titles'
def get_soup(self):
soup = [] for song in self.songs: song_words = song.title.split(' ') artist_words = song.artist.split(' ') soup.extend(song_words) soup.extend(artist_words) title_trans = ''.join(((chr(c) if (chr(c).isupper() or chr(c).islower()) else '_') for c in range(256))) soup...
'Returns the list of unique words that comprise playlist names'
def get_soup_playlist(self):
soup = [] for name in self.playlists: soup.extend(name.split(' ')) title_trans = ''.join(((chr(c) if (chr(c).isupper() or chr(c).islower()) else '_') for c in range(256))) soup = [x.decode('utf-8').encode('ascii', 'ignore').upper().translate(title_trans).replace('_', '') for x in soup] so...
'Returns the list of PHRASES that comprise song and artist titles'
def get_soup_separated(self):
title_soup = [song.title for song in self.songs] artist_soup = [song.artist for song in self.songs] soup = list(set((title_soup + artist_soup))) title_trans = ''.join(((chr(c) if (chr(c).isupper() or chr(c).islower()) else '_') for c in range(256))) soup = [x.decode('utf-8').encode('ascii', 'ignore'...
'Returns songs matching a query best as possible on either artist field, etc'
def fuzzy_songs(self, query):
query = query.upper() matched_song_titles = difflib.get_close_matches(query, self.song_titles) matched_song_artists = difflib.get_close_matches(query, self.song_artists) strict_priority_title = [x for x in matched_song_titles if (x == query)] strict_priority_artists = [x for x in matched_song_artist...
'returns playlist names that match query best as possible'
def fuzzy_playlists(self, query):
query = query.upper() lookup = {n.upper(): n for n in self.playlists} results = [lookup[r] for r in difflib.get_close_matches(query, lookup)] return results
'Initiates the pocketsphinx instance. Arguments: speaker -- handles platform-independent audio output passive_stt_engine -- performs STT while Jasper is in passive listen mode acive_stt_engine -- performs STT while Jasper is in active listen mode'
def __init__(self, speaker, passive_stt_engine, active_stt_engine):
self._logger = logging.getLogger(__name__) self.speaker = speaker self.passive_stt_engine = passive_stt_engine self.active_stt_engine = active_stt_engine self._logger.info((('Initializing PyAudio. ALSA/Jack error messages ' + 'that pop up during this process are n...
'Listens for PERSONA in everyday sound. Times out after LISTEN_TIME, so needs to be restarted.'
def passiveListen(self, PERSONA):
THRESHOLD_MULTIPLIER = 1.8 RATE = 16000 CHUNK = 1024 THRESHOLD_TIME = 1 LISTEN_TIME = 10 stream = self._audio.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNK) frames = [] lastN = [i for i in range(30)] for i in range(0, ((RATE / CHUNK) * THRESH...
'Records until a second of silence or times out after 12 seconds Returns the first matching string or None'
def activeListen(self, THRESHOLD=None, LISTEN=True, MUSIC=False):
options = self.activeListenToAllOptions(THRESHOLD, LISTEN, MUSIC) if options: return options[0]
'Records until a second of silence or times out after 12 seconds Returns a list of the matching options or None'
def activeListenToAllOptions(self, THRESHOLD=None, LISTEN=True, MUSIC=False):
RATE = 16000 CHUNK = 1024 LISTEN_TIME = 12 if (THRESHOLD is None): THRESHOLD = self.fetchThreshold() self.speaker.play(jasperpath.data('audio', 'beep_hi.wav')) stream = self._audio.open(format=pyaudio.paInt16, channels=1, rate=RATE, input=True, frames_per_buffer=CHUNK) frames = [] ...
'Delegates user input to the handling function when activated.'
def handleForever(self):
self._logger.info("Starting to handle conversation with keyword '%s'.", self.persona) while True: notifications = self.notifier.getAllNotifications() for notif in notifications: self._logger.info("Received notification: '%s'", str(notif)) self._logger....
'Instantiates a new Brain object, which cross-references user input with a list of modules. Note that the order of brain.modules matters, as the Brain will cease execution on the first module that accepts a given input. Arguments: mic -- used to interact with the user (for both input and output) profile -- contains inf...
def __init__(self, mic, profile):
self.mic = mic self.profile = profile self.modules = self.get_modules() self._logger = logging.getLogger(__name__)
'Dynamically loads all the modules in the modules folder and sorts them by the PRIORITY key. If no PRIORITY is defined for a given module, a priority of 0 is assumed.'
@classmethod def get_modules(cls):
logger = logging.getLogger(__name__) locations = [jasperpath.PLUGIN_PATH] logger.debug('Looking for modules in: %s', ', '.join([("'%s'" % location) for location in locations])) modules = [] for (finder, name, ispkg) in pkgutil.walk_packages(locations): try: loader ...
'Passes user input to the appropriate module, testing it against each candidate module\'s isValid function. Arguments: text -- user input, typically speech, to be parsed by a module'
def query(self, texts):
for module in self.modules: for text in texts: if module.isValid(text): self._logger.debug(("'%s' is a valid phrase for module " + "'%s'"), text, module.__name__) try: module.handle(text, self.mic, self.profile) ...
'Initiates the pocketsphinx instance. Arguments: vocabulary -- a PocketsphinxVocabulary instance hmm_dir -- the path of the Hidden Markov Model (HMM)'
def __init__(self, vocabulary, hmm_dir=('/usr/local/share/' + 'pocketsphinx/model/hmm/en_US/hub4wsj_sc_8k')):
self._logger = logging.getLogger(__name__) try: import pocketsphinx as ps except: import pocketsphinx as ps with tempfile.NamedTemporaryFile(prefix='psdecoder_', suffix='.log', delete=False) as f: self._logfile = f.name self._logger.debug(('Initializing PocketSphinx Dec...
'Performs STT, transcribing an audio file and returning the result. Arguments: fp -- a file object containing audio data'
def transcribe(self, fp):
fp.seek(44) data = fp.read() self._decoder.start_utt() self._decoder.process_raw(data, False, True) self._decoder.end_utt() result = self._decoder.get_hyp() with open(self._logfile, 'r+') as f: for line in f: self._logger.debug(line.strip()) f.truncate() trans...
'Arguments: api_key - the public api key which allows access to Google APIs'
def __init__(self, api_key=None, language='en-us'):
self._logger = logging.getLogger(__name__) self._request_url = None self._language = None self._api_key = None self._http = requests.Session() self.language = language self.api_key = api_key
'Performs STT via the Google Speech API, transcribing an audio file and returning an English string. Arguments: audio_file_path -- the path to the .wav file to be transcribed'
def transcribe(self, fp):
if (not self.api_key): self._logger.critical(('API key missing, transcription request ' + 'aborted.')) return [] elif (not self.language): self._logger.critical(('Language info missing, transcription ' + 'request aborted.')) return [] wav = wave....
'Does Jasper recognize his name (i.e., passive listen)?'
def testTranscribeJasper(self):
with open(self.jasper_clip, mode='rb') as f: transcription = self.passive_stt_engine.transcribe(f) self.assertIn('JASPER', transcription)
'Does Jasper recognize \'time\' (i.e., active listen)?'
def testTranscribe(self):
with open(self.time_clip, mode='rb') as f: transcription = self.active_stt_engine.transcribe(f) self.assertIn('TIME', transcription)
'Does Brain correctly log errors when raised by modules?'
def testLog(self):
my_brain = TestBrain._emptyBrain() unclear = my_brain.modules[(-1)] with mock.patch.object(unclear, 'handle') as mocked_handle: with mock.patch.object(my_brain._logger, 'error') as mocked_log: mocked_handle.side_effect = KeyError('foo') my_brain.query('zzz gibberish zzz...
'Does Brain sort modules by priority?'
def testSortByPriority(self):
my_brain = TestBrain._emptyBrain() priorities = filter((lambda m: hasattr(m, 'PRIORITY')), my_brain.modules) target = sorted(priorities, key=(lambda m: m.PRIORITY), reverse=True) self.assertEqual(target, priorities)
'Does Brain correctly send query to higher-priority module?'
def testPriority(self):
my_brain = TestBrain._emptyBrain() hn_module = 'HN' hn = filter((lambda m: (m.__name__ == hn_module)), my_brain.modules)[0] with mock.patch.object(hn, 'handle') as mocked_handle: my_brain.query(['hacker news']) self.assertTrue(mocked_handle.called)
'Generic method for spoofing conversation. Arguments: query -- The initial input to the server. inputs -- Additional input, if conversation is extended. Returns: The server\'s responses, in a list.'
def runConversation(self, query, inputs, module):
self.assertTrue(module.isValid(query)) mic = test_mic.Mic(inputs) module.handle(query, mic, self.profile) return mic.outputs
'The lines below is a spider contract. For more info see: http://doc.scrapy.org/en/latest/topics/contracts.html @url http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/ @scrapes name'
def parse(self, response):
sites = response.css('#site-list-content > div.site-item > div.title-and-desc') items = [] for site in sites: item = Website() item['name'] = site.css('a > div.site-title::text').extract_first().strip() item['url'] = site.xpath('a/@href').extract_first().strip() ...
'Since the original function always creates the directory, to resolve the issue a new function had to be created. It\'s a simple copy and was reduced for this case. More info at: https://github.com/scrapy/scrapy/pull/2005'
def _copytree(self, src, dst):
ignore = IGNORE names = os.listdir(src) ignored_names = ignore(src, names) if (not os.path.exists(dst)): os.makedirs(dst) for name in names: if (name in ignored_names): continue srcname = os.path.join(src, name) dstname = os.path.join(dst, name) if...
'Command syntax (preferably one-line). Do not include command name.'
def syntax(self):
return ''
'A short description of the command'
def short_desc(self):
return ''
'A long description of the command. Return short description when not available. It cannot contain newlines, since contents will be formatted by optparser which removes newlines and wraps text.'
def long_desc(self):
return self.short_desc()
'An extensive help for the command. It will be shown when using the "help" command. It can contain newlines, since not post-formatting will be applied to its contents.'
def help(self):
return self.long_desc()
'Populate option parse with options available for this command'
def add_options(self, parser):
group = OptionGroup(parser, 'Global Options') group.add_option('--logfile', metavar='FILE', help='log file. if omitted stderr will be used') group.add_option('-L', '--loglevel', metavar='LEVEL', default=None, help=('log level (default: %s)' % self.settings['LOG_LEVEL'])) ...
'Entry point for running commands'
def run(self, args, opts):
raise NotImplementedError
'Generate the spider module, based on the given template'
def _genspider(self, module, name, domain, template_name, template_file):
tvars = {'project_name': self.settings.get('BOT_NAME'), 'ProjectName': string_camelcase(self.settings.get('BOT_NAME')), 'module': module, 'name': name, 'domain': domain, 'classname': ('%sSpider' % ''.join((s.capitalize() for s in module.split('_'))))} if self.settings.get('NEWSPIDER_MODULE'): spiders_mo...
'You can use this function to update the Scrapy objects that will be available in the shell'
def update_vars(self, vars):
pass
'Start the execution engine'
@defer.inlineCallbacks def start(self):
assert (not self.running), 'Engine already running' self.start_time = time() (yield self.signals.send_catch_log_deferred(signal=signals.engine_started)) self.running = True self._closewait = defer.Deferred() (yield self._closewait)
'Stop the execution engine gracefully'
def stop(self):
assert self.running, 'Engine not running' self.running = False dfd = self._close_all_spiders() return dfd.addBoth((lambda _: self._finish_stopping_engine()))
'Close the execution engine gracefully. If it has already been started, stop it. In all cases, close all spiders and the downloader.'
def close(self):
if self.running: return self.stop() elif self.open_spiders: return self._close_all_spiders() else: return defer.succeed(self.downloader.close())
'Pause the execution engine'
def pause(self):
self.paused = True
'Resume the execution engine'
def unpause(self):
self.paused = False
'Does the engine have capacity to handle more spiders'
def has_capacity(self):
return (not bool(self.slot))
'Called when a spider gets idle. This function is called when there are no remaining pages to download or schedule. It can be called multiple times. If some extension raises a DontCloseSpider exception (in the spider_idle signal handler) the spider is not closed until the next loop and this function is guaranteed to be...
def _spider_idle(self, spider):
res = self.signals.send_catch_log(signal=signals.spider_idle, spider=spider, dont_log=DontCloseSpider) if any(((isinstance(x, Failure) and isinstance(x.value, DontCloseSpider)) for (_, x) in res)): return if self.spider_is_idle(spider): self.close_spider(spider, reason='finished')
'Close (cancel) spider and clear all its outstanding requests'
def close_spider(self, spider, reason='cancelled'):
slot = self.slot if slot.closing: return slot.closing logger.info('Closing spider (%(reason)s)', {'reason': reason}, extra={'spider': spider}) dfd = slot.close() def log_failure(msg): def errback(failure): logger.error(msg, exc_info=failure_to_exc_info(failure), ext...
'Open the given spider for scraping and allocate resources for it'
@defer.inlineCallbacks def open_spider(self, spider):
self.slot = Slot() (yield self.itemproc.open_spider(spider))
'Close a spider being scraped and release its resources'
def close_spider(self, spider):
slot = self.slot slot.closing = defer.Deferred() slot.closing.addCallback(self.itemproc.close_spider) self._check_if_closing(spider, slot) return slot.closing
'Return True if there isn\'t any more spiders to process'
def is_idle(self):
return (not self.slot)
'Handle the downloaded response or failure through the spider callback/errback'
def _scrape(self, response, request, spider):
assert isinstance(response, (Response, Failure)) dfd = self._scrape2(response, request, spider) dfd.addErrback(self.handle_spider_error, request, response, spider) dfd.addCallback(self.handle_spider_output, request, response, spider) return dfd
'Handle the different cases of request\'s result been a Response or a Failure'
def _scrape2(self, request_result, request, spider):
if (not isinstance(request_result, Failure)): return self.spidermw.scrape_response(self.call_spider, request_result, request, spider) else: dfd = self.call_spider(request_result, request, spider) return dfd.addErrback(self._log_download_errors, request_result, request, spider)
'Process each Request/Item (given in the output parameter) returned from the given spider'
def _process_spidermw_output(self, output, request, response, spider):
if isinstance(output, Request): self.crawler.engine.crawl(request=output, spider=spider) elif isinstance(output, (BaseItem, dict)): self.slot.itemproc_size += 1 dfd = self.itemproc.process_item(output, spider) dfd.addBoth(self._itemproc_finished, output, response, spider) ...
'Log and silence errors that come from the engine (typically download errors that got propagated thru here)'
def _log_download_errors(self, spider_failure, download_failure, request, spider):
if (isinstance(download_failure, Failure) and (not download_failure.check(IgnoreRequest))): if download_failure.frames: logger.error('Error downloading %(request)s', {'request': request}, exc_info=failure_to_exc_info(download_failure), extra={'spider': spider}) else: er...
'ItemProcessor finished for the given ``item`` and returned ``output``'
def _itemproc_finished(self, output, item, response, spider):
self.slot.itemproc_size -= 1 if isinstance(output, Failure): ex = output.value if isinstance(ex, DropItem): logkws = self.logformatter.dropped(item, ex, response, spider) logger.log(extra={'spider': spider}, *logformatter_adapter(logkws)) return self.signals.s...
'Lazy-load the downloadhandler for a scheme only on the first request for that scheme.'
def _get_handler(self, scheme):
if (scheme in self._handlers): return self._handlers[scheme] if (scheme in self._notconfigured): return None if (scheme not in self._schemes): self._notconfigured[scheme] = 'no handler available for that scheme' return None path = self._schemes[scheme] ...
'Return a deferred for the HTTP download'
def download_request(self, request, spider):
agent = ScrapyAgent(contextFactory=self._contextFactory, pool=self._pool, maxsize=getattr(spider, 'download_maxsize', self._default_maxsize), warnsize=getattr(spider, 'download_warnsize', self._default_warnsize), fail_on_dataloss=self._fail_on_dataloss) return agent.download_request(request)
'Asks the proxy to open a tunnel.'
def requestTunnel(self, protocol):
tunnelReq = tunnel_request_data(self._tunneledHost, self._tunneledPort, self._proxyAuthHeader) protocol.transport.write(tunnelReq) self._protocolDataReceived = protocol.dataReceived protocol.dataReceived = self.processProxyResponse self._protocol = protocol return protocol
'Processes the response from the proxy. If the tunnel is successfully created, notifies the client that we are ready to send requests. If not raises a TunnelError.'
def processProxyResponse(self, rcvd_bytes):
self._connectBuffer += rcvd_bytes if ('\r\n\r\n' not in self._connectBuffer): return self._protocol.dataReceived = self._protocolDataReceived respm = TunnelingTCP4ClientEndpoint._responseMatcher.match(self._connectBuffer) if (respm and (int(respm.group('status')) == 200)): try: ...
'Propagates the errback to the appropriate deferred.'
def connectFailed(self, reason):
self._tunnelReadyDeferred.errback(reason)
'Return a deferred for the HTTP download'
def download_request(self, request, spider):
factory = self.HTTPClientFactory(request) self._connect(factory) return factory.deferred
'Upload file to S3 storage'
def persist_file(self, path, buf, info, meta=None, headers=None):
key_name = ('%s%s' % (self.prefix, path)) buf.seek(0) if self.is_botocore: extra = self._headers_to_botocore_kwargs(self.HEADERS) if headers: extra.update(self._headers_to_botocore_kwargs(headers)) return threads.deferToThread(self.s3_client.put_object, Bucket=self.bucket...
'Convert headers to botocore keyword agruments.'
def _headers_to_botocore_kwargs(self, headers):
mapping = CaselessDict({'Content-Type': 'ContentType', 'Cache-Control': 'CacheControl', 'Content-Disposition': 'ContentDisposition', 'Content-Encoding': 'ContentEncoding', 'Content-Language': 'ContentLanguage', 'Content-Length': 'ContentLength', 'Content-MD5': 'ContentMD5', 'Expires': 'Expires', 'X-Amz-Grant-Full-C...