desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
''
def write_gifs(self, clip, gif_dir):
for (start, end, _, _) in self: name = ('%s/%08d_%08d.gif' % (gif_dir, (100 * start), (100 * end))) clip.subclip(start, end).write_gif(name, verbose=False)
'Returns a list of the clips in the composite clips that are actually playing at the given time `t`.'
def playing_clips(self, t=0):
return [c for c in self.clips if c.is_playing(t)]
'Writes one frame in the file.'
def write_frame(self, img_array):
try: if PY3: self.proc.stdin.write(img_array.tobytes()) else: self.proc.stdin.write(img_array.tostring()) except IOError as err: (_, ffmpeg_error) = self.proc.communicate() error = (str(err) + ('\n\nMoviePy error: FFMPEG encountered the foll...
'Close/delete the internal reader.'
def __del__(self):
try: del self.reader except AttributeError: pass try: del self.audio except AttributeError: pass
'Opens the file, creates the pipe.'
def initialize(self, starttime=0):
self.close() if (starttime != 0): offset = min(1, starttime) i_arg = ['-ss', ('%.06f' % (starttime - offset)), '-i', self.filename, '-ss', ('%.06f' % offset)] else: i_arg = ['-i', self.filename] cmd = (([get_setting('FFMPEG_BINARY')] + i_arg) + ['-loglevel', 'error', '-f', 'image...
'Reads and throws away n frames'
def skip_frames(self, n=1):
(w, h) = self.size for i in range(n): self.proc.stdout.read(((self.depth * w) * h)) self.pos += n
'Read a file video frame at time t. Note for coders: getting an arbitrary frame in the video with ffmpeg can be painfully slow if some decoding has to be done. This function tries to avoid fectching arbitrary frames whenever possible, by moving between adjacent frames.'
def get_frame(self, t):
pos = (int(((self.fps * t) + 1e-05)) + 1) if (pos == self.pos): return self.lastread else: if ((pos < self.pos) or (pos > (self.pos + 100))): self.initialize(t) self.pos = pos else: self.skip_frames(((pos - self.pos) - 1)) result = self.rea...
'Shallow copy of the clip. Returns a shwallow copy of the clip whose mask and audio will be shallow copies of the clip\'s mask and audio if they exist. This method is intensively used to produce new clips every time there is an outplace transformation of the clip (clip.resize, clip.subclip, etc.)'
def copy(self):
newclip = copy(self) if hasattr(self, 'audio'): newclip.audio = copy(self.audio) if hasattr(self, 'mask'): newclip.mask = copy(self.mask) return newclip
'Gets a numpy array representing the RGB picture of the clip at time t or (mono or stereo) value for a sound clip'
@convert_to_seconds(['t']) def get_frame(self, t):
if self.memoize: if (t == self.memoized_t): return self.memoized_frame else: frame = self.make_frame(t) self.memoized_t = t self.memoized_frame = frame return frame else: return self.make_frame(t)
'General processing of a clip. Returns a new Clip whose frames are a transformation (through function ``fun``) of the frames of the current clip. Parameters fun A function with signature (gf,t -> frame) where ``gf`` will represent the current clip\'s ``get_frame`` method, i.e. ``gf`` is a function (t->image). Parameter...
def fl(self, fun, apply_to=None, keep_duration=True):
if (apply_to is None): apply_to = [] newclip = self.set_make_frame((lambda t: fun(self.get_frame, t))) if (not keep_duration): newclip.duration = None newclip.end = None if isinstance(apply_to, str): apply_to = [apply_to] for attr in apply_to: if hasattr(newcl...
'Returns a Clip instance playing the content of the current clip but with a modified timeline, time ``t`` being replaced by another time `t_func(t)`. Parameters t_func: A function ``t-> new_t`` apply_to: Can be either \'mask\', or \'audio\', or [\'mask\',\'audio\']. Specifies if the filter ``fl`` should also be applied...
def fl_time(self, t_func, apply_to=None, keep_duration=False):
if (apply_to is None): apply_to = [] return self.fl((lambda gf, t: gf(t_func(t))), apply_to, keep_duration=keep_duration)
'Returns the result of ``func(self, *args, **kwargs)``. for instance >>> newclip = clip.fx(resize, 0.2, method=\'bilinear\') is equivalent to >>> newclip = resize(clip, 0.2, method=\'bilinear\') The motivation of fx is to keep the name of the effect near its parameters, when the effects are chained: >>> from moviepy.vi...
def fx(self, func, *args, **kwargs):
return func(self, *args, **kwargs)
'Returns a copy of the clip, with the ``start`` attribute set to ``t``, which can be expressed in seconds (15.35), in (min, sec), in (hour, min, sec), or as a string: \'01:03:05.35\'. If ``change_end=True`` and the clip has a ``duration`` attribute, the ``end`` atrribute of the clip will be updated to ``start+duration`...
@apply_to_mask @apply_to_audio @convert_to_seconds(['t']) @outplace def set_start(self, t, change_end=True):
self.start = t if ((self.duration is not None) and change_end): self.end = (t + self.duration) elif (self.end is not None): self.duration = (self.end - self.start)
'Returns a copy of the clip, with the ``end`` attribute set to ``t``, which can be expressed in seconds (15.35), in (min, sec), in (hour, min, sec), or as a string: \'01:03:05.35\'. Also sets the duration of the mask and audio, if any, of the returned clip.'
@apply_to_mask @apply_to_audio @convert_to_seconds(['t']) @outplace def set_end(self, t):
self.end = t if (self.end is None): return if (self.start is None): if (self.duration is not None): self.start = max(0, (t - newclip.duration)) else: self.duration = (self.end - self.start)
'Returns a copy of the clip, with the ``duration`` attribute set to ``t``, which can be expressed in seconds (15.35), in (min, sec), in (hour, min, sec), or as a string: \'01:03:05.35\'. Also sets the duration of the mask and audio, if any, of the returned clip. If change_end is False, the start attribute of the clip ...
@apply_to_mask @apply_to_audio @convert_to_seconds(['t']) @outplace def set_duration(self, t, change_end=True):
self.duration = t if change_end: self.end = (None if (t is None) else (self.start + t)) else: if (self.duration is None): raise Exception('Cannot change clip start when newduration is None') self.start = (self.end - t)
'Sets a ``make_frame`` attribute for the clip. Useful for setting arbitrary/complicated videoclips.'
@outplace def set_make_frame(self, make_frame):
self.make_frame = make_frame
'Returns a copy of the clip with a new default fps for functions like write_videofile, iterframe, etc.'
@outplace def set_fps(self, fps):
self.fps = fps
'Says wheter the clip is a mask or not (ismask is a boolean)'
@outplace def set_ismask(self, ismask):
self.ismask = ismask
'Sets wheter the clip should keep the last frame read in memory'
@outplace def set_memoize(self, memoize):
self.memoize = memoize
'If t is a time, returns true if t is between the start and the end of the clip. t can be expressed in seconds (15.35), in (min, sec), in (hour, min, sec), or as a string: \'01:03:05.35\'. If t is a numpy array, returns False if none of the t is in theclip, else returns a vector [b_1, b_2, b_3...] where b_i is true iff...
@convert_to_seconds(['t']) def is_playing(self, t):
if isinstance(t, np.ndarray): (tmin, tmax) = (t.min(), t.max()) if ((self.end is not None) and (tmin >= self.end)): return False if (tmax < self.start): return False result = (1 * (t >= self.start)) if (self.end is not None): result *= (t <...
'Returns a clip playing the content of the current clip between times ``t_start`` and ``t_end``, which can be expressed in seconds (15.35), in (min, sec), in (hour, min, sec), or as a string: \'01:03:05.35\'. If ``t_end`` is not provided, it is assumed to be the duration of the clip (potentially infinite). If ``t_end``...
@convert_to_seconds(['t_start', 't_end']) @apply_to_mask @apply_to_audio def subclip(self, t_start=0, t_end=None):
if (t_start < 0): t_start = (self.duration + t_start) if ((self.duration is not None) and (t_start > self.duration)): raise ValueError(((('t_start (%.02f) ' % t_start) + "should be smaller than the clip's ") + ('duration (%.02f).' % self.duration))) newclip = self....
'Returns a clip playing the content of the current clip but skips the extract between ``ta`` and ``tb``, which can be expressed in seconds (15.35), in (min, sec), in (hour, min, sec), or as a string: \'01:03:05.35\'. If the original clip has a ``duration`` attribute set, the duration of the returned clip is automatica...
@apply_to_mask @apply_to_audio @convert_to_seconds(['ta', 'tb']) def cutout(self, ta, tb):
fl = (lambda t: (t + ((t >= ta) * (tb - ta)))) newclip = self.fl_time(fl) if (self.duration is not None): return newclip.set_duration((self.duration - (tb - ta))) else: return newclip
'Iterates over all the frames of the clip. Returns each frame of the clip as a HxWxN np.array, where N=1 for mask clips and N=3 for RGB clips. This function is not really meant for video editing. It provides an easy way to do frame-by-frame treatment of a video, for fields like science, computer vision... The ``fps`` (...
@requires_duration @use_clip_fps_by_default def iter_frames(self, fps=None, with_times=False, progress_bar=False, dtype=None):
def generator(): for t in np.arange(0, self.duration, (1.0 / fps)): frame = self.get_frame(t) if ((dtype is not None) and (frame.dtype != dtype)): frame = frame.astype(dtype) if with_times: (yield (t, frame)) else: ...
'Returns a copy of the AudioFileClip, i.e. a new entrance point to the audio file. Use copy when you have different clips watching the audio file at different times.'
def coreader(self):
return AudioFileClip(self.filename, self.buffersize)
'Close/delete the internal reader.'
def __del__(self):
try: del self.reader except AttributeError: pass
'Opens the file, creates the pipe.'
def initialize(self, starttime=0):
self.close_proc() if (starttime != 0): offset = min(1, starttime) i_arg = ['-ss', ('%.05f' % (starttime - offset)), '-i', self.filename, '-vn', '-ss', ('%.05f' % offset)] else: i_arg = ['-i', self.filename, '-vn'] cmd = (([get_setting('FFMPEG_BINARY')] + i_arg) + ['-loglevel', 'e...
'Reads a frame at time t. Note for coders: getting an arbitrary frame in the video with ffmpeg can be painfully slow if some decoding has to be done. This function tries to avoid fectching arbitrary frames whenever possible, by moving between adjacent frames.'
def seek(self, pos):
if ((pos < self.pos) or (pos > (self.pos + 1000000))): t = ((1.0 * pos) / self.fps) self.initialize(t) elif (pos > self.pos): self.skip_chunk((pos - self.pos)) self.pos = pos
'Fills the buffer with frames, centered on ``framenumber`` if possible'
def buffer_around(self, framenumber):
new_bufferstart = max(0, (framenumber - (self.buffersize // 2))) if (self.buffer is not None): current_f_end = (self.buffer_startframe + self.buffersize) if (new_bufferstart < current_f_end < (new_bufferstart + self.buffersize)): conserved = ((current_f_end - new_bufferstart) + 1) ...
'Iterator that returns the whole sound array of the clip by chunks'
@requires_duration def iter_chunks(self, chunksize=None, chunk_duration=None, fps=None, quantize=False, nbytes=2, progress_bar=False):
if (fps is None): fps = self.fps if (chunk_duration is not None): chunksize = int((chunk_duration * fps)) totalsize = int((fps * self.duration)) if ((totalsize % chunksize) == 0): nchunks = (totalsize // chunksize) else: nchunks = ((totalsize // chunksize) + 1) po...
'Transforms the sound into an array that can be played by pygame or written in a wav file. See ``AudioClip.preview``. Parameters fps Frame rate of the sound for the conversion. 44100 for top quality. nbytes Number of bytes to encode the sound: 1 for 8bit sound, 2 for 16bit, 4 for 32bit sound.'
@requires_duration def to_soundarray(self, tt=None, fps=None, quantize=False, nbytes=2, buffersize=50000):
if (fps is None): fps = self.fps stacker = (np.vstack if (self.nchannels == 2) else np.hstack) max_duration = ((1.0 * buffersize) / fps) if (tt is None): if (self.duration > max_duration): return stacker(self.iter_chunks(fps=fps, quantize=quantize, nbytes=2, chunksize=buffers...
'Writes an audio file from the AudioClip. Parameters filename Name of the output file fps Frames per second nbyte Sample width (set to 2 for 16-bit sound, 4 for 32-bit sound) codec Which audio codec should be used. If None provided, the codec is determined based on the extension of the filename. Choose \'pcm_s16le\' fo...
@requires_duration def write_audiofile(self, filename, fps=44100, nbytes=2, buffersize=2000, codec=None, bitrate=None, ffmpeg_params=None, write_logfile=False, verbose=True, progress_bar=True):
if (codec is None): (name, ext) = os.path.splitext(os.path.basename(filename)) try: codec = extensions_dict[ext[1:]]['codec'][0] except KeyError: raise ValueError("MoviePy couldn't find the codec associated with the filename. Provide the ...
'Initialize the PyTest options.'
def initialize_options(self):
TestCommand.initialize_options(self) self.pytest_args = []
'Finalize the PyTest options.'
def finalize_options(self):
TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True
'Run the PyTest testing suite.'
def run_tests(self):
try: import pytest except ImportError: raise ImportError('Running tests requires additional dependencies.\nPlease run (pip install moviepy[test])') errno = pytest.main(self.pytest_args) sys.exit(errno)
'Initialize SoupData object. Load data from HTML.'
def __init__(self):
self.SOUP_HTML = '' self.load_data()
'Open the HTML file and load it into the object.'
def load_data(self):
with open('download/index.html', 'r') as data_file: self.SOUP_HTML = data_file.read()
'Returns: The raw HTML that was loaded.'
def get_raw_data(self):
return self.SOUP_HTML
'Given raw data, get the relevant section Args: raw_data: HTML data'
def __init__(self, raw_data):
self.parsed_data = None self.sections = list() soup_data = BeautifulSoup(raw_data, 'html.parser') for content in soup_data.find('div', {'class': 'body'}): if ((not content) or isinstance(content, NavigableString)): continue self.sections.append(content)
'Find the name and anchor for a given section Args: section: A section of parsed HTML Returns: name: Name of the section anchor: Anchor tag to use when linking back to the docs (ie #tags)'
def parse_name_and_anchor_from_data(self, section):
(name, anchor) = (None, None) a_tag = section.find('a', {'class': 'headerlink'}) if a_tag: anchor = a_tag['href'] name = a_tag.parent.text[:(-1)].replace('()', '').replace('.', '') return (name, anchor)
'Get the first paragraph for display Args: section: A section of parsed HTML Returns: First paragraph in the HTML'
def parse_first_paragraph_from_data(self, section):
data = section.find('p') if data: return data.text.replace('\n', ' ').replace(' ', ' ') return None
'Look for example code block to output Args: section: A section of parsed HTML Returns: Formatted code string'
def parse_code_from_data(self, section):
code = section.find('div', {'class': 'highlight-python'}) if code: return '<pre><code>{}</code></pre>'.format(code.text.replace('\xc2\xb6', '').replace('\n', '\\n')) return None
'Main gateway into parsing the data. Will retrieve all necessary data elements.'
def parse_for_data(self):
data = list() for section in self.sections: for sub_section in section.find_all('div', {'class': 'section'}): (name, anchor) = self.parse_name_and_anchor_from_data(sub_section) first_paragraph = self.parse_first_paragraph_from_data(sub_section) code = self.parse_code_...
'Get the parsed data. Returns: self.parsed_data: Dict containing necessary data elements'
def get_data(self):
return self.parsed_data
'Initialize SoupDataOutput object Args: data: Dict containing the data elements'
def __init__(self, data):
self.data = data
'Iterate through the data and create the necessary output.txt file'
def create_file(self):
with open('output.txt', 'w+') as output_file: for data_element in self.data: name = data_element.get('name') code = data_element.get('code') first_paragraph = data_element.get('first_paragraph') abstract = '{}{}{}'.format(code, ('<br>' if code else ''), first_...
':param name: Name of the Fathead :param description: Description of what\'s being displayed :param filename: The filename from which the information came. Used to construct the URL for the entry Instantiate the information about the class'
def __init__(self, name, description, filename):
self.name = name self.description = description.replace('\n', '').replace(' DCTB ', ' ') self.description = '<p>{}</p>'.format(self.description) self.filename = filename
'Get all itext class files that need to be parsed'
def __init__(self):
self.itext_classes = {} self.files_to_parse = glob.glob('download/*.html')
'Args: specfile: A filesystem path to a csv file containing language definitions. It should have the format: BaseObject,property,{class_property,class_function,instance_method,instance_property}'
def __init__(self, specfile):
self.inverted_index = {} self.objects = set() with codecs.open(specfile, 'r', 'utf-8') as f: for line in f: line = line.strip() index = line.split('(')[0] if (index.count('.') > 1): index = index.split('prototype')[(-1)] index = index.s...
'Standardize and clean the fields within an MDN object.'
def standardize(self, mdn):
if ('Global' in mdn.obj): mdn.obj = 'Global' if ((mdn.obj not in self.objects) and ('Global' in mdn.url)): return None if (mdn.prop.lower() not in self.inverted_index): return mdn for signature in self.inverted_index[mdn.prop.lower()]: if signature.startswith(mdn.obj): ...
'Write the dict row.'
def writerow(self, outdict):
row = [] for field in FatWriter.FIELDS: col = outdict.get(field, '') col = col.replace(' DCTB ', ' ') col = col.replace('\n', '\\n') row.append(col) self.outfile.write((' DCTB '.join(row) + '\n'))
'Parse an html file and return an mdn object. Args: htmlfile: A file-like object that should parse with lxml html parser.'
def parse(self, htmlfile):
page = htmlfile.read() tree = html.fromstring(page) if self._is_obsolete(tree): return None title = tree.xpath("//meta[@property='og:title']/@content")[0] article = tree.xpath("//article[contains(@id,'wikiArticle')]") summary = '' if article: summary_nodes = tree.xpath("//h2[...
'Initialize PythonData object. Load data from HTML.'
def __init__(self, file):
self.HTML = '' self.FILE = file self.load_data()
'Open the HTML file and load it into the object.'
def load_data(self):
with open(self.FILE, 'r') as data_file: self.HTML = data_file.read()
'Returns: The raw HTML that was loaded.'
def get_raw_data(self):
return self.HTML
'Returns: The file path of the file being used.'
def get_file(self):
return self.FILE
'Given raw data, get the relevant sections Args: raw_data: HTML data path: path of downloaded HTML data'
def __init__(self, data_object, info):
self.parsed_data = None self.function_sections = [] self.method_sections = [] self.intro_text = '' self.title = '' self.info = info self.file_being_used = data_object.get_file() soup_data = BeautifulSoup(data_object.get_raw_data(), 'html.parser') sections = soup_data.find_all('div', ...
'Returns the module name Args: section: A section of parsed HTML that represents a function definition Returns: Name of the module'
def parse_for_module_name(self, section):
module_name = section.find('code', {'class': 'descclassname'}) if module_name: return module_name.text.rstrip('.') return ''
'Returns the function name Args: section: A section of parsed HTML that represents a function definition Returns: Name of function'
def parse_for_function_name(self, section):
function_name = section.find('code', {'class': 'descname'}) if function_name: return function_name.text return ''
'Returns the first paragraph of text for a given function Fixes up some weird double spacing and newlines. Args: section: A section of parsed HTML that represents a function definition Returns: First paragraph found with text'
def parse_for_first_paragraph(self, section):
paragraphs = section.find_all('p') for paragraph in paragraphs: if paragraph.text: return paragraph.text.replace(' ', ' ').replace('\n', ' ').replace('\\n', '\\\\n') return ''
'Returns the anchor link to specific function doc Args: section: A section of parsed HTML that represents a function definition Returns: The href value of the link to doc'
def parse_for_anchor(self, section):
a_tag = section.find('a', {'class': 'headerlink'}) if a_tag: return a_tag['href'] return ''
'Returns the method signature Args: section: A section of parsed HTML that represents a function definition Returns: The method signature'
def parse_for_method_signature(self, section):
dt = section.find('dt') if dt: return '<pre><code>{}</code></pre>'.format(dt.text.replace('\xc2\xb6', '').replace('\n', '').replace('\\n', '\\\\n')) return ''
'Returns the class.module.method signature Args: section: A section of parsed HTML that represents a method definition Returns: The method signature'
def parse_for_class_method(self, section):
id_tag = section.find('dt').get('id') if id_tag: tag_parts = id_tag.split('.') if (len(tag_parts) == 3): return tag_parts elif (len(tag_parts) > 3): return (tag_parts[0], tag_parts[1], '.'.join(tag_parts[2:])) return ['', '', '']
'Helper method to create URL back to document Args: anchor: #anchor Returns: Full URL to function on the python doc'
def create_url(self, anchor):
file_path = self.file_being_used.replace(self.info['download_path'], '') return self.info['doc_base_url'].format('{}{}'.format(file_path, anchor))
'Main gateway into parsing the data. Will retrieve all necessary data elements.'
def parse_for_data(self):
data = [] if (self.intro_text and self.title): data_elements = {'module': self.title, 'function': '', 'method_signature': '', 'first_paragraph': self.intro_text, 'url': self.create_url('')} data.append(data_elements) for function_section in self.function_sections: module = self.parse...
'Get the parsed data. Returns: self.parsed_data: Dict containing necessary data elements'
def get_data(self):
return self.parsed_data
'Figure out the name of the function. Will contain the module name if one exists. Args: data_element: Incoming data dict Returns: Name, with whitespace stripped out'
def create_names_from_data(self, data_element):
module = data_element.get('module') function = data_element.get('function') dotted_name = '{}{}{}'.format(module, ('.' if (module and function) else ''), function) spaced_name = '{} {}'.format(module, function) return (dotted_name.strip(), spaced_name.strip())
'Iterate through the data and create the needed output.txt file, appending to file as necessary.'
def create_file(self):
with open(self.output, 'a') as output_file: for data_element in self.data: if (data_element.get('module') or data_element.get('function')): method_signature = data_element.get('method_signature') first_paragraph = (('<p>' + data_element.get('first_paragraph')) + '...
'Try to parse given input into a valid entry. Args: input_obj: TSV string or list of data. Returns: List of data Raises: Throws BadEntryException if data is invalid.'
def parse(self, input_obj):
if isinstance(input_obj, str): processed = input_obj.split(' DCTB ') self.data = processed elif isinstance(input_obj, list): self.data = input_obj try: self.key = self.data[0].strip() self.entry_type = self.data[1].strip() self.reference = self.data[2].strip()...
'Find alternative keys to use in generated redirects Returns: Set of possible redirect entries'
def parse_alternative_keys(self):
self.alternative_keys = set() if (('.' in self.key) and (self.entry_type == 'A')): key_arr = self.key.split('.') method_name = key_arr[(-1)] key_arr_len = len(key_arr) self.alternative_keys.add(method_name) if (key_arr_len >= 3): for l in range((key_arr_len - ...
'Instantiate the information about the command'
def __init__(self, name, description, filename):
self.name = name self.description = description.replace('\n', '\\n').replace(' DCTB ', ' ') self.description = '<p>{}</p>'.format(self.description) self.filename = filename self.usage = ''
'Output the git command information in the proper format required for DuckDuckGo Fatheads'
def basic_usage(self):
usage_cleaned = self.usage.replace('\n', '\\n').replace(' DCTB ', ' ') if usage_cleaned: abstract = '{}\\n<pre><code>{}</code></pre>'.format(self.description, usage_cleaned) else: abstract = self.description abstract = '<section class="prog__container">{}</section>'.for...
'Get all git command files that need to be parsed'
def __init__(self):
self.files_to_parse = glob.glob('download/*.html')
'Parse each git command and make a Command object for each'
def parse_commands(self):
self.commands = [] for file in self.files_to_parse: soup = BeautifulSoup(open(file), 'html.parser') name_h2 = soup.find('h2', {'id': '_name'}) if (not name_h2): continue description_p = name_h2.findNext('p') if (not description_p): continue ...
'Initialize PythonData object. Load data from HTML.'
def __init__(self, file):
self.HTML = '' self.FILE = file self.load_data()
'Open the HTML file and load it into the object.'
def load_data(self):
with open(self.FILE, 'r') as data_file: self.HTML = data_file.read()
'Returns: The raw HTML that was loaded.'
def get_raw_data(self):
return self.HTML
'Returns: The file path of the file being used.'
def get_file(self):
return self.FILE
'Returns the function name Args: section: A section of parsed HTML that represents a function definition Returns: Name of function'
def parse_for_prop_name(self, section):
prop_name_h4 = section.find('h4', {'class': 'propTitle'}) link_to_general_props = 'View props... #' if (prop_name_h4 and (prop_name_h4.text != link_to_general_props)): prop_name = prop_name_h4.next.next if prop_name_h4.find('span', {'class': 'platform'}): prop_name = prop_n...
'Returns the first paragraph of text for a given function Fixes up some weird double spacing and newlines. Args: section: A section of parsed HTML that represents a function definition Returns: First paragraph found with text'
def parse_for_first_paragraph(self, section):
paragraphs = section.find_all('p') for paragraph in paragraphs: if paragraph.text: return self._format_output(paragraph.text) return ''
'Returns the anchor link to specific function doc Args: section: A section of parsed HTML that represents a function definition Returns: The href value of the link to doc'
def parse_for_anchor(self, section):
a_tag = section.find('a', {'class': 'anchor'}) if a_tag: return a_tag['name'] return ''
'Returns the signature Args: section: A section of parsed HTML that represents a definition of a property or method Returns: The signature'
def parse_for_signature(self, section, titleName):
h4 = section.find('h4', {'class': titleName}) contents = [] for e in h4.strings: contents.append(e) del contents[(-1)] del contents[(-1)] if h4.find('span', {'class': 'platform'}): del contents[0] if (len(h4.find_all('span', {'class': 'methodType'})) > 1): del content...
'Returns the name of a method Args: section: A section of parsed HTML that represents a method definition Returns: The method name'
def parse_for_method_name(self, section):
method_name_h4 = section.find('h4', {'class': 'methodTitle'}) if method_name_h4: method_name = method_name_h4.next.next nbr_of_methodType_tags_in_h4 = len(method_name_h4.find_all('span', {'class': 'methodType'})) if (nbr_of_methodType_tags_in_h4 > 1): method_name = method_nam...
'Helper method to create URL back to document Args: anchor: #anchor Returns: Full URL to function on the python doc'
def create_url(self, anchor):
file_path = self.file_being_used.replace(self.info['download_path'], '') return self.info['doc_base_url'].format('{}#{}'.format(file_path, anchor))
'Main gateway into parsing the data. Will retrieve all necessary data elements.'
def parse_for_data(self):
data = [] if (self.intro_text and self.title): data_elements = {'module': self.title, 'function': '', 'method_signature': '', 'first_paragraph': self.intro_text, 'url': self.create_url('')} data.append(data_elements) titleName = 'propTitle' for prop_section in self.prop_sections: ...
'Get the parsed data. Returns: self.parsed_data: Dict containing necessary data elements'
def get_data(self):
return self.parsed_data
'Helper method to format the output appropriately.'
def _format_output(self, text):
return text.replace(' ', ' ').replace('\n', ' ').replace('\\n', '\\\\n')
'Figure out the name of the function. Will contain the module name if one exists. Args: data_element: Incoming data dict Returns: Name, with whitespace stripped out'
def create_names_from_data(self, data_element):
module = data_element.get('module') function = data_element.get('function') dotted_name = '{}{}{}'.format(module, ('.' if (module and function) else ''), function) spaced_name = '{} {}'.format(module, function) return (dotted_name.strip(), spaced_name.strip())
'Iterate through the data and create the needed output.txt file, appending to file as necessary.'
def create_file(self):
with open(self.output, 'a') as output_file: for data_element in self.data: if (data_element.get('module') or data_element.get('function')): method_signature = data_element.get('method_signature') first_paragraph_text = data_element.get('first_paragraph') ...
'Try to parse given input into a valid entry. Args: input_obj: TSV string or list of data. Returns: List of data Raises: Throws BadEntryException if data is invalid.'
def parse(self, input_obj):
if isinstance(input_obj, str): processed = input_obj.split(' DCTB ') self.data = processed elif isinstance(input_obj, list): self.data = input_obj try: self.key = self.data[0].strip() self.entry_type = self.data[1].strip() self.reference = self.data[2].strip()...
'Find alternative keys to use in generated redirects Returns: Set of possible redirect entries'
def parse_alternative_keys(self):
self.alternative_keys = set() if (('.' in self.key) and (self.entry_type == 'A')): key_arr = self.key.split('.') method_name = key_arr[(-1)] key_arr_len = len(key_arr) self.alternative_keys.add(method_name) if (key_arr_len >= 3): for l in range((key_arr_len - ...
'The setup member function checks to see if the \'output.txt\' file exists. If it does, delete it and move on, otherwise move on. This is called in the constructor of the Environment object and shouldn\'t be called again.'
def setup(self):
if os.path.exists('output.txt'): os.remove('output.txt')
'The get_contents() member function loads the file into memory and reads the contents. The file buffer is then closed and then a BeautifulSoup object is instantiated, with the contents. More on this can be read at the BeautifulSoup documentation website (https://www.crummy.com/software/BeautifulSoup/bs4/doc/).'
def get_contents(self):
with open('download/packages.html') as f: contents = f.read() contents = BeautifulSoup(contents, 'html.parser', from_encoding='utf-8') return contents
'This member function parses the html document and extracts the cells from the table.'
def parse_contents(self, soup):
data = [] table = soup.find('table', attrs={'id': 'packages'}) table_body = table.find('tbody') rows = table_body.find_all('tr') '\n This section aims to extract the individual data points from the\n table ...
'The concat (concatenation) member function is responsible for preparing the data to be written to the file. The file is layed outlike this as requested in the DuckDuckHack docs found here: http://docs.duckduckhack.com/resources/fathead-overview.html#data-file-format'
def concat(self, name, desc, url, version):
title = name type_ = 'A' redirect = '' four = '' categories = '' six = '' related_topics = '' eight = '' external_links = '' ten = '' image = '' nAbstract = u'\n <section class="prog__container">\n ...
'The output() member function outputs the rows of data at a time to the output.txt file which is used as the k/v store for the FatHead IA.'
def output(self, data_list):
with open('output.txt', 'a') as f: for data in data_list: line = self.concat(data[0], data[2], data[3], data[1]) f.write(line.encode('utf'))
'Gets all tags defined in \'dl\' tags'
def get_tags(self):
self.tags = [] for tag in self.soup.find_all('dl'): name = tag.dt.contents[0] info = '' for p in tag.dd.find_all('p'): info += (p.getText() + ' ') a_tags = tag.dd.find_all('a') example_id = a_tags[1]['href'].replace('#', '') example = self.soup.find...
'Function to get the source code of the tutorials page'
def get_pages(self):
file_loc = 'download/events.html' file = open(file_loc, 'r+') code_str = '' for k in file.readlines(): code_str += k self.events_page = bs(code_str, 'html.parser') file_loc = 'download/internals.html' file = open(file_loc, 'r+') code_str = '' for k in file.readlines(): ...
'Function to replace all unicodes with their HTML equivalent'
def replace_unicodes(self, txt):
txt = txt.replace('\n', '\\n') txt = txt.replace(u'\u2019', '&#8217;') txt = txt.replace(u'\u201c', '&#8220;') txt = txt.replace(u'\u201d', '&#8221;') txt = txt.replace(u'\xb6', '') txt = txt.replace(u'\u2013', '&#8211;') txt = txt.replace(u'\u2018', '&#8216;') return txt
'Function to append a given statement to the given file'
def write_to_file(self, filename, elements):
currFile = open(filename, 'a') for e in elements: currFile.write(elements[e]) currFile.close()
'Function to remove \' from the start of a sentence'
def remove_newline(self, text):
t_list = text.split('\\n') txt = '' for k in t_list: if ((k != '') and (k != ' ')): txt += (k + ' ') return txt