2 from collections
import namedtuple
10 from sqlalchemy
.sql
import func
12 import whoosh
.filedb
.filestore
13 import whoosh
.filedb
.fileindex
15 from whoosh
.qparser
import QueryParser
17 import whoosh
.spelling
19 from pokedex
.db
import connect
20 import pokedex
.db
.tables
as tables
21 from pokedex
.roomaji
import romanize
23 __all__
= ['PokedexLookup']
26 rx_is_number
= re
.compile('^\d+$')
28 LookupResult
= namedtuple('LookupResult',
29 ['object', 'indexed_name', 'name', 'language', 'iso3166', 'exact'])
31 class LanguageWeighting(whoosh
.scoring
.Weighting
):
32 """A scoring class that forces otherwise-equal English results to come
33 before foreign results.
36 def score(self
, searcher
, fieldnum
, text
, docnum
, weight
, QTF
=1):
37 doc
= searcher
.stored_fields(docnum
)
38 if doc
['language'] == None:
39 # English (well, "default"); leave it at 1
41 elif doc
['language'] == u
'Roomaji':
42 # Give Roomaji a little boost; it's most likely to be searched
45 # Everything else can drop down the totem pole
49 class PokedexLookup(object):
50 INTERMEDIATE_LOOKUP_RESULTS
= 25
51 MAX_LOOKUP_RESULTS
= 10
53 # Dictionary of table name => table class.
54 # Need the table name so we can get the class from the table name after we
55 # retrieve something from the index
56 indexed_tables
= dict(
57 (cls
.__tablename__
, cls
)
70 def __init__(self
, directory
=None, session
=None, recreate
=False):
71 """Opens the whoosh index stored in the named directory. If the index
72 doesn't already exist, it will be created.
75 Directory containing the index. Defaults to a location within the
76 `pokedex` egg directory.
79 If the index needs to be created, this database session will be
80 used. Defaults to an attempt to connect to the default SQLite
81 database installed by `pokedex setup`.
84 If set to True, the whoosh index will be created even if it already
88 # By the time this returns, self.index, self.speller, and self.session
93 directory
= pkg_resources
.resource_filename('pokedex',
97 self
.session
= session
99 self
.session
= connect()
101 # Attempt to open or create the index
102 directory_exists
= os
.path
.exists(directory
)
103 if directory_exists
and not recreate
:
104 # Already exists; should be an index! Bam, done.
106 self
.index
= whoosh
.index
.open_dir(directory
, indexname
='MAIN')
107 spell_store
= whoosh
.filedb
.filestore
.FileStorage(directory
)
108 self
.speller
= whoosh
.spelling
.SpellChecker(spell_store
)
110 except whoosh
.index
.EmptyIndexError
as e
:
111 # Apparently not a real index. Fall out and create it
114 # Delete and start over if we're going to bail anyway.
115 if directory_exists
and recreate
:
116 # Be safe and only delete if it looks like a whoosh index, i.e.,
117 # everything starts with _
118 if all(f
[0] == '_' for f
in os
.listdir(directory
)):
119 shutil
.rmtree(directory
)
120 directory_exists
= False
122 if not directory_exists
:
127 schema
= whoosh
.fields
.Schema(
128 name
=whoosh
.fields
.ID(stored
=True),
129 table
=whoosh
.fields
.ID(stored
=True),
130 row_id
=whoosh
.fields
.ID(stored
=True),
131 language
=whoosh
.fields
.STORED
,
132 iso3166
=whoosh
.fields
.STORED
,
133 display_name
=whoosh
.fields
.STORED
, # non-lowercased name
136 self
.index
= whoosh
.index
.create_in(directory
, schema
=schema
,
138 writer
= self
.index
.writer()
140 # Index every name in all our tables of interest
141 # speller_entries becomes a list of (word, score) tuples; the score is
142 # 2 for English names, 1.5 for Roomaji, and 1 for everything else. I
143 # think this biases the results in the direction most people expect,
144 # especially when e.g. German names are very similar to English names
146 for cls
in self
.indexed_tables
.values():
147 q
= self
.session
.query(cls
)
149 for row
in q
.yield_per(5):
150 row_key
= dict(table
=unicode(cls
.__tablename__
),
151 row_id
=unicode(row
.id))
153 def add(name
, language
, iso3166
, score
):
154 normalized_name
= self
.normalize_name(name
)
157 name
=normalized_name
, display_name
=name
,
158 language
=language
, iso3166
=iso3166
,
162 speller_entries
.append((normalized_name
, score
))
165 # Add the basic English name to the index
166 if cls
== tables
.Pokemon
:
167 # Pokémon need their form name added
169 add(row
.full_name
, None, u
'us', 1)
171 # If this is a default form, ALSO add the unadorned name,
172 # so 'Deoxys' alone will still do the right thing
173 if row
.forme_name
and not row
.forme_base_pokemon_id
:
174 add(row
.name
, None, u
'us', 1)
176 add(row
.name
, None, u
'us', 1)
178 # Some things also have other languages' names
179 # XXX other language form names..?
180 for foreign_name
in getattr(row
, 'foreign_names', []):
181 moonspeak
= foreign_name
.name
182 if row
.name
== moonspeak
:
183 # Don't add the English name again as a different
184 # language; no point and it makes spell results
188 add(moonspeak
, foreign_name
.language
.name
,
189 foreign_name
.language
.iso3166
,
193 if foreign_name
.language
.name
== 'Japanese':
194 roomaji
= romanize(foreign_name
.name
)
195 add(roomaji
, u
'Roomaji', u
'jp', 8)
199 # Construct and populate a spell-checker index. Quicker to do it all
200 # at once, as every call to add_* does a commit(), and those seem to be
202 self
.speller
= whoosh
.spelling
.SpellChecker(self
.index
.storage
)
203 self
.speller
.add_scored_words(speller_entries
)
206 def normalize_name(self
, name
):
207 """Strips irrelevant formatting junk from name input.
209 Specifically: everything is lowercased, and accents are removed.
211 # http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string
212 # Makes sense to me. Decompose by Unicode rules, then remove combining
213 # characters, then recombine. I'm explicitly doing it this way instead
214 # of testing combining() because Korean characters apparently
215 # decompose! But the results are considered letters, not combining
216 # characters, so testing for Mn works well, and combining them again
217 # makes them look right.
218 nkfd_form
= unicodedata
.normalize('NFKD', unicode(name
))
219 name
= u
"".join(c
for c
in nkfd_form
220 if unicodedata
.category(c
) != 'Mn')
221 name
= unicodedata
.normalize('NFC', name
)
229 def _parse_table_name(self
, name
):
230 """Takes a singular table name, table name, or table object and returns
233 Returns None for a bogus name.
235 if hasattr(name
, '__tablename__'):
236 return getattr(name
, '__tablename__')
237 elif name
in self
.indexed_tables
:
239 elif name
+ 's' in self
.indexed_tables
:
242 # Bogus. Be nice and return dummy
245 def _whoosh_records_to_results(self
, records
, exact
=True):
246 """Converts a list of whoosh's indexed records to LookupResult tuples
247 containing database objects.
249 # XXX this 'exact' thing is getting kinda leaky. would like a better
250 # way to handle it, since only lookup() cares about fuzzy results
253 for record
in records
:
255 seen_key
= record
['table'], record
['row_id']
258 seen
[seen_key
] = True
260 cls
= self
.indexed_tables
[record
['table']]
261 obj
= self
.session
.query(cls
).get(record
['row_id'])
263 results
.append(LookupResult(object=obj
,
264 indexed_name
=record
['name'],
265 name
=record
['display_name'],
266 language
=record
['language'],
267 iso3166
=record
['iso3166'],
273 def lookup(self
, input, valid_types
=[], exact_only
=False):
274 """Attempts to find some sort of object, given a name.
276 Returns a list of named (object, name, language, iso3166, exact)
277 tuples. `object` is a database object, `name` is the name under which
278 the object was found, `language` and `iso3166` are the name and country
279 code of the language in which the name was found, and `exact` is True
283 This function currently ONLY does fuzzy matching if there are no exact
286 Formes are not returned unless requested; "Shaymin" will return only
289 Extraneous whitespace is removed with extreme prejudice.
292 - Names: "Eevee", "Surf", "Run Away", "Payapa Berry", etc.
293 - Foreign names: "Iibui", "Eivui"
294 - Fuzzy names in whatever language: "Evee", "Ibui"
295 - IDs: "133", "192", "250"
297 - Type restrictions. "type:psychic" will only return the type. This
298 is how to make ID lookup useful. Multiple type specs can be entered
299 with commas, as "move,item:1". If `valid_types` are provided, any
300 type prefix will be ignored.
301 - Alternate formes can be specified merely like "wash rotom".
304 Name of the thing to look for.
307 A list of table objects or names, e.g., `['pokemon', 'moves']`. If
308 this is provided, only results in one of the given tables will be
312 If True, only exact matches are returned. If set to False (the
313 default), and the provided `name` doesn't match anything exactly,
314 spelling correction will be attempted.
317 name
= self
.normalize_name(input)
321 # Remove any type prefix (pokemon:133) before constructing a query
323 prefix_chunk
, name
= name
.split(':', 1)
327 # Only use types from the query string if none were explicitly
329 prefixes
= prefix_chunk
.split(',')
330 valid_types
= [_
.strip() for _
in prefixes
]
334 return self
.random_lookup(valid_types
=valid_types
)
336 # Do different things depending what the query looks like
337 # Note: Term objects do an exact match, so we don't have to worry about
338 # a query parser tripping on weird characters in the input
339 if '*' in name
or '?' in name
:
341 query
= whoosh
.query
.Wildcard(u
'name', name
)
342 elif rx_is_number
.match(name
):
343 # Don't spell-check numbers!
345 query
= whoosh
.query
.Term(u
'row_id', name
)
348 query
= whoosh
.query
.Term(u
'name', name
)
350 ### Filter by type of object
352 for valid_type
in valid_types
:
353 table_name
= self
._parse_table_name(valid_type
)
355 # Quietly ignore bogus valid_types; more likely to DTRT
356 type_terms
.append(whoosh
.query
.Term(u
'table', table_name
))
359 query
= query
& whoosh
.query
.Or(type_terms
)
363 searcher
= self
.index
.searcher()
364 # XXX is this kosher? docs say search() takes a weighting arg, but it
366 searcher
.weighting
= LanguageWeighting()
367 results
= searcher
.search(query
,
368 limit
=self
.INTERMEDIATE_LOOKUP_RESULTS
)
370 # Look for some fuzzy matches if necessary
371 if not exact_only
and not results
:
375 for suggestion
in self
.speller
.suggest(
376 name
, self
.INTERMEDIATE_LOOKUP_RESULTS
):
378 query
= whoosh
.query
.Term('name', suggestion
)
379 results
.extend(searcher
.search(query
))
381 ### Convert results to db objects
382 objects
= self
._whoosh_records_to_results(results
, exact
=exact
)
384 # Only return up to 10 matches; beyond that, something is wrong. We
385 # strip out duplicate entries above, so it's remotely possible that we
386 # should have more than 10 here and lost a few. The speller returns 25
387 # to give us some padding, and should avoid that problem. Not a big
388 # deal if we lose the 25th-most-likely match anyway.
389 return objects
[:self
.MAX_LOOKUP_RESULTS
]
392 def random_lookup(self
, valid_types
=[]):
393 """Returns a random lookup result from one of the provided
398 for valid_type
in valid_types
:
399 table_name
= self
._parse_table_name(valid_type
)
401 tables
.append(self
.indexed_tables
[table_name
])
404 # n.b.: It's possible we got a list of valid_types and none of them
405 # were valid, but this function is guaranteed to return
406 # *something*, so it politely selects from the entire index isntead
407 tables
= self
.indexed_tables
.values()
409 # Rather than create an array of many hundred items and pick randomly
410 # from it, just pick a number up to the total number of potential
411 # items, then pick randomly from that, and partition the whole range
412 # into chunks. This also avoids the slight problem that the index
413 # contains more rows (for languages) for some items than others.
414 # XXX ought to cache this (in the index?) if possible
418 count
= self
.session
.query(table
).count()
420 partitions
.append((table
, count
))
422 n
= random
.randint(1, total
)
423 while n
> partitions
[0][1]:
424 n
-= partitions
[0][1]
427 return self
.lookup(unicode(n
), valid_types
=[ partitions
[0][0] ])
429 def prefix_lookup(self
, prefix
):
430 """Returns terms starting with the given exact prefix.
432 No special magic is currently done with the name; type prefixes are not
436 query
= whoosh
.query
.Prefix(u
'name', self
.normalize_name(prefix
))
438 searcher
= self
.index
.searcher()
439 searcher
.weighting
= LanguageWeighting()
440 results
= searcher
.search(query
) # XXX , limit=self.MAX_LOOKUP_RESULTS)
442 return self
._whoosh_records_to_results(results
)