Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
415 lines (344 loc) · 13.8 KB
/
Copy pathapp.py
File metadata and controls
415 lines (344 loc) · 13.8 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
from flask import Flask, render_template, request, jsonify, redirect, url_for, session, flash
import os
import numpy as np
import time
import json
import uuid
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from PIL import Image
from tensorflow.keras.applications import ResNet50, MobileNetV2, InceptionV3, VGG16
from tensorflow.keras.applications.resnet50 import preprocess_input as preprocess_input_resnet
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input as preprocess_input_mobilenet
from tensorflow.keras.applications.inception_v3 import preprocess_input as preprocess_input_inception
from tensorflow.keras.applications.vgg16 import preprocess_input as preprocess_input_vgg
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout, GlobalAveragePooling2D
import matplotlib.pyplot as plt
import cv2
import functools
app = Flask(__name__)
app.secret_key = os.urandom(24)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['HISTORY_FOLDER'] = 'history'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB limit
app.config['USERS_FILE'] = 'users.json'
app.config['MODEL_FOLDER'] = 'model'
# 필요한 디렉토리 생성
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs(app.config['HISTORY_FOLDER'], exist_ok=True)
os.makedirs('static/plots', exist_ok=True)
os.makedirs(app.config['MODEL_FOLDER'], exist_ok=True)
# 사용자 데이터 로드 또는 초기화
def load_users():
if os.path.exists(app.config['USERS_FILE']):
with open(app.config['USERS_FILE'], 'r') as f:
return json.load(f)
return {}
def save_users(users):
with open(app.config['USERS_FILE'], 'w') as f:
json.dump(users, f)
# 커스텀 모델 생성 함수
def create_custom_model():
# 간단한 CNN 모델 생성
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),
MaxPooling2D(2, 2),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D(2, 2),
Conv2D(128, (3, 3), activation='relu'),
MaxPooling2D(2, 2),
Flatten(),
Dense(512, activation='relu'),
Dropout(0.5),
Dense(1000, activation='softmax') # ImageNet 클래스와 호환되도록 1000개 클래스
])
# 모델 컴파일
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
# 모델 저장은 생략합니다 - 경로 문제 해결을 위해
return model
# 커스텀 모델 전처리 함수
def preprocess_input_custom(x):
# 간단한 전처리: 픽셀값을 0~1 사이로 정규화
return x / 255.0
# 모델 초기화 함수
def load_models():
models = {
'resnet50': {
'model': ResNet50(weights='imagenet'),
'preprocess': preprocess_input_resnet,
'name': 'ResNet50',
'input_size': (224, 224)
},
'mobilenet': {
'model': MobileNetV2(weights='imagenet'),
'preprocess': preprocess_input_mobilenet,
'name': 'MobileNet V2',
'input_size': (224, 224)
},
'inception': {
'model': InceptionV3(weights='imagenet'),
'preprocess': preprocess_input_inception,
'name': 'Inception V3',
'input_size': (299, 299)
},
'vgg16': {
'model': VGG16(weights='imagenet'),
'preprocess': preprocess_input_vgg,
'name': 'VGG16',
'input_size': (224, 224)
}
}
# 커스텀 모델을 직접 생성하여 사용 (파일 로드 회피)
custom_model = create_custom_model()
# 커스텀 모델 추가
models['custom_cnn'] = {
'model': custom_model,
'preprocess': preprocess_input_custom,
'name': '커스텀 CNN',
'input_size': (224, 224)
}
return models
# 모델 로드
models = load_models()
users = load_users()
# 로그인 필요 데코레이터
def login_required(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
if 'username' not in session:
flash('로그인이 필요합니다.')
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
# 이미지 예측 함수
def predict_image(img_path, model_name='resnet50', top_n=5):
model_info = models[model_name]
model = model_info['model']
preprocess_input = model_info['preprocess']
input_size = model_info['input_size']
img = image.load_img(img_path, target_size=input_size)
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array = preprocess_input(img_array)
start_time = time.time()
predictions = model.predict(img_array)
inference_time = time.time() - start_time
from tensorflow.keras.applications.imagenet_utils import decode_predictions
# 커스텀 모델인 경우 자체적으로 결과 처리
if model_name == 'custom_cnn':
# 상위 예측 클래스 인덱스 추출
top_indices = np.argsort(predictions[0])[-top_n:][::-1]
# ImageNet 클래스 레이블 목록 (간략화)
imagenet_classes = ["배경", "티셔츠", "청바지", "스웨터", "드레스", "코트", "샌들", "셔츠",
"스니커즈", "가방", "발목 부츠"] + ["기타클래스_" + str(i) for i in range(11, 1000)]
# 상위 예측 결과 포맷팅
result = [
{"label": imagenet_classes[idx], "confidence": float(predictions[0][idx] * 100)}
for idx in top_indices
]
else:
# 사전 훈련된 모델은 decode_predictions 사용
decoded = decode_predictions(predictions, top=top_n)[0]
result = [
{"label": label, "confidence": float(confidence) * 100}
for _, label, confidence in decoded
]
return {
'predictions': result,
'inference_time': inference_time
}
# 시각화 함수
def generate_visualization(img_path, result, username):
# matplotlib 한글 폰트 설정
plt.rcParams['font.family'] = 'Malgun Gothic' # 윈도우의 기본 한글 폰트
plt.rcParams['axes.unicode_minus'] = False # 마이너스 기호 깨짐 방지
# 원본 이미지 로드
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 결과 시각화
plt.figure(figsize=(12, 6))
# 이미지 표시
plt.subplot(1, 2, 1)
plt.imshow(img)
plt.title('입력 이미지')
plt.axis('off')
# 결과 바 차트
plt.subplot(1, 2, 2)
labels = [p['label'] for p in result['predictions']]
confidences = [p['confidence'] for p in result['predictions']]
# 신뢰도 기준 정렬
sorted_indices = np.argsort(confidences)[::-1]
labels = [labels[i] for i in sorted_indices]
confidences = [confidences[i] for i in sorted_indices]
plt.barh(labels, confidences, color='skyblue')
plt.xlabel('신뢰도 (%)')
plt.title('예측 결과')
plt.tight_layout()
try:
# 파일 저장
plot_filename = f'static/plots/{username}_{int(time.time())}.png'
plt.savefig(plot_filename)
plt.close()
return '/' + plot_filename
except Exception as e:
print(f"시각화 저장 중 오류 발생: {str(e)}")
# 폰트 문제가 있을 경우 기본 폰트로 재시도
plt.rcParams['font.family'] = 'DejaVu Sans'
plot_filename = f'static/plots/{username}_{int(time.time())}_fallback.png'
plt.savefig(plot_filename)
plt.close()
return '/' + plot_filename
# 이미지 분석 기록 저장
def save_history(username, img_path, model_name, result, visualization_path):
user_history_dir = os.path.join(app.config['HISTORY_FOLDER'], username)
os.makedirs(user_history_dir, exist_ok=True)
history_id = str(uuid.uuid4())
history_file = os.path.join(user_history_dir, f'{history_id}.json')
# 이미지 파일명 저장
filename = os.path.basename(img_path)
# 기록 데이터 생성
history_data = {
'id': history_id,
'timestamp': datetime.now().isoformat(),
'filename': filename,
'model': model_name,
'result': result,
'visualization': visualization_path
}
# 파일에 저장
with open(history_file, 'w') as f:
json.dump(history_data, f)
return history_id
# 사용자 기록 로드
def load_user_history(username):
user_history_dir = os.path.join(app.config['HISTORY_FOLDER'], username)
if not os.path.exists(user_history_dir):
return []
history_files = [os.path.join(user_history_dir, f) for f in os.listdir(user_history_dir) if f.endswith('.json')]
history = []
for file in history_files:
with open(file, 'r') as f:
history.append(json.load(f))
# 시간순 정렬
history.sort(key=lambda x: x['timestamp'], reverse=True)
return history
# 라우트: 메인 페이지
@app.route('/')
def index():
if 'username' in session:
return render_template('index.html', logged_in=True, username=session['username'])
return render_template('index.html', logged_in=False)
# 라우트: 로그인
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username in users and check_password_hash(users[username]['password'], password):
session['username'] = username
flash('로그인되었습니다.')
return redirect(url_for('index'))
flash('사용자 이름 또는 비밀번호가 올바르지 않습니다.')
return render_template('login.html')
# 라우트: 회원가입
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username in users:
flash('이미 사용 중인 사용자 이름입니다.')
return render_template('register.html')
users[username] = {
'password': generate_password_hash(password),
'created_at': datetime.now().isoformat()
}
save_users(users)
flash('회원가입이 완료되었습니다. 로그인해주세요.')
return redirect(url_for('login'))
return render_template('register.html')
# 라우트: 로그아웃
@app.route('/logout')
def logout():
session.pop('username', None)
flash('로그아웃되었습니다.')
return redirect(url_for('index'))
# 라우트: 예측 처리
@app.route('/predict', methods=['POST'])
def predict():
model_name = request.form.get('model', 'resnet50')
if model_name not in models:
return jsonify({'error': '유효하지 않은 모델입니다.'})
if 'file' not in request.files:
return jsonify({'error': '파일이 없습니다.'})
file = request.files['file']
if file.filename == '':
return jsonify({'error': '선택된 파일이 없습니다.'})
# 파일 저장
filename = str(int(time.time())) + '_' + file.filename
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
try:
# 이미지 예측
result = predict_image(file_path, model_name=model_name)
# 로그인한 사용자라면 기록 저장
visualization_path = None
if 'username' in session:
username = session['username']
visualization_path = generate_visualization(file_path, result, username)
save_history(username, file_path, model_name, result, visualization_path)
result['visualization'] = visualization_path
return jsonify(result)
except Exception as e:
return jsonify({'error': str(e)})
# 라우트: 히스토리 페이지
@app.route('/history')
@login_required
def history():
username = session['username']
user_history = load_user_history(username)
return render_template('history.html', history=user_history)
# 라우트: 분석 상세 페이지
@app.route('/analysis/<history_id>')
@login_required
def analysis(history_id):
username = session['username']
user_history_dir = os.path.join(app.config['HISTORY_FOLDER'], username)
history_file = os.path.join(user_history_dir, f'{history_id}.json')
if not os.path.exists(history_file):
flash('존재하지 않는 분석 기록입니다.')
return redirect(url_for('history'))
with open(history_file, 'r') as f:
analysis_data = json.load(f)
return render_template('analysis.html', analysis=analysis_data)
# 라우트: 모델 비교 페이지
@app.route('/compare')
def compare():
return render_template('compare.html', models=models)
# 라우트: 여러 모델로 예측
@app.route('/predict_all', methods=['POST'])
def predict_all():
if 'file' not in request.files:
return jsonify({'error': '파일이 없습니다.'})
file = request.files['file']
if file.filename == '':
return jsonify({'error': '선택된 파일이 없습니다.'})
# 파일 저장
filename = str(int(time.time())) + '_' + file.filename
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
try:
results = {}
for model_name in models:
results[model_name] = predict_image(file_path, model_name=model_name)
return jsonify(results)
except Exception as e:
return jsonify({'error': str(e)})
if __name__ == '__main__':
app.run(debug=True)