seawolf2357 commited on
Commit
d927a6e
ยท
verified ยท
1 Parent(s): bd5a51b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +792 -0
app.py ADDED
@@ -0,0 +1,792 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, redirect, url_for, jsonify, session
2
+ import requests
3
+ import os
4
+ import json
5
+ from datetime import timedelta
6
+
7
+ app = Flask(__name__)
8
+ app.secret_key = os.urandom(24) # ์„ธ์…˜ ์•”ํ˜ธํ™”๋ฅผ ์œ„ํ•œ ๋น„๋ฐ€ ํ‚ค
9
+ app.permanent_session_lifetime = timedelta(days=7) # ์„ธ์…˜ ์œ ์ง€ ๊ธฐ๊ฐ„ ์„ค์ •
10
+
11
+ # ํ—ˆ๊น…ํŽ˜์ด์Šค URL ๋ชฉ๋ก
12
+ HUGGINGFACE_URLS = [
13
+ "https://huggingface.co/spaces/ginipick/Tech_Hangman_Game",
14
+ "https://huggingface.co/spaces/openfree/deepseek_r1_API",
15
+ "https://huggingface.co/spaces/ginipick/open_Deep-Research",
16
+ "https://huggingface.co/spaces/aiqmaster/open-deep-research",
17
+ "https://huggingface.co/spaces/seawolf2357/DeepSeek-R1-32b-search",
18
+ "https://huggingface.co/spaces/ginigen/LLaDA",
19
+ "https://huggingface.co/spaces/VIDraft/PHI4-Multimodal",
20
+ "https://huggingface.co/spaces/ginigen/Ovis2-8B",
21
+ "https://huggingface.co/spaces/ginigen/Graph-Mind",
22
+ "https://huggingface.co/spaces/ginigen/Workflow-Canvas",
23
+ "https://huggingface.co/spaces/ginigen/Design",
24
+ "https://huggingface.co/spaces/ginigen/Diagram",
25
+ "https://huggingface.co/spaces/ginigen/Mockup",
26
+ "https://huggingface.co/spaces/ginigen/Infographic",
27
+ "https://huggingface.co/spaces/ginigen/Flowchart",
28
+ "https://huggingface.co/spaces/aiqcamp/FLUX-Vision",
29
+ "https://huggingface.co/spaces/ginigen/VoiceClone-TTS",
30
+ "https://huggingface.co/spaces/openfree/Perceptron-Network",
31
+ "https://huggingface.co/spaces/openfree/Article-Generator",
32
+ ]
33
+
34
+ # URL์—์„œ ๋ชจ๋ธ/์ŠคํŽ˜์ด์Šค ์ •๋ณด ์ถ”์ถœ
35
+ def extract_model_info(url):
36
+ parts = url.split('/')
37
+ if len(parts) < 6:
38
+ return None
39
+
40
+ if parts[3] == 'spaces' or parts[3] == 'models':
41
+ return {
42
+ 'type': parts[3],
43
+ 'owner': parts[4],
44
+ 'repo': parts[5],
45
+ 'full_id': f"{parts[4]}/{parts[5]}"
46
+ }
47
+ elif len(parts) >= 5:
48
+ # ๋‹ค๋ฅธ ํ˜•์‹์˜ URL
49
+ return {
50
+ 'type': 'models', # ๊ธฐ๋ณธ๊ฐ’
51
+ 'owner': parts[3],
52
+ 'repo': parts[4],
53
+ 'full_id': f"{parts[3]}/{parts[4]}"
54
+ }
55
+
56
+ return None
57
+
58
+ # URL์˜ ๋งˆ์ง€๋ง‰ ๋ถ€๋ถ„์„ ์ œ๋ชฉ์œผ๋กœ ์ถ”์ถœ
59
+ def extract_title(url):
60
+ parts = url.split("/")
61
+ title = parts[-1] if parts else ""
62
+ return title.replace("_", " ").replace("-", " ")
63
+
64
+ # ํ—ˆ๊น…ํŽ˜์ด์Šค ์ธ์ฆ ํ™•์ธ
65
+ def validate_token(token):
66
+ headers = {"Authorization": f"Bearer {token}"}
67
+ try:
68
+ response = requests.get("https://huggingface.co/api/whoami", headers=headers)
69
+ return response.ok, response.json() if response.ok else None
70
+ except Exception as e:
71
+ print(f"ํ† ํฐ ๊ฒ€์ฆ ์˜ค๋ฅ˜: {e}")
72
+ return False, None
73
+
74
+ # ์ข‹์•„์š” ๋ชฉ๋ก ๊ฐ€์ ธ์˜ค๊ธฐ
75
+ def get_liked_repos(token):
76
+ headers = {"Authorization": f"Bearer {token}"}
77
+ endpoints = [
78
+ "/api/me/likes",
79
+ "/api/me/liked-repos",
80
+ "/api/me/favorites"
81
+ ]
82
+
83
+ liked_models = {}
84
+
85
+ for endpoint in endpoints:
86
+ try:
87
+ response = requests.get(f"https://huggingface.co{endpoint}", headers=headers)
88
+ if response.ok:
89
+ data = response.json()
90
+ if isinstance(data, list):
91
+ for model in data:
92
+ if isinstance(model, dict):
93
+ if 'owner' in model and 'name' in model:
94
+ liked_models[f"{model['owner']}/{model['name']}"] = True
95
+ elif 'id' in model:
96
+ liked_models[model['id']] = True
97
+ elif isinstance(data, dict):
98
+ for key in data:
99
+ liked_models[key] = True
100
+
101
+ print(f"์ข‹์•„์š” ๋ชฉ๋ก ๊ฐ€์ ธ์˜ค๊ธฐ ์„ฑ๊ณต (์—”๋“œํฌ์ธํŠธ: {endpoint})")
102
+ return liked_models
103
+ except Exception as e:
104
+ print(f"์ข‹์•„์š” ๋ชฉ๋ก ๊ฐ€์ ธ์˜ค๊ธฐ ์˜ค๋ฅ˜ (์—”๋“œํฌ์ธํŠธ: {endpoint}): {e}")
105
+
106
+ return liked_models
107
+
108
+ # ์ข‹์•„์š” ํ† ๊ธ€ API ํ˜ธ์ถœ
109
+ def toggle_like(token, type_name, owner, repo, is_liked):
110
+ headers = {"Authorization": f"Bearer {token}"}
111
+ normalized_type = "spaces" if type_name == "spaces" else "models"
112
+ method = "DELETE" if is_liked else "POST"
113
+ url = f"https://huggingface.co/api/{normalized_type}/{owner}/{repo}/like"
114
+
115
+ try:
116
+ if method == "DELETE":
117
+ response = requests.delete(url, headers=headers)
118
+ else:
119
+ response = requests.post(url, headers=headers)
120
+
121
+ return response.ok, response.status_code
122
+ except Exception as e:
123
+ print(f"์ข‹์•„์š” ํ† ๊ธ€ ์˜ค๋ฅ˜: {e}")
124
+ return False, 500
125
+
126
+ # ํ™ˆํŽ˜์ด์ง€ ๋ผ์šฐํŠธ
127
+ @app.route('/')
128
+ def home():
129
+ return render_template('index.html')
130
+
131
+ # ๋กœ๊ทธ์ธ ์ฒ˜๋ฆฌ API
132
+ @app.route('/api/login', methods=['POST'])
133
+ def login():
134
+ token = request.form.get('token', '')
135
+
136
+ if not token:
137
+ return jsonify({'success': False, 'message': 'ํ† ๏ฟฝ๏ฟฝ๏ฟฝ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.'})
138
+
139
+ is_valid, user_info = validate_token(token)
140
+
141
+ if not is_valid or not user_info:
142
+ return jsonify({'success': False, 'message': '์œ ํšจํ•˜์ง€ ์•Š์€ ํ† ํฐ์ž…๋‹ˆ๋‹ค.'})
143
+
144
+ # ์‚ฌ์šฉ์ž ์ด๋ฆ„ ์ฐพ๊ธฐ
145
+ username = None
146
+ if 'name' in user_info:
147
+ username = user_info['name']
148
+ elif 'user' in user_info and 'username' in user_info['user']:
149
+ username = user_info['user']['username']
150
+ elif 'username' in user_info:
151
+ username = user_info['username']
152
+ else:
153
+ username = '์ธ์ฆ๋œ ์‚ฌ์šฉ์ž'
154
+
155
+ # ์ข‹์•„์š” ๋ชฉ๋ก ๊ฐ€์ ธ์˜ค๊ธฐ
156
+ liked_models = get_liked_repos(token)
157
+
158
+ # ์„ธ์…˜์— ์ €์žฅ
159
+ session['token'] = token
160
+ session['username'] = username
161
+ session['liked_models'] = liked_models
162
+
163
+ return jsonify({
164
+ 'success': True,
165
+ 'username': username,
166
+ 'liked_models': liked_models
167
+ })
168
+
169
+ # ๋กœ๊ทธ์•„์›ƒ ์ฒ˜๋ฆฌ API
170
+ @app.route('/api/logout', methods=['POST'])
171
+ def logout():
172
+ session.pop('token', None)
173
+ session.pop('username', None)
174
+ session.pop('liked_models', None)
175
+ return jsonify({'success': True})
176
+
177
+ # URL ๋ชฉ๋ก ๊ฐ€์ ธ์˜ค๊ธฐ API
178
+ @app.route('/api/urls', methods=['GET'])
179
+ def get_urls():
180
+ search_query = request.args.get('search', '').lower()
181
+ show_only_liked = request.args.get('liked', 'false').lower() == 'true'
182
+
183
+ liked_models = session.get('liked_models', {})
184
+
185
+ results = []
186
+ for url in HUGGINGFACE_URLS:
187
+ title = extract_title(url)
188
+ model_info = extract_model_info(url)
189
+
190
+ if not model_info:
191
+ continue
192
+
193
+ is_liked = model_info['full_id'] in liked_models
194
+
195
+ # ํ•„ํ„ฐ๋ง ์ ์šฉ
196
+ if show_only_liked and not is_liked:
197
+ continue
198
+
199
+ if search_query and search_query not in url.lower() and search_query not in title.lower():
200
+ continue
201
+
202
+ results.append({
203
+ 'url': url,
204
+ 'title': title,
205
+ 'model_info': model_info,
206
+ 'is_liked': is_liked
207
+ })
208
+
209
+ return jsonify(results)
210
+
211
+ # ์ข‹์•„์š” ํ† ๊ธ€ API
212
+ @app.route('/api/toggle-like', methods=['POST'])
213
+ def api_toggle_like():
214
+ if 'token' not in session:
215
+ return jsonify({'success': False, 'message': '๋กœ๊ทธ์ธ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.'})
216
+
217
+ data = request.json
218
+ url = data.get('url')
219
+ current_liked = data.get('currentLiked', False)
220
+
221
+ if not url:
222
+ return jsonify({'success': False, 'message': 'URL์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.'})
223
+
224
+ model_info = extract_model_info(url)
225
+ if not model_info:
226
+ return jsonify({'success': False, 'message': '์œ ํšจํ•˜์ง€ ์•Š์€ URL์ž…๋‹ˆ๋‹ค.'})
227
+
228
+ success, status_code = toggle_like(
229
+ session['token'],
230
+ model_info['type'],
231
+ model_info['owner'],
232
+ model_info['repo'],
233
+ current_liked
234
+ )
235
+
236
+ liked_models = session.get('liked_models', {})
237
+
238
+ if success:
239
+ # ์„ธ์…˜์˜ ์ข‹์•„์š” ์ƒํƒœ ์—…๋ฐ์ดํŠธ
240
+ if current_liked:
241
+ if model_info['full_id'] in liked_models:
242
+ del liked_models[model_info['full_id']]
243
+ else:
244
+ liked_models[model_info['full_id']] = True
245
+
246
+ session['liked_models'] = liked_models
247
+
248
+ return jsonify({
249
+ 'success': True,
250
+ 'new_state': not current_liked,
251
+ 'message': f"{'์ข‹์•„์š” ์ทจ์†Œ' if current_liked else '์ข‹์•„์š”'} ์„ฑ๊ณต"
252
+ })
253
+ else:
254
+ return jsonify({
255
+ 'success': False,
256
+ 'message': f"API ์˜ค๋ฅ˜ (์ƒํƒœ ์ฝ”๋“œ: {status_code})"
257
+ })
258
+
259
+ # ์„ธ์…˜ ์ƒํƒœ ํ™•์ธ API
260
+ @app.route('/api/session-status', methods=['GET'])
261
+ def session_status():
262
+ return jsonify({
263
+ 'logged_in': 'token' in session,
264
+ 'username': session.get('username'),
265
+ 'liked_count': len(session.get('liked_models', {}))
266
+ })
267
+
268
+ if __name__ == '__main__':
269
+ # templates ํด๋” ์ƒ์„ฑ
270
+ os.makedirs('templates', exist_ok=True)
271
+
272
+ # index.html ํŒŒ์ผ ์ƒ์„ฑ
273
+ with open('templates/index.html', 'w', encoding='utf-8') as f:
274
+ f.write('''
275
+ <!DOCTYPE html>
276
+ <html lang="ko">
277
+ <head>
278
+ <meta charset="UTF-8">
279
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
280
+ <title>Hugging Face URL ์นด๋“œ ๋ฆฌ์ŠคํŠธ</title>
281
+ <style>
282
+ body {
283
+ font-family: Arial, sans-serif;
284
+ line-height: 1.6;
285
+ margin: 0;
286
+ padding: 0;
287
+ color: #333;
288
+ }
289
+
290
+ .container {
291
+ max-width: 1200px;
292
+ margin: 0 auto;
293
+ padding: 1rem;
294
+ }
295
+
296
+ .header {
297
+ background-color: #f0f0f0;
298
+ padding: 1rem;
299
+ border-radius: 5px;
300
+ margin-bottom: 1rem;
301
+ }
302
+
303
+ .user-controls {
304
+ display: flex;
305
+ justify-content: space-between;
306
+ align-items: center;
307
+ flex-wrap: wrap;
308
+ }
309
+
310
+ .filter-controls {
311
+ background-color: #f8f9fa;
312
+ padding: 1rem;
313
+ border-radius: 5px;
314
+ margin-bottom: 1rem;
315
+ }
316
+
317
+ input[type="password"],
318
+ input[type="text"] {
319
+ padding: 0.5rem;
320
+ border: 1px solid #ccc;
321
+ border-radius: 4px;
322
+ margin-right: 5px;
323
+ }
324
+
325
+ button {
326
+ padding: 0.5rem 1rem;
327
+ background-color: #4CAF50;
328
+ color: white;
329
+ border: none;
330
+ border-radius: 4px;
331
+ cursor: pointer;
332
+ }
333
+
334
+ button:hover {
335
+ background-color: #45a049;
336
+ }
337
+
338
+ button.logout {
339
+ background-color: #f44336;
340
+ }
341
+
342
+ button.logout:hover {
343
+ background-color: #d32f2f;
344
+ }
345
+
346
+ .token-help {
347
+ margin-top: 0.5rem;
348
+ font-size: 0.8rem;
349
+ color: #666;
350
+ }
351
+
352
+ .token-help a {
353
+ color: #4CAF50;
354
+ text-decoration: none;
355
+ }
356
+
357
+ .token-help a:hover {
358
+ text-decoration: underline;
359
+ }
360
+
361
+ .cards-container {
362
+ display: flex;
363
+ flex-wrap: wrap;
364
+ gap: 1rem;
365
+ }
366
+
367
+ .card {
368
+ border: 1px solid #ccc;
369
+ border-radius: 5px;
370
+ padding: 1rem;
371
+ width: 300px;
372
+ box-shadow: 2px 2px 8px rgba(0,0,0,0.1);
373
+ position: relative;
374
+ background-color: #f9f9f9;
375
+ }
376
+
377
+ .card a {
378
+ text-decoration: none;
379
+ color: #333;
380
+ word-break: break-all;
381
+ }
382
+
383
+ .like-button {
384
+ position: absolute;
385
+ top: 1rem;
386
+ right: 1rem;
387
+ border: none;
388
+ background: transparent;
389
+ font-size: 1.5rem;
390
+ cursor: pointer;
391
+ transition: color 0.2s;
392
+ }
393
+
394
+ .like-button.liked {
395
+ color: red;
396
+ }
397
+
398
+ .like-button.not-liked {
399
+ color: white;
400
+ -webkit-text-stroke: 1px #333;
401
+ }
402
+
403
+ .status-message {
404
+ padding: 1rem;
405
+ border-radius: 4px;
406
+ margin-bottom: 1rem;
407
+ display: none;
408
+ }
409
+
410
+ .success {
411
+ background-color: #dff0d8;
412
+ color: #3c763d;
413
+ }
414
+
415
+ .error {
416
+ background-color: #f2dede;
417
+ color: #a94442;
418
+ }
419
+
420
+ .loading {
421
+ position: fixed;
422
+ top: 0;
423
+ left: 0;
424
+ right: 0;
425
+ bottom: 0;
426
+ background-color: rgba(255, 255, 255, 0.7);
427
+ display: none;
428
+ justify-content: center;
429
+ align-items: center;
430
+ z-index: 1000;
431
+ font-size: 1.5rem;
432
+ }
433
+
434
+ .login-section {
435
+ margin-top: 1rem;
436
+ }
437
+
438
+ .logged-in-section {
439
+ display: none;
440
+ margin-top: 1rem;
441
+ }
442
+
443
+ @media (max-width: 768px) {
444
+ .user-controls {
445
+ flex-direction: column;
446
+ align-items: flex-start;
447
+ }
448
+
449
+ .user-controls > div {
450
+ margin-bottom: 1rem;
451
+ }
452
+
453
+ .card {
454
+ width: 100%;
455
+ }
456
+ }
457
+ </style>
458
+ </head>
459
+ <body>
460
+ <div class="container">
461
+ <div class="header">
462
+ <div class="user-controls">
463
+ <div>
464
+ <span>ํ—ˆ๊น…ํŽ˜์ด์Šค ๊ณ„์ •: </span>
465
+ <span id="currentUser">๋กœ๊ทธ์ธ๋˜์ง€ ์•Š์Œ</span>
466
+ </div>
467
+
468
+ <div id="loginSection" class="login-section">
469
+ <input type="password" id="tokenInput" placeholder="ํ—ˆ๊น…ํŽ˜์ด์Šค API ํ† ํฐ ์ž…๋ ฅ" />
470
+ <button id="loginButton">์ธ์ฆํ•˜๊ธฐ</button>
471
+ <div class="token-help">
472
+ API ํ† ํฐ์€ <a href="https://huggingface.co/settings/tokens" target="_blank">ํ—ˆ๊น…ํŽ˜์ด์Šค ํ† ํฐ ํŽ˜์ด์ง€</a>์—์„œ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
473
+ </div>
474
+ </div>
475
+
476
+ <div id="loggedInSection" class="logged-in-section">
477
+ <button id="logoutButton" class="logout">๋กœ๊ทธ์•„์›ƒ</button>
478
+ </div>
479
+ </div>
480
+ </div>
481
+
482
+ <div class="filter-controls">
483
+ <label>
484
+ <input type="checkbox" id="showOnlyLiked" />
485
+ ๋‚ด๊ฐ€ ์ข‹์•„์š”ํ•œ URL๋งŒ ๋ณด๊ธฐ
486
+ </label>
487
+ <label style="margin-left: 1rem;">
488
+ <input type="text" id="searchInput" placeholder="URL ๋˜๋Š” ์ œ๋ชฉ์œผ๋กœ ๊ฒ€์ƒ‰" style="width: 250px;" />
489
+ </label>
490
+ </div>
491
+
492
+ <div id="statusMessage" class="status-message"></div>
493
+
494
+ <div id="loadingIndicator" class="loading">์ฒ˜๋ฆฌ ์ค‘...</div>
495
+
496
+ <div id="cardsContainer" class="cards-container"></div>
497
+ </div>
498
+
499
+ <script>
500
+ // DOM ์š”์†Œ ์ฐธ์กฐ
501
+ const elements = {
502
+ tokenInput: document.getElementById('tokenInput'),
503
+ loginButton: document.getElementById('loginButton'),
504
+ logoutButton: document.getElementById('logoutButton'),
505
+ currentUser: document.getElementById('currentUser'),
506
+ cardsContainer: document.getElementById('cardsContainer'),
507
+ loadingIndicator: document.getElementById('loadingIndicator'),
508
+ statusMessage: document.getElementById('statusMessage'),
509
+ showOnlyLiked: document.getElementById('showOnlyLiked'),
510
+ searchInput: document.getElementById('searchInput'),
511
+ loginSection: document.getElementById('loginSection'),
512
+ loggedInSection: document.getElementById('loggedInSection')
513
+ };
514
+
515
+ // ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ƒํƒœ
516
+ const state = {
517
+ username: null,
518
+ likedModels: {},
519
+ isLoading: false
520
+ };
521
+
522
+ // ๋กœ๋”ฉ ์ƒํƒœ ํ‘œ์‹œ ํ•จ์ˆ˜
523
+ function setLoading(isLoading) {
524
+ state.isLoading = isLoading;
525
+ elements.loadingIndicator.style.display = isLoading ? 'flex' : 'none';
526
+ }
527
+
528
+ // ์ƒํƒœ ๋ฉ”์‹œ์ง€ ํ‘œ์‹œ ํ•จ์ˆ˜
529
+ function showMessage(message, isError = false) {
530
+ elements.statusMessage.textContent = message;
531
+ elements.statusMessage.className = `status-message ${isError ? 'error' : 'success'}`;
532
+ elements.statusMessage.style.display = 'block';
533
+
534
+ // 3์ดˆ ํ›„ ๋ฉ”์‹œ์ง€ ์‚ฌ๋ผ์ง
535
+ setTimeout(() => {
536
+ elements.statusMessage.style.display = 'none';
537
+ }, 3000);
538
+ }
539
+
540
+ // API ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ ํ•จ์ˆ˜
541
+ async function handleApiResponse(response) {
542
+ if (!response.ok) {
543
+ const errorText = await response.text();
544
+ throw new Error(`API ์˜ค๋ฅ˜ (${response.status}): ${errorText}`);
545
+ }
546
+ return response.json();
547
+ }
548
+
549
+ // ์„ธ์…˜ ์ƒํƒœ ํ™•์ธ
550
+ async function checkSessionStatus() {
551
+ try {
552
+ const response = await fetch('/api/session-status');
553
+ const data = await handleApiResponse(response);
554
+
555
+ if (data.logged_in) {
556
+ state.username = data.username;
557
+ elements.currentUser.textContent = data.username;
558
+ elements.loginSection.style.display = 'none';
559
+ elements.loggedInSection.style.display = 'block';
560
+
561
+ // URL ๋ชฉ๋ก ๋กœ๋“œ
562
+ loadUrls();
563
+ }
564
+ } catch (error) {
565
+ console.error('์„ธ์…˜ ์ƒํƒœ ํ™•์ธ ์˜ค๋ฅ˜:', error);
566
+ }
567
+ }
568
+
569
+ // ๋กœ๊ทธ์ธ ์ฒ˜๋ฆฌ
570
+ async function login(token) {
571
+ if (!token.trim()) {
572
+ showMessage('ํ† ํฐ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.', true);
573
+ return;
574
+ }
575
+
576
+ setLoading(true);
577
+
578
+ try {
579
+ const formData = new FormData();
580
+ formData.append('token', token);
581
+
582
+ const response = await fetch('/api/login', {
583
+ method: 'POST',
584
+ body: formData
585
+ });
586
+
587
+ const data = await handleApiResponse(response);
588
+
589
+ if (data.success) {
590
+ state.username = data.username;
591
+ state.likedModels = data.liked_models || {};
592
+
593
+ elements.currentUser.textContent = state.username;
594
+ elements.loginSection.style.display = 'none';
595
+ elements.loggedInSection.style.display = 'block';
596
+
597
+ showMessage(`${state.username}๋‹˜์œผ๋กœ ๋กœ๊ทธ์ธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.`);
598
+
599
+ // URL ๋ชฉ๋ก ๋กœ๋“œ
600
+ loadUrls();
601
+ } else {
602
+ showMessage(data.message || '๋กœ๊ทธ์ธ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.', true);
603
+ }
604
+ } catch (error) {
605
+ console.error('๋กœ๊ทธ์ธ ์˜ค๋ฅ˜:', error);
606
+ showMessage(`๋กœ๊ทธ์ธ ์˜ค๋ฅ˜: ${error.message}`, true);
607
+ } finally {
608
+ setLoading(false);
609
+ }
610
+ }
611
+
612
+ // ๋กœ๊ทธ์•„์›ƒ ์ฒ˜๋ฆฌ
613
+ async function logout() {
614
+ setLoading(true);
615
+
616
+ try {
617
+ const response = await fetch('/api/logout', {
618
+ method: 'POST'
619
+ });
620
+
621
+ const data = await handleApiResponse(response);
622
+
623
+ if (data.success) {
624
+ state.username = null;
625
+ state.likedModels = {};
626
+
627
+ elements.currentUser.textContent = '๋กœ๊ทธ์ธ๋˜์ง€ ์•Š์Œ';
628
+ elements.tokenInput.value = '';
629
+ elements.loginSection.style.display = 'block';
630
+ elements.loggedInSection.style.display = 'none';
631
+
632
+ showMessage('๋กœ๊ทธ์•„์›ƒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.');
633
+
634
+ // ์นด๋“œ ์ดˆ๊ธฐํ™”
635
+ elements.cardsContainer.innerHTML = '';
636
+ }
637
+ } catch (error) {
638
+ console.error('๋กœ๊ทธ์•„์›ƒ ์˜ค๋ฅ˜:', error);
639
+ showMessage(`๋กœ๊ทธ์•„์›ƒ ์˜ค๋ฅ˜: ${error.message}`, true);
640
+ } finally {
641
+ setLoading(false);
642
+ }
643
+ }
644
+
645
+ // URL ๋ชฉ๋ก ๋กœ๋“œ
646
+ async function loadUrls() {
647
+ setLoading(true);
648
+
649
+ try {
650
+ const showOnlyLiked = elements.showOnlyLiked.checked;
651
+ const searchText = elements.searchInput.value;
652
+
653
+ const response = await fetch(`/api/urls?liked=${showOnlyLiked}&search=${encodeURIComponent(searchText)}`);
654
+ const urls = await handleApiResponse(response);
655
+
656
+ renderCards(urls);
657
+ } catch (error) {
658
+ console.error('URL ๋ชฉ๋ก ๋กœ๋“œ ์˜ค๋ฅ˜:', error);
659
+ showMessage(`URL ๋กœ๋“œ ์˜ค๋ฅ˜: ${error.message}`, true);
660
+ } finally {
661
+ setLoading(false);
662
+ }
663
+ }
664
+
665
+ // ์ข‹์•„์š” ํ† ๊ธ€
666
+ async function toggleLike(url, button, currentLiked) {
667
+ if (!state.username) {
668
+ showMessage('์ข‹์•„์š”๋ฅผ ํ•˜๋ ค๋ฉด ํ—ˆ๊น…ํŽ˜์ด์Šค API ํ† ํฐ์œผ๋กœ ์ธ์ฆ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.', true);
669
+ return;
670
+ }
671
+
672
+ setLoading(true);
673
+
674
+ try {
675
+ const response = await fetch('/api/toggle-like', {
676
+ method: 'POST',
677
+ headers: {
678
+ 'Content-Type': 'application/json'
679
+ },
680
+ body: JSON.stringify({
681
+ url: url,
682
+ currentLiked: currentLiked
683
+ })
684
+ });
685
+
686
+ const data = await handleApiResponse(response);
687
+
688
+ if (data.success) {
689
+ if (currentLiked) {
690
+ button.classList.remove('liked');
691
+ button.classList.add('not-liked');
692
+ } else {
693
+ button.classList.add('liked');
694
+ button.classList.remove('not-liked');
695
+ }
696
+
697
+ showMessage(data.message);
698
+
699
+ // ํ•„ํ„ฐ๋ง๋œ ๊ฒฝ์šฐ ๋ชฉ๋ก ๋‹ค์‹œ ๋กœ๋“œ
700
+ if (elements.showOnlyLiked.checked) {
701
+ loadUrls();
702
+ }
703
+ } else {
704
+ showMessage(data.message, true);
705
+ }
706
+ } catch (error) {
707
+ console.error('์ข‹์•„์š” ํ† ๊ธ€ ์˜ค๋ฅ˜:', error);
708
+ showMessage(`์ข‹์•„์š” ์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: ${error.message}`, true);
709
+ } finally {
710
+ setLoading(false);
711
+ }
712
+ }
713
+
714
+ // ์นด๋“œ ๋ Œ๋”๋ง
715
+ function renderCards(urls) {
716
+ elements.cardsContainer.innerHTML = '';
717
+
718
+ if (!urls || urls.length === 0) {
719
+ const noResultsMsg = document.createElement('p');
720
+ noResultsMsg.textContent = 'ํ‘œ์‹œํ•  URL์ด ์—†์Šต๋‹ˆ๋‹ค.';
721
+ noResultsMsg.style.padding = '1rem';
722
+ noResultsMsg.style.fontStyle = 'italic';
723
+ elements.cardsContainer.appendChild(noResultsMsg);
724
+ return;
725
+ }
726
+
727
+ urls.forEach(item => {
728
+ const { url, title, is_liked } = item;
729
+
730
+ // ์นด๋“œ ์ƒ์„ฑ
731
+ const card = document.createElement('div');
732
+ card.className = 'card';
733
+
734
+ // ์ œ๋ชฉ
735
+ const titleEl = document.createElement('h3');
736
+ titleEl.textContent = title;
737
+ card.appendChild(titleEl);
738
+
739
+ // URL ๋งํฌ
740
+ const linkEl = document.createElement('a');
741
+ linkEl.href = url;
742
+ linkEl.textContent = url;
743
+ linkEl.target = '_blank';
744
+ card.appendChild(linkEl);
745
+
746
+ // ์ข‹์•„์š” ๋ฒ„ํŠผ (โ™ฅ ์•„์ด์ฝ˜)
747
+ const likeBtn = document.createElement('button');
748
+ likeBtn.className = `like-button ${is_liked ? 'liked' : 'not-liked'}`;
749
+ likeBtn.textContent = 'โ™ฅ';
750
+
751
+ likeBtn.addEventListener('click', function(e) {
752
+ e.preventDefault();
753
+ toggleLike(url, likeBtn, is_liked);
754
+ });
755
+ card.appendChild(likeBtn);
756
+
757
+ // ์นด๋“œ ์ถ”๊ฐ€
758
+ elements.cardsContainer.appendChild(card);
759
+ });
760
+ }
761
+
762
+ // ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ ์„ค์ •
763
+ elements.loginButton.addEventListener('click', () => {
764
+ login(elements.tokenInput.value);
765
+ });
766
+
767
+ elements.logoutButton.addEventListener('click', logout);
768
+
769
+ // ์—”ํ„ฐ ํ‚ค๋กœ ๋กœ๊ทธ์ธ ๊ฐ€๋Šฅํ•˜๊ฒŒ
770
+ elements.tokenInput.addEventListener('keypress', (event) => {
771
+ if (event.key === 'Enter') {
772
+ login(elements.tokenInput.value);
773
+ }
774
+ });
775
+
776
+ // ํ•„ํ„ฐ๋ง ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ
777
+ elements.showOnlyLiked.addEventListener('change', loadUrls);
778
+ elements.searchInput.addEventListener('input', () => {
779
+ // ์ž…๋ ฅ ์ง€์—ฐ ์ฒ˜๋ฆฌ (ํƒ€์ดํ•‘ํ•  ๋•Œ๋งˆ๋‹ค API ํ˜ธ์ถœ ๋ฐฉ์ง€)
780
+ clearTimeout(state.searchTimeout);
781
+ state.searchTimeout = setTimeout(loadUrls, 300);
782
+ });
783
+
784
+ // ์ดˆ๊ธฐํ™”
785
+ checkSessionStatus();
786
+ </script>
787
+ </body>
788
+ </html>
789
+ ''')
790
+
791
+ # ์„œ๋ฒ„ ์‹คํ–‰
792
+ app.run(debug=True)