forked from captbaritone/hss-urlmeme
/
url.py
73 lines (56 loc) · 1.52 KB
/
url.py
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
import re
import os
from flask import Flask, render_template, request, redirect
from ngram import NGram
APP_ROOT = os.path.dirname(__file__)
app = Flask(__name__, static_url_path='/static')
IMAGES = {
"garland-dance.gif": [
"garland dance",
"trice dance",
"gtrice dance"
],
"ofer-uggs.jpg": [
"ofer uggs",
"goldstein uggs",
"tulioz uggs"
],
"dcash.jpg": [
"daniel cash",
"d cash",
"d cache",
"d money",
"d ram"
]
}
def replace_underscore(string):
return re.sub(r'_', ' ', string)
def tokenize(string):
return replace_underscore(string.lower())
def guess_image(name):
'''
Guess which meme image they mean by finding the alias with greatest ngram
similarity
'''
name = tokenize(name)
best = '404'
best_score = None
for guess_image, names in IMAGES.iteritems():
for guess in names:
score = NGram.compare(guess, name)
if best_score is None or score > best_score:
best_score = score
best = guess_image
app.logger.info('Pick image %s for name "%s"' % (best, name))
return best
@app.route("/")
def help():
return render_template('help.html', base_url=request.base_url)
@app.route('/<name>')
def image(name):
if name.endswith(('.png', '.jpg', '.gif')):
name = name[:-4]
image = guess_image(name)
return redirect("/static/images/" + image, code=301)
if __name__ == "__main__":
app.run(debug=True)