forked from piyush01123/Flask-Image-Gallery
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
271 lines (239 loc) · 10.4 KB
/
Copy pathapp.py
File metadata and controls
271 lines (239 loc) · 10.4 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
from flask import Flask
from flask import request
from flask import render_template
from flask import send_from_directory
from io import BytesIO
from PIL import Image, ImageSequence, GifImagePlugin
from threading import Thread
import os
import random
import time
import json
import requests
import glob
import sys
import base64
import argparse
import socket
# Constants
HUB75_WIDTH = 128
HUB75_HEIGHT = 64
# Add your upload function (to the matrix display) here
def upload_image(imagePath):
#return
UPLOAD_URL = "http://10.42.28.7/upload"
UPLOAD_FORM = "data"
with open(imagePath, "rb") as gif:
#print(f"Trying to upload {imagePath} to {UPLOAD_URL}!")
#requests.post(UPLOAD_URL, files = {UPLOAD_FORM: gif})
pass
# Flask app
app = Flask("pythonGIFChooser")
app.config['IMAGE_EXTS'] = [".gif"] # Only GIFs for now
# State variables
current_image = None
image_delay = 3 # in Minutes
next_image_time = 0 # Timestamp when next image should be shown
display_mode = "random" # random, sequential
def encode(x):
return base64.b64encode(x.encode('utf-8')).decode()
def decode(x):
return base64.b64decode(x.encode('utf-8')).decode()
def htmlColorToTuple(htmlcolor):
htmlcolor = htmlcolor.lstrip('#')
vals = [int(htmlcolor[i:i+2], 16) for i in (0, 2, 4)]
vals.append(255)# Add alpha
return tuple(vals)
GifImagePlugin.LOADING_STRATEGY = GifImagePlugin.LoadingStrategy.RGB_ALWAYS
@app.route('/', methods = ['GET'])
def home():
root_dir = app.config['ROOT_DIR']
image_paths = []
for root,dirs,files in os.walk(root_dir):
for file in files:
if any(file.endswith(ext) for ext in app.config['IMAGE_EXTS']):
path = os.path.join(root,file)
size = f"{os.path.getsize(path)/1000:0.1f}"
image_paths.append([encode(path), size])
current_imageVar = encode(current_image) if current_image is not None else "None"
return render_template('index.html', paths=image_paths, hub75width=HUB75_WIDTH, hub75height=HUB75_HEIGHT,
image_delay=image_delay, display_mode=display_mode, current_image=current_imageVar,
imageTime=next_image_time, currentTime=time.time(), threadActive=workerTH.is_alive())
@app.route('/cdn/<path:filepath>', methods = ['GET'])
def fetch_file(filepath):
if os.path.isfile(decode(filepath)):
dir,filename = os.path.split(decode(filepath))
return send_from_directory(dir, filename, as_attachment=False)
else:
return 404
@app.route('/cdn/current', methods = ['GET'])
def get_current():
current_imageVar = encode(current_image) if current_image is not None else "None"
return '{"status":"OK", "current_image":"'+current_imageVar+'", "image_delay_s":"'+str(int(image_delay*60))+'", "statusId":0}',200
@app.route('/cdn/upload', methods = ['POST'])
def create_file():
imageFile = request.files['imageData']
bgColor = request.form.get('customBGColor', '#000000')
bgColorRGB = htmlColorToTuple(bgColor)
imageDataB64 = base64.b64encode(imageFile.read())
if(imageDataB64 == ''):
retVal = {"status":"Please provide an image file in \"imageData\"", "statusId":-1}
return json.dumps(retVal),400
if(bgColorRGB[0]+bgColorRGB[1]+bgColorRGB[2] > 255):
retVal = {"status":"Please provide a darker image background!", "statusId":-1}
return json.dumps(retVal),400
try:
im = Image.open(BytesIO(base64.b64decode(imageDataB64)))
except Exception as e:
retVal = {"status":"Image could not be parsed properly!", "error":str(e), "statusId":-1}
return json.dumps(retVal),400
else:
# Modify GIF here
gif_duration = im.info['duration']
avg_duration = 0
count = 0
im.info["transparency"] = im.info["background"]
frames = [frame.copy() for frame in ImageSequence.Iterator(im)]
newFrames = []
for frame in frames:
print(frame.mode)
frame.thumbnail((HUB75_WIDTH,HUB75_HEIGHT), resample=Image.LANCZOS, reducing_gap=3.0)
avg_duration += frame.info['duration']
count += 1
newFrame = Image.new('RGBA', (HUB75_WIDTH,HUB75_HEIGHT), bgColorRGB)
newFrame.info["version"] = "GIF87a"
offset_x = int(max((HUB75_WIDTH - frame.size[0]) / 2, 0))
offset_y = int(max((HUB75_HEIGHT - frame.size[1]) / 2, 0))
offset_tuple = (offset_x, offset_y) #pack x and y into a tuple
newFrame.alpha_composite(frame.convert('RGBA'), offset_tuple)
newFrames.append(newFrame.convert("RGB"))
# Save GIF to disk
filepath = os.path.join(app.config['ROOT_DIR'], imageFile.filename)
avg_duration = int(avg_duration / count)
if avg_duration != gif_duration:
gif_duration = avg_duration
newFrames[0].save(filepath,
save_all = True, append_images = newFrames[1:],
optimize = False, duration = gif_duration, loop=0,
interlace=True, disposal=2)
retVal = {"statusId":0, "newFile":filepath}
return json.dumps(retVal),200
@app.route('/cdn/config', methods = ['POST'])
def setConfig():
global image_delay
global display_mode
data = request.form
try:
delay = float(data['image_delay'])
if delay < 1 or delay > 60:
return '{"status":"Invalid image delay provided! Must be between 1 and 60!", "statusId":-1}',400
image_delay = delay
mode = str(data['display_mode'])
if mode not in ["random", "sequential"]:
return '{"status":"Invalid display mode provided!", "statusId":-1}',400
display_mode = mode
return '{"status":"Set config!", "statusId":0}',200
except Exception as e:
return '{"status":"Invalid data provided!", "error":%s, "statusId":-1}' % str(e),400
@app.route('/cdn/show/<path:filepath>', methods = ['POST'])
def show_file(filepath):
global current_image
global next_image_time
if os.path.isfile(decode(filepath)):
current_image = decode(filepath)
next_image_time = 0 # Force next image to be shown
#print("Showing file: %s" % current_image)
return '{"status":"Showing image", "current_image":"'+encode(current_image)+'", "statusId":0}',200
else:
return '{"status":"Image not found", "statusId":-3}',404
@app.route('/cdn/del/<path:filepath>', methods = ['POST'])
def remove_file(filepath):
#return '{"status":"Image not found", "statusId":-5}',404
# Disabled for now
if os.path.isfile(decode(filepath)):
fullpath = decode(filepath)
#print("Deleting: %s" % fullpath)
if fullpath.startswith(app.config['ROOT_DIR']):
#print("Deleting file: %s" % fullpath)
os.remove(fullpath)
return '{"status":"Deleting Image", "statusId":0}',200
else:
return '{"status":"Image not found", "statusId":-4}',404
else:
return '{"status":"Image not found", "statusId":-5}',404
def worker_thread(root_dir):
global current_image
global image_delay
global next_image_time
global display_mode
while True:
if current_image is not None:
try:
upload_image(current_image)
except Exception as e:
pass # Fail silent if upload fails
while(time.time() < next_image_time):
time.sleep(2)
if(next_image_time == 0):
break
try:
if next_image_time != 0:
# Select next image only if we are not in "show" mode
if display_mode == "random":
image_paths = []
for root,dirs,files in os.walk(root_dir):
for file in files:
if any(file.endswith(ext) for ext in app.config['IMAGE_EXTS']):
image_paths.append(os.path.join(root,file))
current_image = random.choice(image_paths)
#print("Next image: %s" % current_image)
elif display_mode == "sequential":
image_paths = []
for root,dirs,files in os.walk(root_dir):
for file in files:
if any(file.endswith(ext) for ext in app.config['IMAGE_EXTS']):
image_paths.append(os.path.join(root,file))
if current_image is None:
current_image = image_paths[0]
else:
current_image = image_paths[(image_paths.index(current_image)+1)%len(image_paths)]
#print("Next image: %s" % current_image)
next_image_time = time.time() + image_delay*60
#time.sleep(image_delay*60)
except KeyboardInterrupt as e:
raise e
except Exception as e:
# Reset image selection if we have an error
display_mode = "random"
root,dirs,files = os.walk(root_dir)
for file in files:
if any(file.endswith(ext) for ext in app.config['IMAGE_EXTS']):
# Choose the first image we find
current_image = os.path.join(root,file)
break
next_image_time = time.time() + image_delay*60
pass
if __name__=="__main__":
parser = argparse.ArgumentParser('Usage: %prog [options]')
parser.add_argument('root_dir', help='Gallery root directory path')
parser.add_argument('-l', '--listen', dest='host', default='127.0.0.1', \
help='address to listen on [127.0.0.1]')
parser.add_argument('-p', '--port', metavar='PORT', dest='port', type=int, \
default=5000, help='port to listen on [5000]')
args = parser.parse_args()
# Create pid file for auto-restart
with open("./pid", "w") as pidFile:
pidFile.write(str(os.getpid()))
# Start with random Image
image_paths = []
for root,dirs,files in os.walk(args.root_dir):
for file in files:
if any(file.endswith(ext) for ext in app.config['IMAGE_EXTS']):
image_paths.append(os.path.join(root,file))
current_image = random.choice(image_paths)
next_image_time = time.time() + image_delay*60
#print("Next image: %s" % current_image)
workerTH = Thread(target=worker_thread,args=(args.root_dir,))
workerTH.start()
app.config['ROOT_DIR'] = args.root_dir
app.run(host=args.host, port=args.port, debug=False)