public
Last active

Demo of using marisa's predictive search + flask + angular.js.

  • Download Gist
marisa_autocomplete.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
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()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.