Example #1
0
def main():
    usage = "%prog [options] <results-file> [<result-number>=0]"
    parser = OptionParser(usage=usage)
    parser.add_option(
        "-q",
        "--quiet",
        dest="quiet",
        action="store_true",
        help="only output the requested information, no meta-info.")
    parser.add_option("-p",
                      "--print",
                      dest="printout",
                      action="store_true",
                      help="output the result to stdout.")
    parser.add_option("--path",
                      dest="path",
                      action="store_true",
                      help="display the fully-specified tonal space path.")
    parser.add_option(
        "--play",
        dest="play",
        action="store_true",
        help=
        "use the harmonical to play the root sequence of the result's semantics."
    )
    parser.add_option(
        "--audio",
        dest="audio",
        action="store",
        help=
        "use the harmonical to render the root sequence, as with --play, and store the result to a wave file."
    )
    options, arguments = parser.parse_args()

    # Just get the default formalism
    formalism = get_default_formalism()

    def _print(string=""):
        if not options.quiet:
            print >> sys.stderr, string

    if len(arguments) == 0:
        print >> sys.stderr, "Specify a file to read the results from"
        sys.exit(1)
    results = ParseResults.from_file(arguments[0])

    if len(arguments) > 1:
        res_num = int(arguments[1])
    else:
        res_num = 0
    prob, result = results.sorted_results[res_num]

    if options.printout:
        _print("Result:")
        # Just display the resulting category
        print result
        _print()

    if options.path:
        _print("Tonal space path:")
        # Compute the tonal path (coordinates) from the result
        path = formalism.semantics_to_coordinates(result.semantics)
        points, timings = zip(*path)
        print ", ".join(coordinates_to_roman_names(points))
        _print()

    if options.play or options.audio is not None:
        _print("Building pitch structure from result...")
        # Convert the semantics into a list of TS points
        path = formalism.semantics_to_coordinates(result.semantics)
        # Decide on chord types
        # For now, since we don't know the original chords, use dom7
        #  for dom chords, maj for subdoms, and M7 for tonics
        fun_chords = {
            'T': 'M7',
            'D': '7',
            'S': '',
        }
        functions = formalism.semantics_to_functions(result.semantics)
        chord_types = [(fun_chords[f], t) for (f, t) in functions]

        tones = path_to_tones(path, chord_types=chord_types, double_root=True)

        _print("Rendering audio samples...")
        samples = tones.render()
        if options.audio is not None:
            filename = os.path.abspath(options.audio)
            _print("Writing wave data to %s" % filename)
            save_wave_data(samples, filename)
        if options.play:
            _print("Playing...")
            play_audio(samples, wait_for_end=True)
        _print()
Example #2
0
def main():
    usage = "%prog [options] <results-file> [<result-number>=0]"
    parser = OptionParser(usage=usage)
    parser.add_option("-q", "--quiet", dest="quiet", action="store_true", help="only output the requested information, no meta-info.")
    parser.add_option("-p", "--print", dest="printout", action="store_true", help="output the result to stdout.")
    parser.add_option("--path", dest="path", action="store_true", help="display the fully-specified tonal space path.")
    parser.add_option("--play", dest="play", action="store_true", help="use the harmonical to play the root sequence of the result's semantics.")
    parser.add_option("--audio", dest="audio", action="store", help="use the harmonical to render the root sequence, as with --play, and store the result to a wave file.")
    options, arguments = parser.parse_args()
    
    # Just get the default formalism
    formalism = get_default_formalism()
    
    def _print(string=""):
        if not options.quiet:
            print >>sys.stderr, string
        
    if len(arguments) == 0:
        print >>sys.stderr, "Specify a file to read the results from"
        sys.exit(1)
    results = ParseResults.from_file(arguments[0])
    
    if len(arguments) > 1:
        res_num = int(arguments[1])
    else:
        res_num = 0
    prob,result = results.sorted_results[res_num]
    
    if options.printout:
        _print("Result:")
        # Just display the resulting category
        print result
        _print()
        
    if options.path:
        _print("Tonal space path:")
        # Compute the tonal path (coordinates) from the result
        path = formalism.semantics_to_coordinates(result.semantics)
        points,timings = zip(*path)
        print ", ".join(coordinates_to_roman_names(points))
        _print()
        
    if options.play or options.audio is not None:
        _print("Building pitch structure from result...")
        # Convert the semantics into a list of TS points
        path = formalism.semantics_to_coordinates(result.semantics)
        # Decide on chord types
        # For now, since we don't know the original chords, use dom7 
        #  for dom chords, maj for subdoms, and M7 for tonics
        fun_chords = {
            'T' : 'M7',
            'D' : '7',
            'S' : '',
        }
        functions = formalism.semantics_to_functions(result.semantics)
        chord_types = [(fun_chords[f],t) for (f,t) in functions]
        
        tones = path_to_tones(path, chord_types=chord_types, double_root=True)
        
        _print("Rendering audio samples...")
        samples = tones.render()
        if options.audio is not None:
            filename = os.path.abspath(options.audio)
            _print("Writing wave data to %s" % filename)
            save_wave_data(samples, filename)
        if options.play:
            _print("Playing...")
            play_audio(samples, wait_for_end=True)
        _print()
Example #3
0
 def _result_callback(response):
     if response is None:
         # Empty input, or the subprocess doesn't want us to do anything
         return
     else:
         # Mark this input as completed
         global completed_parses
         completed_parses[response['identifier']] = True
         
         if response['results'] is None:
             # There was some error: check what it was
             error = response['error']
             print >> sys.stderr, "Error parsing %s" % str(response['input'])
             print >> sys.stderr, "The error was:"
             print >>sys.stderr, error[2]
             global parse_exit_status
             parse_exit_status = 1
         else:
             # Keep this together with all the other processes' responses
             all_results.append(response)
             print "Parsed: %s" % response['input']
             
             # Run any cleanup routines that the formalism defines
             grammar.formalism.clean_results(response['results'])
             
             # Remove complex results if atomic-only option has been set
             if options.atoms_only:
                 response['results'] = remove_complex_categories(response['results'], grammar.formalism)
             
             if not options.no_results:
                 print "Results:"
                 list_results(response['results'])
             
             if output_dir is not None:
                 # Try getting a gold standard analysis if one has been 
                 #  associated with the input
                 gold = response['input'].get_gold_analysis()
                 
                 # Get the results with their probabilities
                 top_results = [(getattr(res, 'probability', None), res) \
                                     for res in response['results']]
                 if options.topn is not None:
                     # Limit the results that get stored
                     top_results = list(reversed(sorted(
                                             top_results)))[:options.topn]
                 # Output the results to a file
                 presults = ParseResults(
                                 top_results, 
                                 signs=True,
                                 gold_parse=gold,
                                 timed_out=response['timed_out'],
                                 cpu_time=response['time'])
                 filename = get_output_filename(response['identifier'])
                 presults.save(filename)
                 print "Parse results output to %s" % filename
             
             if time_parse:
                 print "Parse took %f seconds" % response['time']
                 
             if options.lh_analysis:
                 print >>sys.stderr, "\nLonguet-Higgins tonal space analysis for each result:"
                 # Output the tonal space path for each result
                 for i,result in enumerate(response['results']):
                     path = grammar.formalism.sign_to_coordinates(result)
                     coords,times = zip(*path)
                     print "%d> %s" % (i, ", ".join(
                         ["%s@%s" % (crd,time) for (crd,time) in 
                                 zip(coordinates_to_roman_names(coords),times)]))
                     
             if options.lh_coord:
                 print >>sys.stderr, "\nLonguet-Higgins tonal space coordinates for each result:"
                 # Output the tonal space path for each result
                 for i,result in enumerate(response['results']):
                     path = grammar.formalism.sign_to_coordinates(result)
                     print "%d> %s" % (i, ", ".join(["(%d,%d)@%s" % (x,y,t) for ((x,y),t) in path]))
             
             # Print out any messages the parse routine sent to us
             for message in response['messages']:
                 print message
                 
             # Print as summary of what we've completed
             num_completed = len(filter(lambda x:x[1], completed_parses.items()))
             if not stdinput:
                 if not options.no_progress:
                     print format_table([
                             [str(ident), 
                              "Complete" if completed_parses[ident] else ""]
                                 for ident in sorted(completed_parses.keys())])
                 if num_inputs is None:
                     print "\nCompleted %d parses" % num_completed
                 else:
                     print "\nCompleted %d/%d parses" % (num_completed, num_inputs)
                 
             # Enter interactive mode now if requested in options
             # Don't do this is we're in a process pool
             if not multiprocessing and options.interactive:
                 print 
                 from jazzparser.shell import interactive_shell
                 env = {}
                 env.update(globals())
                 env.update(locals())
                 interactive_shell(response['results'],
                                   options,
                                   response['tagger'], 
                                   response['parser'],
                                   grammar.formalism,
                                   env,
                                   input_data=response['input'])
             print
             # Flush the output to make sure everything gets out before we start the next one
             sys.stderr.flush()
             sys.stdout.flush()