def save(grammar, tryfilename, override=False, clean=True): """ Tries to write out grammar contents to new file <tryfilename> :param override: If <override> is true, it will write to <tryfilename> without question If <override> is false, it will search for the first available filename using first_available_filename :param clean: Determines whether the marked up grammar body or the cleaned up grammar body is saved :return: If successful, actual file name used """ if override: usefilename = tryfilename else: usefilename = saveutils.first_available_filename(tryfilename) try: f = open(usefilename, 'w') if clean: f.write(gramparse.clean_body(grammar)) else: f.write(grammar.body) f.close() except IOError as e: print "Error saving grammar '{0}' to {1}".format( grammar.name, usefilename) raise e return usefilename
def generate_exemplar(grammar, **kwargs): """ Using CFDG, creates an exemplar from the provided grammar, retrieves the image data, and returns the image data Available kwargs: 'maxshapes': maximum number of shapes 'width': width, in pixels, of image 'height': height, in pixels, of image :return: Exemplar instance """ commandstr = "cfdg" # process keyword arguments if 'maxshapes' in kwargs: commandstr += " -m {0}".format(kwargs['maxshapes']) else: commandstr += " -m {0}".format(MAX_SHAPES) if 'width' in kwargs: commandstr += " -w {0}".format(kwargs['width']) if 'height' in kwargs: commandstr += " -h {0}".format(kwargs['height']) # specify to cfdg that grammar file will come from stdin commandstr += " -" # run cfdg, passing in grammar.body as the input try: cfdg_proccess = proc.Popen(commandstr, shell=True, stdin=proc.PIPE, stdout=proc.PIPE) comm = cfdg_proccess.communicate(input=clean_body(grammar)) cfdg_output = comm[0] if cfdg_output == '': raise Exception("CFDG output is empty.") except Exception as e: print("Error using CFDG to parse grammar '{0}'".format(grammar.name)) raise e # parse output of cfdg into an image file, ready to save try: p = Parser() p.feed(cfdg_output) image = p.close() except IOError as e: print("Error parsing CFDG output for grammar '{0}' into an image file".format(grammar.name)) raise e ex = Exemplar(image=image) return ex