Last active
December 15, 2015 15:09
-
-
Save e000/5279314 to your computer and use it in GitHub Desktop.
Demo of using marisa's predictive search + flask + angular.js.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import marisa, flask, time | |
app = flask.Flask(__name__) | |
trie = marisa.Trie() | |
agent = marisa.Agent() | |
NUM_RESULTS = 30 | |
DICT_FILE = "/usr/share/dict/words" | |
_index_html = """ | |
<html> | |
<head> | |
<title>Marisa Predictive Search Demo + AngularJS</title> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.1/angular.min.js"></script> | |
<script> | |
function SearchCtrl($scope, $http) { | |
$scope.doAutoComplete = function() { | |
if($scope.query) | |
$http.get("/s/" + escape($scope.query = $scope.query.toLowerCase())).then(function(r) { | |
$scope.results = r.data.results, $scope.ms_p = r.data.ms / 1000; | |
}); | |
else | |
$scope.results = [], $scope.ms_p = 0; | |
} | |
$http.get("/meta").then(function(r) { | |
$scope.meta = r.data; | |
}); | |
} | |
</script> | |
</head> | |
<body ng-app=""> | |
<div ng-controller="SearchCtrl"> | |
<h1>Dict Autocomplete w/ Marisa Demo</h1> | |
<input type="text" ng-change="doAutoComplete()" ng-model="query" placeholder="query"> | |
<ul> | |
<li ng-repeat="result in results"> | |
<b>{{ query }}</b>{{ result.substr(query.length) }} | |
</li> | |
</ul> | |
<i ng-show="ms_p"><b>{{ms_p}}</b> ms in flask</i> <br /> | |
<hr> | |
<i>{{meta}}</i> | |
</div> | |
</body> | |
</html> | |
""" | |
@app.route("/s/<query>") | |
def search(query): | |
t = long(time.time() * 1000000) | |
agent.set_query(str(query)) | |
results = [] | |
i = NUM_RESULTS | |
while i and trie.predictive_search(agent): | |
i -= 1 | |
results.append(agent.key_str()) | |
return flask.jsonify(results = results, ms = long(time.time() * 1000000) - t) | |
@app.route("/meta") | |
def meta(): | |
return flask.jsonify(num_keys=trie.num_keys(), num_tries=trie.num_tries(), | |
num_nodes=trie.num_nodes(), io_size=trie.io_size()) | |
@app.route("/") | |
def index(): | |
return _index_html | |
def build_trie(): | |
s = time.time() | |
ks = marisa.Keyset() | |
with open(DICT_FILE) as fp: | |
for l in fp: | |
ks.push_back(l.lower().strip()) | |
trie.build(ks) | |
print "built trie in", time.time() - s, "seconds." | |
print dict(num_keys=trie.num_keys(), num_tries=trie.num_tries(), | |
num_nodes=trie.num_nodes(), io_size=trie.io_size()) | |
build_trie() | |
if __name__ == '__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment