-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
268 lines (223 loc) · 8.65 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
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
from flask import Flask, redirect, render_template, request, session, url_for, flash
from flask_dropzone import Dropzone
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
import os
from functools import wraps
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy import create_engine, Date
from database.tabledef import User, UserImage, ClassImage
from PIL import Image
import requests
from io import BytesIO
import datetime
from multiprocessing import Queue
import image_processing
import imagehash
image_queue = Queue()
image_processer = None
engine = create_engine('sqlite:///ap.db', echo=True)
app = Flask(__name__)
# Uploads settings
app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd() + '/uploads'
app.config['SECRET_KEY'] = 'supersecretkeygoeshere'
photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)
dropzone = Dropzone(app)
app.config['DROPZONE_UPLOAD_MULTIPLE'] = True
app.config['DROPZONE_ALLOWED_FILE_CUSTOM'] = True
app.config['DROPZONE_ALLOWED_FILE_TYPE'] = 'image/*'
app.config['DROPZONE_REDIRECT_VIEW'] = 'view_images'
def login_required(func):
@wraps(func)
def wrap(*args, **kwargs):
if session.get('user_id'):
return func(*args, **kwargs)
else:
flash('You need to login first')
return redirect(url_for('home'))
return wrap
@app.route('/')
def home(status=None):
if not session.get('user_id'):
return render_template('login.html', status=None)
Session = scoped_session(sessionmaker(bind=engine))
sess = Session()
query = sess.query(UserImage).filter(UserImage.userid.in_([session['user_id']]))
result = query.all()
file_urls = []
for userimg in result:
photo_info = {'url': userimg.imgurl, 'width': userimg.imgw, 'height': userimg.imgh, 'id': userimg.id}
file_urls.append(photo_info)
session['file_urls'] = file_urls
sess.close()
return render_template('view_images.html', file_urls=file_urls)
@app.route('/signup', methods=['GET', 'POST'])
def signup(status=None):
if request.method == 'GET':
if not session.get('user_id'):
return render_template('signup.html', status=status)
else:
return redirect(url_for('home'))
elif request.method == 'POST':
try:
email = request.form['email']
username = request.form['username']
password = request.form['password']
confirmedpassword = request.form['confirmpassword']
if password != confirmedpassword:
return render_template('signup.html', status=True)
print(email + '\t' + username + '\t' + password + '\t' + confirmedpassword)
Session = scoped_session(sessionmaker(bind=engine))
sess = Session()
user = User(username, password, email)
sess.add(user)
sess.commit()
sess.close()
return redirect(url_for('home'))
except Exception as ex:
print("error in insert operation", ex)
return "Register error"
@app.route('/view_similar_images', methods=['GET', 'POST'])
@login_required
def view_similar_images():
Session = scoped_session(sessionmaker(bind=engine))
sess = Session()
query = sess.query(UserImage).filter(UserImage.userid.in_([session['user_id']]))
result = query.all()
groups = {}
for userimg in result:
if userimg.groupid is not None:
photo_info = {'url': userimg.imgurl, 'width': userimg.imgw, 'height': userimg.imgh, 'id': userimg.id}
if userimg.groupid not in groups:
groups[userimg.groupid] = []
groups[userimg.groupid].append(photo_info)
sess.close()
print(groups)
return render_template('view_similar_images.html', groups=groups)
@app.route('/delete_images', methods=['GET', 'POST'])
@login_required
def delete_images():
print("enter delete")
Session = scoped_session(sessionmaker(bind=engine))
sess = Session()
if request.method == "POST":
data = request.get_json()
list_ids = data['data']
for did in list_ids:
print("delete id: " + did)
sess.query(UserImage).filter(UserImage.id == did).delete()
sess.commit()
sess.close()
if len(list_ids):
session.pop('file_urls', None)
return redirect(url_for("view_similar_images"))
@app.route('/login', methods=['POST'])
def do_admin_login():
POST_USERNAME = str(request.form['username'])
POST_PASSWORD = str(request.form['password'])
Session = scoped_session(sessionmaker(bind=engine))
sess = Session()
query = sess.query(User).filter(User.username.in_([POST_USERNAME]), User.password.in_([POST_PASSWORD]))
print(POST_USERNAME + '\t' + POST_PASSWORD)
result = query.first()
sess.close()
if result:
status = None
session['user_name'] = POST_USERNAME
session['user_id'] = result.userid
else:
status = True
flash('wrong password!')
return home(status)
@app.route("/logout")
@login_required
def logout():
session['user_id'] = None
session.pop('file_urls', None)
return home()
@app.route('/upload_image', methods=['GET', 'POST'])
@login_required
def upload_image():
global image_queue
# set session for image results
if "file_urls" not in session:
session['file_urls'] = []
# list to hold our uploaded image urls
file_urls = session['file_urls']
# handle image upload from Dropzone
if request.method == 'POST':
Session = scoped_session(sessionmaker(bind=engine))
sess = Session()
file_obj = request.files
for f in file_obj:
file = request.files.get(f)
# save the file with to our photos folder
filename = photos.save(
file,
name=file.filename.lower()
)
# append image urls
photo_url = photos.url(filename)
response = requests.get(photo_url)
img = Image.open(BytesIO(response.content))
(w, h) = img.size
photo_info = {'url': photo_url, 'width': w, 'height': h}
file_urls.insert(0, photo_info)
id = int(datetime.datetime.now().strftime("%Y%m%d%H%M%f"))
user_img = UserImage(id, session['user_id'], photo_url, img.size, None, uploaddate=datetime.date.today())
sess.add(user_img)
sess.commit()
image_queue.put((id, img))
session['file_urls'] = file_urls
return "uploading..."
# return dropzone template on GET request
return render_template('upload_image.html')
@app.route('/view_images')
@login_required
def view_images():
# redirect to home if no images to display
if "file_urls" not in session:
return redirect(url_for('home'))
# set the file_urls and remove the session variable
file_urls = session['file_urls']
print(file_urls)
return render_template('view_images.html', file_urls=file_urls)
@app.route('/view_albums')
@login_required
def view_albums():
Session = scoped_session(sessionmaker(bind=engine))
sess = Session()
query = sess.query(UserImage, ClassImage).filter(UserImage.classid == ClassImage.id).distinct(ClassImage.id)
result = query.all()
list_class = []
classid = []
for userimg in result:
if userimg[1].id not in classid:
photo_info = {'url': userimg[0].imgurl, 'width': userimg[0].imgw, 'height': userimg[0].imgh, 'image_id': userimg[0].id, 'classid': userimg[1].id, 'classname': userimg[1].name}
classid.append(userimg[1].id)
list_class.append(photo_info)
return render_template('image_album.html', list_class = list_class)
@app.route('/view_images_of_album/<int:id>')
@login_required
def view_images_of_album(id):
Session = scoped_session(sessionmaker(bind=engine))
sess = Session()
query = sess.query(UserImage).filter(UserImage.userid.in_([session['user_id']])).filter(UserImage.classid == id)
result = query.all()
file_urls = []
for userimg in result:
photo_info = {'url': userimg.imgurl, 'width': userimg.imgw, 'height': userimg.imgh, 'id': userimg.id}
file_urls.append(photo_info)
sess.close()
return render_template('view_images.html', file_urls=file_urls)
@app.route('/show_duplicated_images')
@login_required
def show_duplicated_images():
image_processer.image_clustering()
return redirect(url_for('view_similar_images'))
def start_processes():
return image_processing.start_process(image_queue)
if __name__ == "__main__":
image_processer = start_processes()
app.run(host='0.0.0.0', port=4000, debug=True)