1 | from galaxy.eggs import require |
---|
2 | # Whoosh is compatible with Python 2.5+ Try to import Whoosh and set flag to indicate whether tool search is enabled. |
---|
3 | try: |
---|
4 | require( "Whoosh" ) |
---|
5 | |
---|
6 | from whoosh.filedb.filestore import RamStorage |
---|
7 | from whoosh.fields import Schema, STORED, ID, KEYWORD, TEXT |
---|
8 | from whoosh.index import Index |
---|
9 | from whoosh.qparser import QueryParser |
---|
10 | tool_search_enabled = True |
---|
11 | schema = Schema( id = STORED, title = TEXT, description = TEXT, help = TEXT ) |
---|
12 | except ImportError, e: |
---|
13 | tool_search_enabled = False |
---|
14 | schema = None |
---|
15 | |
---|
16 | class ToolBoxSearch( object ): |
---|
17 | """ |
---|
18 | Support searching tools in a toolbox. This implementation uses |
---|
19 | the "whoosh" search library. |
---|
20 | """ |
---|
21 | |
---|
22 | def __init__( self, toolbox ): |
---|
23 | """ |
---|
24 | Create a searcher for `toolbox`. |
---|
25 | """ |
---|
26 | self.toolbox = toolbox |
---|
27 | self.enabled = tool_search_enabled |
---|
28 | if tool_search_enabled: |
---|
29 | self.build_index() |
---|
30 | |
---|
31 | def build_index( self ): |
---|
32 | self.storage = RamStorage() |
---|
33 | self.index = self.storage.create_index( schema ) |
---|
34 | writer = self.index.writer() |
---|
35 | ## TODO: would also be nice to search section headers. |
---|
36 | for id, tool in self.toolbox.tools_by_id.iteritems(): |
---|
37 | def to_unicode( a_basestr ): |
---|
38 | if type( a_basestr ) is str: |
---|
39 | return unicode( a_basestr, 'utf-8' ) |
---|
40 | else: |
---|
41 | return a_basestr |
---|
42 | |
---|
43 | writer.add_document( id=id, title=to_unicode(tool.name), description=to_unicode(tool.description), help=to_unicode(tool.help) ) |
---|
44 | writer.commit() |
---|
45 | |
---|
46 | def search( self, query, return_attribute='id' ): |
---|
47 | if not tool_search_enabled: |
---|
48 | return [] |
---|
49 | searcher = self.index.searcher() |
---|
50 | parser = QueryParser( "help", schema = schema ) |
---|
51 | # Set query to search title, description, and help. |
---|
52 | query = "title:query OR description:query OR help:query".replace( "query", query ) |
---|
53 | results = searcher.search( parser.parse( query ), minscore=1.5 ) |
---|
54 | print results.scores |
---|
55 | return [ result[ return_attribute ] for result in results ] |
---|