paulb@4 | 1 | #!/usr/bin/env python |
paulb@4 | 2 | |
paulb@20 | 3 | from parallel import start, Exchange, waitall |
paulb@10 | 4 | from Dict import Indexer, Searcher, Parser |
paulb@4 | 5 | |
paulb@10 | 6 | def apply_parser(channel, filename): |
paulb@10 | 7 | print "Parsing", filename |
paulb@10 | 8 | parser = Parser(filename) |
paulb@10 | 9 | parser.send_entries(channel) |
paulb@18 | 10 | print "Done", filename |
paulb@4 | 11 | |
paulb@6 | 12 | def get_searcher(filenames, window_size): |
paulb@10 | 13 | master_index = Indexer() |
paulb@4 | 14 | |
paulb@4 | 15 | # Start indexing. |
paulb@4 | 16 | |
paulb@6 | 17 | for i in range(0, len(filenames), window_size): |
paulb@6 | 18 | channels = [] |
paulb@6 | 19 | for filename in filenames[i:i + window_size]: |
paulb@10 | 20 | channels.append(start(apply_parser, filename)) |
paulb@4 | 21 | |
paulb@6 | 22 | # Start listening for responses. |
paulb@4 | 23 | |
paulb@6 | 24 | exchange = Exchange(channels) |
paulb@8 | 25 | while exchange.active(): |
paulb@32 | 26 | #print "Waiting for %d channels..." % len(exchange.active()) |
paulb@6 | 27 | for channel in exchange.ready(): |
paulb@10 | 28 | entry = channel.receive() |
paulb@10 | 29 | master_index.add_entry(entry) |
paulb@4 | 30 | |
paulb@12 | 31 | # Tidy up as we go. |
paulb@12 | 32 | |
paulb@12 | 33 | for channel in channels: |
paulb@12 | 34 | channel.close() |
paulb@12 | 35 | |
paulb@20 | 36 | waitall() |
paulb@20 | 37 | |
paulb@4 | 38 | # Provide a search interface. |
paulb@4 | 39 | |
paulb@10 | 40 | return Searcher(master_index.get_index()) |
paulb@4 | 41 | |
paulb@4 | 42 | if __name__ == "__main__": |
paulb@8 | 43 | import sys, os |
paulb@12 | 44 | |
paulb@12 | 45 | # Get the parameters. |
paulb@12 | 46 | |
paulb@8 | 47 | window_size, directory = int(sys.argv[1]), sys.argv[2] |
paulb@12 | 48 | |
paulb@12 | 49 | # Build a list of filenames. |
paulb@12 | 50 | |
paulb@8 | 51 | filenames = [os.path.join(directory, filename) for filename in os.listdir(directory)] |
paulb@10 | 52 | filenames = [filename for filename in filenames if os.path.isfile(filename)] |
paulb@8 | 53 | |
paulb@12 | 54 | # Get a searcher using an index built in parallel. |
paulb@12 | 55 | |
paulb@6 | 56 | searcher = get_searcher(filenames, window_size) |
paulb@20 | 57 | waitall() |
paulb@13 | 58 | |
paulb@12 | 59 | # Present a user interface. |
paulb@12 | 60 | |
paulb@32 | 61 | if "--noprompt" not in sys.argv: |
paulb@32 | 62 | while 1: |
paulb@32 | 63 | print "Pattern:", |
paulb@32 | 64 | pattern = raw_input() |
paulb@32 | 65 | print searcher.find(pattern) |
paulb@4 | 66 | |
paulb@4 | 67 | # vim: tabstop=4 expandtab shiftwidth=4 |