public
Last active

  • Download Gist
dawg_ps.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
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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.