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