-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
94 lines (77 loc) · 2.67 KB
/
app.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import requests
from PIL import Image, ImageColor
from flask import Flask, make_response, redirect, request, send_file
from io import BytesIO
import os
import math
PIXEL = " "
MAX_WIDTH = 150
ASPECT_RATIO = 2.3 # characters in a terminal aren't square so we have to stretch the image to compensate.
# Takes a tuple and returns the required characters to print it to terminal.
# 4 element: (r,g,b,opacity)
# 3 element: (r,g,b)
def pixelchar(color):
# Handling transparency.
if len(color) == 4:
if color[3] == 0:
return "\u001b[0m" + PIXEL
# normalize color from 24-bit 3*(0-255) to 8-bit 3*(0-5)
r,g,b = color[0:3]
r = math.floor(r/51)
g = math.floor(g/51)
b = math.floor(b/51)
# create the appropriate ansi control character.
color = 16 + 36 * r + 6 * g + b
ccode = "\u001b[48;5;{}m".format(color)
return ccode + PIXEL
def image_to_characters(img):
rows = []
for row in range(img.size[1]):
rstring = ""
for column in range(img.size[0]):
rstring += pixelchar(img.getpixel((column, row)))
rstring += "\u001b[0m" # Reset code.
rows.append(rstring)
return rows
app = Flask(__name__)
# Resize to a max width of 70px
def get_new_size(size, width):
if size[0] <= width:
return size
return (width, int(size[1]/(size[0]/width)))
@app.before_request
def before_request():
if not request.is_secure and (app.env != "development"):
url = request.url.replace("http://", "https://", 1)
code = 301
return redirect(url, code=code)
@app.route('/')
def base_route():
url = request.args.get('url', None)
if url is None:
img = Image.open('raccoon.png')
else:
try:
response = requests.get(url)
img = Image.open(BytesIO(response.content))
if img.mode == 'P':
img = img.convert('RGBA')
except Exception as ex:
return make_response("Error: {}".format(type(ex).__name__), 400)
width = min(int(request.args.get('width', MAX_WIDTH)), 200)
img = img.resize((int(img.size[0]*ASPECT_RATIO), img.size[1]))
img = img.resize(get_new_size(img.size, width))
resp = redirect("/about", 302)
lines = image_to_characters(img)
for i in range(len(lines)):
resp.headers['{}'.format(i).ljust(3, '-')] = lines[i]
return resp
@app.route('/about')
def hello():
return send_file('./about.html')
if __name__ == '__main__':
port = os.getenv("PORT", 5000)
if app.env != "development":
app.run(host='0.0.0.0', port=port, ssl_context=('/certs/cert.pem', '/certs/privkey.pem'))
else:
app.run(host='0.0.0.0', port=port, debug=True)