+ def __init__(self, directory=None, session=None):
+ """Opens the whoosh index stored in the named directory. If the index
+ doesn't already exist, it will be created.
+
+ `directory`
+ Directory containing the index. Defaults to a location within the
+ `pokedex` egg directory.
+
+ `session`
+ Used for creating the index and retrieving objects. Defaults to an
+ attempt to connect to the default SQLite database installed by
+ `pokedex setup`.
+ """
+
+ # By the time this returns, self.index, self.speller, and self.session
+ # must be set
+
+ # If a directory was not given, use the default
+ if directory is None:
+ directory = get_default_index_dir()
+
+ self.directory = directory
+
+ if session:
+ self.session = session
+ else:
+ self.session = connect()
+
+ # Attempt to open or create the index
+ if not os.path.exists(directory) or not os.listdir(directory):
+ # Directory doesn't exist OR is empty; caller needs to use
+ # rebuild_index before doing anything. Provide a dummy object that
+ # complains when used
+ self.index = UninitializedIndex()
+ self.speller = UninitializedIndex()
+ return
+
+ # Otherwise, already exists; should be an index! Bam, done.
+ # Note that this will explode if the directory exists but doesn't
+ # contain an index; that's a feature
+ try:
+ self.index = whoosh.index.open_dir(directory, indexname='MAIN')
+ except whoosh.index.EmptyIndexError:
+ raise IOError(
+ "The index directory already contains files. "
+ "Please use a dedicated directory for the lookup index."
+ )
+
+ # Create speller, and done
+ spell_store = whoosh.filedb.filestore.FileStorage(directory)
+ self.speller = whoosh.spelling.SpellChecker(spell_store,
+ **self.SPELLER_OPTIONS)
+
+
+ def rebuild_index(self):
+ """Creates the index from scratch."""
+
+ schema = whoosh.fields.Schema(
+ name=whoosh.fields.ID(stored=True),
+ table=whoosh.fields.ID(stored=True),
+ row_id=whoosh.fields.ID(stored=True),
+ language=whoosh.fields.STORED,
+ iso639=whoosh.fields.ID(stored=True),
+ iso3166=whoosh.fields.ID(stored=True),
+ display_name=whoosh.fields.STORED, # non-lowercased name
+ )
+
+ if os.path.exists(self.directory):
+ # create_in() isn't totally reliable, so just nuke whatever's there
+ # manually. Try to be careful about this...
+ for f in os.listdir(self.directory):
+ if re.match('^_?(MAIN|SPELL)_', f):
+ os.remove(os.path.join(self.directory, f))
+ else:
+ os.mkdir(self.directory)
+
+ self.index = whoosh.index.create_in(self.directory, schema=schema,
+ indexname='MAIN')
+ writer = self.index.writer()
+
+ # Index every name in all our tables of interest
+ speller_entries = set()
+ for cls in self.indexed_tables.values():
+ q = self.session.query(cls)
+
+ for row in q.yield_per(5):
+ row_key = dict(table=unicode(cls.__tablename__),
+ row_id=unicode(row.id))
+
+ def add(name, language, iso639, iso3166):
+ normalized_name = self.normalize_name(name)
+
+ writer.add_document(
+ name=normalized_name, display_name=name,
+ language=language, iso639=iso639, iso3166=iso3166,
+ **row_key
+ )
+
+ speller_entries.add(normalized_name)
+
+
+ # Add the basic English name to the index
+ if cls == tables.Pokemon:
+ # Don't re-add alternate forms of the same Pokémon; they'll
+ # be added as Pokémon forms instead
+ if not row.is_base_form:
+ continue
+ elif cls == tables.PokemonForm:
+ if row.name:
+ add(row.pokemon_name, None, u'en', u'us')
+ continue
+
+ add(row.name, None, u'en', u'us')
+
+ # Some things also have other languages' names
+ # XXX other language form names..?
+ for foreign_name in getattr(row, 'foreign_names', []):
+ moonspeak = foreign_name.name
+ if row.name == moonspeak:
+ # Don't add the English name again as a different
+ # language; no point and it makes spell results
+ # confusing
+ continue
+
+ add(moonspeak, foreign_name.language.name,
+ foreign_name.language.iso639,
+ foreign_name.language.iso3166)
+
+ # Add Roomaji too
+ if foreign_name.language.name == 'Japanese':
+ roomaji = romanize(foreign_name.name)
+ add(roomaji, u'Roomaji', u'ja', u'jp')
+
+ writer.commit()
+
+ # Construct and populate a spell-checker index. Quicker to do it all
+ # at once, as every call to add_* does a commit(), and those seem to be
+ # expensive
+ self.speller = whoosh.spelling.SpellChecker(self.index.storage, mingram=2,
+ **self.SPELLER_OPTIONS)
+ self.speller.add_words(speller_entries)
+
+
+ def normalize_name(self, name):
+ """Strips irrelevant formatting junk from name input.
+
+ Specifically: everything is lowercased, and accents are removed.
+ """
+ # http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string
+ # Makes sense to me. Decompose by Unicode rules, then remove combining
+ # characters, then recombine. I'm explicitly doing it this way instead
+ # of testing combining() because Korean characters apparently
+ # decompose! But the results are considered letters, not combining
+ # characters, so testing for Mn works well, and combining them again
+ # makes them look right.
+ nkfd_form = unicodedata.normalize('NFKD', unicode(name))
+ name = u"".join(c for c in nkfd_form
+ if unicodedata.category(c) != 'Mn')
+ name = unicodedata.normalize('NFC', name)
+
+ name = name.strip()
+ name = name.lower()
+
+ return name
+
+
+ def _apply_valid_types(self, name, valid_types):
+ """Combines the enforced `valid_types` with any from the search string
+ itself and updates the query.
+
+ For example, a name of 'a,b:foo' and valid_types of b,c will search for
+ only `b`s named "foo".
+
+ Returns `(name, merged_valid_types, term)`, where `name` has had any type
+ prefix stripped, `merged_valid_types` combines the original
+ `valid_types` with the type prefix, and `term` is a query term for
+ limited to just the allowed types. If there are no type restrictions
+ at all, `term` will be None.
+ """
+
+ # Remove any type prefix (pokemon:133) first
+ user_valid_types = []
+ if ':' in name:
+ prefix_chunk, name = name.split(':', 1)
+ name = name.strip()
+
+ prefixes = prefix_chunk.split(',')
+ user_valid_types = []
+ for prefix in prefixes:
+ prefix = prefix.strip()
+ if prefix:
+ user_valid_types.append(prefix)