Skip to content

Instantly share code, notes, and snippets.

@e000
Last active December 19, 2015 15:18
Show Gist options
  • Save e000/5279695 to your computer and use it in GitHub Desktop.
Save e000/5279695 to your computer and use it in GitHub Desktop.
import dawg, flask, time, string
app = flask.Flask(__name__)
trie = None
NUM_RESULTS = 30
DICT_FILE = "/usr/share/dict/words"
_index_html = """
<html>
<head>
<title>DAWG 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) {
$scope.query = $scope.query.toLowerCase();
$http.get("/s/" + escape($scope.query)).then(function(r) {
$scope.results = r.data.results;
$scope.ms_p = r.data.ms / 1000;
$scope.r_query = r.data.query;
});
} 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/ DAWG Demo</h1>
<input type="text" ng-change="doAutoComplete()" ng-model="query" placeholder="query">
<ul>
<li ng-repeat="result in results">
<b>{{ r_query }}</b>{{ result.substr(r_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)
results = []
i = NUM_RESULTS
qlen = len(query)
for key in trie.iterkeys(query):
results.append(key)
i -= 1
if not i:
break
return flask.jsonify(results = results, ms = long(time.time() * 1000000) - t, query=query)
@app.route("/meta")
def meta():
return flask.jsonify(len=len(trie))
@app.route("/")
def index():
return _index_html
def build_trie():
s = time.time()
global trie
with open(DICT_FILE) as fp:
trie = dawg.CompletionDAWG(i.lower().strip() for i in fp)
print "built trie in", time.time() - s, "seconds."
if __name__ == '__main__':
build_trie()
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment