File size: 18,451 Bytes
cf37bae
4372751
d927a6e
 
 
 
84739ea
 
d927a6e
84739ea
fb08ce6
4372751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb08ce6
 
cf37bae
 
 
 
 
 
 
 
84739ea
fb08ce6
 
 
 
 
84739ea
4372751
 
 
84739ea
4372751
 
 
 
 
84739ea
4372751
84739ea
4372751
84739ea
 
 
4372751
84739ea
4372751
84739ea
4372751
84739ea
fb08ce6
 
 
 
84739ea
fb08ce6
 
 
 
 
4f82889
fb08ce6
4372751
 
 
4f82889
fb08ce6
84739ea
4372751
 
 
 
 
 
 
 
4f82889
fb08ce6
84739ea
4372751
fb08ce6
 
 
 
 
 
 
84739ea
fb08ce6
 
4372751
fb08ce6
 
 
84739ea
fb08ce6
 
84739ea
4372751
fb08ce6
cf37bae
fb08ce6
cf37bae
4372751
84739ea
 
9142e02
fb08ce6
 
cf37bae
98d3d46
fb08ce6
d927a6e
fb08ce6
 
84739ea
fb08ce6
 
 
84739ea
fb08ce6
 
6bd9991
fb08ce6
84739ea
fb08ce6
 
84739ea
fb08ce6
 
 
1045095
fb08ce6
 
 
4f82889
fb08ce6
 
84739ea
fb08ce6
 
 
 
84739ea
fb08ce6
 
 
84739ea
fb08ce6
 
 
 
 
84739ea
ac61d23
9142e02
ac61d23
84739ea
ac61d23
 
fb08ce6
 
 
 
 
 
 
 
84739ea
fb08ce6
9142e02
fb08ce6
84739ea
fb08ce6
 
 
 
84739ea
9142e02
fb08ce6
 
84739ea
 
fb08ce6
 
 
84739ea
fb08ce6
 
 
 
 
84739ea
9142e02
fb08ce6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84739ea
fb08ce6
 
 
 
 
 
 
 
 
 
 
 
73bb808
 
98d3d46
84739ea
fb08ce6
 
73bb808
84739ea
ac61d23
84739ea
c3b008e
73bb808
 
98d3d46
9142e02
 
73bb808
c3b008e
73bb808
84739ea
c3b008e
 
 
9142e02
 
84739ea
73bb808
84739ea
c3b008e
84739ea
c3b008e
 
 
 
 
 
 
 
 
fb08ce6
 
73bb808
 
 
84739ea
ac61d23
 
84739ea
73bb808
 
 
 
 
 
ac61d23
 
fb08ce6
 
9142e02
84739ea
fb08ce6
84739ea
fb08ce6
 
 
84739ea
 
fb08ce6
 
 
84739ea
 
fb08ce6
 
 
 
 
 
 
 
9142e02
fb08ce6
 
 
 
84739ea
fb08ce6
 
84739ea
 
 
9142e02
84739ea
 
9142e02
fb08ce6
 
9142e02
 
 
fb08ce6
 
9142e02
 
 
 
 
 
 
 
 
fb08ce6
 
 
 
 
 
 
 
 
 
73bb808
 
ac61d23
fb08ce6
 
 
 
 
 
 
 
c3b008e
 
fb08ce6
6bd9991
fb08ce6
c3b008e
 
fb08ce6
c3b008e
fb08ce6
 
6bd9991
fb08ce6
c3b008e
fb08ce6
 
 
 
 
c3b008e
73bb808
 
fb08ce6
 
73bb808
fb08ce6
 
84739ea
 
 
 
fb08ce6
84739ea
 
 
 
 
 
 
 
 
 
 
 
fb08ce6
 
84739ea
fb08ce6
 
84739ea
fb08ce6
 
84739ea
fb08ce6
 
 
 
 
84739ea
fb08ce6
 
 
 
 
84739ea
fb08ce6
 
 
 
 
84739ea
fb08ce6
 
 
4f82889
fb08ce6
 
 
 
84739ea
fb08ce6
 
 
 
6bd9991
fb08ce6
 
 
 
 
 
84739ea
fb08ce6
6bd9991
fb08ce6
4f82889
fb08ce6
 
 
84739ea
fb08ce6
 
4f82889
fb08ce6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d927a6e
fb08ce6
 
 
 
 
 
 
4f82889
fb08ce6
84739ea
fb08ce6
 
4f82889
fb08ce6
 
4f82889
 
fb08ce6
 
 
 
6bd9991
84739ea
fb08ce6
 
 
 
 
 
 
 
 
6bd9991
fb08ce6
 
 
c3b008e
fb08ce6
 
 
 
4f82889
fb08ce6
84739ea
73bb808
fb08ce6
 
4f82889
 
fb08ce6
 
 
 
 
84739ea
4372751
 
ac61d23
4372751
84739ea
ac61d23
84739ea
 
 
 
4372751
4f82889
 
4372751
 
 
ac61d23
 
84739ea
 
73bb808
fb08ce6
84739ea
 
c3b008e
84739ea
 
 
fb08ce6
 
 
84739ea
cf37bae
f8b8ae4
84739ea
 
 
6bd9991
c3b008e
73bb808
 
6bd9991
84739ea
 
 
73bb808
c3b008e
 
 
 
 
 
 
84739ea
 
73bb808
84739ea
73bb808
 
 
4f82889
84739ea
cf37bae
84739ea
c3b008e
4f82889
 
c3b008e
73bb808
84739ea
 
 
73bb808
 
84739ea
73bb808
fb08ce6
 
 
84739ea
 
 
 
 
 
 
 
 
 
4372751
84739ea
 
ac61d23
84739ea
 
 
 
 
 
ac61d23
84739ea
 
fb08ce6
 
 
73bb808
d927a6e
84739ea
c3b008e
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
from flask import Flask, render_template, request, redirect, url_for, jsonify, session
import requests
import os
from datetime import timedelta

app = Flask(__name__)
app.secret_key = os.urandom(24)  # Session encryption key
app.permanent_session_lifetime = timedelta(days=7)  # Session duration

# Huggingface URL list
HUGGINGFACE_URLS = [
    "https://huggingface.co/spaces/ginipick/Tech_Hangman_Game",
    "https://huggingface.co/spaces/openfree/deepseek_r1_API",
    "https://huggingface.co/spaces/ginipick/open_Deep-Research",
    "https://huggingface.co/spaces/aiqmaster/open-deep-research",
    "https://huggingface.co/spaces/seawolf2357/DeepSeek-R1-32b-search",
    "https://huggingface.co/spaces/ginigen/LLaDA",
    "https://huggingface.co/spaces/VIDraft/PHI4-Multimodal",
    "https://huggingface.co/spaces/ginigen/Ovis2-8B",
    "https://huggingface.co/spaces/ginigen/Graph-Mind",
    "https://huggingface.co/spaces/ginigen/Workflow-Canvas",
    "https://huggingface.co/spaces/ginigen/Design",
    "https://huggingface.co/spaces/ginigen/Diagram",
    "https://huggingface.co/spaces/ginigen/Mockup",
    "https://huggingface.co/spaces/ginigen/Infographic",
    "https://huggingface.co/spaces/ginigen/Flowchart",
    "https://huggingface.co/spaces/aiqcamp/FLUX-Vision",
    "https://huggingface.co/spaces/ginigen/VoiceClone-TTS",
    "https://huggingface.co/spaces/openfree/Perceptron-Network",
    "https://huggingface.co/spaces/openfree/Article-Generator",
]

# Transform Huggingface URL to direct space URL
def transform_url(url):
    prefix = "https://huggingface.co/spaces/"
    if url.startswith(prefix):
        rest = url[len(prefix):]
        return f"https://{rest.replace('/', '-')}.hf.space"
    return url

# Extract title from the last part of URL
def extract_title(url):
    parts = url.split("/")
    title = parts[-1] if parts else ""
    return title.replace("_", " ").replace("-", " ")

# Huggingface token validation
def validate_token(token):
    headers = {"Authorization": f"Bearer {token}"}
    
    # Try whoami-v2 endpoint first
    try:
        response = requests.get("https://huggingface.co/api/whoami-v2", headers=headers)
        if response.ok:
            return True, response.json()
    except Exception as e:
        print(f"whoami-v2 token validation error: {e}")
    
    # Try the original whoami endpoint
    try:
        response = requests.get("https://huggingface.co/api/whoami", headers=headers)
        if response.ok:
            return True, response.json()
    except Exception as e:
        print(f"whoami token validation error: {e}")
    
    return False, None

# Homepage route
@app.route('/')
def home():
    return render_template('index.html')

# Login API
@app.route('/api/login', methods=['POST'])
def login():
    token = request.form.get('token', '')
    
    if not token:
        return jsonify({'success': False, 'message': 'ํ† ํฐ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.'})
    
    is_valid, user_info = validate_token(token)
    
    if not is_valid or not user_info:
        return jsonify({'success': False, 'message': '์œ ํšจํ•˜์ง€ ์•Š์€ ํ† ํฐ์ž…๋‹ˆ๋‹ค.'})
    
    # Find username
    username = None
    if 'name' in user_info:
        username = user_info['name']
    elif 'user' in user_info and 'username' in user_info['user']:
        username = user_info['user']['username']
    elif 'username' in user_info:
        username = user_info['username']
    else:
        username = '์ธ์ฆ๋œ ์‚ฌ์šฉ์ž'
    
    # Save to session
    session['token'] = token
    session['username'] = username
    
    return jsonify({
        'success': True, 
        'username': username
    })

# Logout API
@app.route('/api/logout', methods=['POST'])
def logout():
    session.pop('token', None)
    session.pop('username', None)
    return jsonify({'success': True})

# URL list API
@app.route('/api/urls', methods=['GET'])
def get_urls():
    search_query = request.args.get('search', '').lower()
    
    results = []
    for url in HUGGINGFACE_URLS:
        title = extract_title(url)
        transformed_url = transform_url(url)
        
        if search_query and search_query not in url.lower() and search_query not in title.lower():
            continue
        
        results.append({
            'url': url,
            'embedUrl': transformed_url,
            'title': title
        })
    
    return jsonify(results)

# Session status API
@app.route('/api/session-status', methods=['GET'])
def session_status():
    return jsonify({
        'logged_in': 'token' in session,
        'username': session.get('username')
    })

if __name__ == '__main__':
    # Create templates folder
    os.makedirs('templates', exist_ok=True)
    
    # Create index.html file
    with open('templates/index.html', 'w', encoding='utf-8') as f:
        f.write('''
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ํ—ˆ๊น…ํŽ˜์ด์Šค ์ŠคํŽ˜์ด์Šค ๊ทธ๋ฆฌ๋“œ</title>
  <style>
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      line-height: 1.6;
      margin: 0;
      padding: 0;
      color: #333;
      background-color: #f5f8fa;
    }
    
    .container {
      max-width: 1400px;
      margin: 0 auto;
      padding: 1rem;
    }
    
    .header {
      background-color: #ffffff;
      padding: 1rem;
      border-radius: 8px;
      margin-bottom: 1rem;
      box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    }
    
    .user-controls {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
    }
    
    .filter-controls {
      background-color: #ffffff;
      padding: 1rem;
      border-radius: 8px;
      margin-bottom: 1rem;
      box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    }
    
    input[type="password"],
    input[type="text"] {
      padding: 0.7rem;
      border: 1px solid #ddd;
      border-radius: 4px;
      margin-right: 5px;
      font-size: 1rem;
      width: 250px;
    }
    
    button {
      padding: 0.7rem 1.2rem;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 1rem;
      transition: background-color 0.2s;
    }
    
    button:hover {
      background-color: #45a049;
    }
    
    button.logout {
      background-color: #f44336;
    }
    
    button.logout:hover {
      background-color: #d32f2f;
    }
    
    .token-help {
      margin-top: 0.5rem;
      font-size: 0.9rem;
      color: #666;
    }
    
    .token-help a {
      color: #4CAF50;
      text-decoration: none;
    }
    
    .token-help a:hover {
      text-decoration: underline;
    }
    
    .grid-container {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(450px, 1fr));
      gap: 1.5rem;
    }
    
    .grid-item {
      background-color: #ffffff;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 4px 15px rgba(0,0,0,0.1);
      display: flex;
      flex-direction: column;
      height: 600px;
    }
    
    .grid-header {
      padding: 0.8rem;
      border-bottom: 1px solid #eee;
      background-color: #f9f9f9;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .grid-header h3 {
      margin: 0;
      padding: 0;
      font-size: 1.1rem;
      color: #333;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .open-link {
      color: #4CAF50;
      text-decoration: none;
      font-size: 0.9rem;
    }
    
    .grid-content {
      flex: 1;
      position: relative;
      overflow: hidden;
    }
    
    .grid-content iframe {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      border: none;
    }
    
    .status-message {
      padding: 1rem;
      border-radius: 8px;
      margin-bottom: 1rem;
      display: none;
      box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    }
    
    .success {
      background-color: #dff0d8;
      color: #3c763d;
    }
    
    .error {
      background-color: #f2dede;
      color: #a94442;
    }
    
    .loading {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(255, 255, 255, 0.8);
      display: none;
      justify-content: center;
      align-items: center;
      z-index: 1000;
      font-size: 1.5rem;
    }
    
    .loading-spinner {
      border: 5px solid #f3f3f3;
      border-top: 5px solid #4CAF50;
      border-radius: 50%;
      width: 50px;
      height: 50px;
      animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
    
    .login-section {
      margin-top: 1rem;
    }
    
    .logged-in-section {
      display: none;
      margin-top: 1rem;
    }
    
    @media (max-width: 768px) {
      .user-controls {
        flex-direction: column;
        align-items: flex-start;
      }
      
      .user-controls > div {
        margin-bottom: 1rem;
      }
      
      .grid-container {
        grid-template-columns: 1fr;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <div class="user-controls">
        <div>
          <span>ํ—ˆ๊น…ํŽ˜์ด์Šค ๊ณ„์ •: </span>
          <span id="currentUser">๋กœ๊ทธ์ธ๋˜์ง€ ์•Š์Œ</span>
        </div>
        
        <div id="loginSection" class="login-section">
          <input type="password" id="tokenInput" placeholder="ํ—ˆ๊น…ํŽ˜์ด์Šค API ํ† ํฐ ์ž…๋ ฅ" />
          <button id="loginButton">์ธ์ฆํ•˜๊ธฐ</button>
          <div class="token-help">
            API ํ† ํฐ์€ <a href="https://huggingface.co/settings/tokens" target="_blank">ํ—ˆ๊น…ํŽ˜์ด์Šค ํ† ํฐ ํŽ˜์ด์ง€</a>์—์„œ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
          </div>
        </div>
        
        <div id="loggedInSection" class="logged-in-section">
          <button id="logoutButton" class="logout">๋กœ๊ทธ์•„์›ƒ</button>
        </div>
      </div>
    </div>
    
    <div class="filter-controls">
      <input type="text" id="searchInput" placeholder="URL ๋˜๋Š” ์ œ๋ชฉ์œผ๋กœ ๊ฒ€์ƒ‰" />
    </div>
    
    <div id="statusMessage" class="status-message"></div>
    
    <div id="gridContainer" class="grid-container"></div>
  </div>
  
  <div id="loadingIndicator" class="loading">
    <div class="loading-spinner"></div>
  </div>
  
  <script>
    // DOM element references
    const elements = {
      tokenInput: document.getElementById('tokenInput'),
      loginButton: document.getElementById('loginButton'),
      logoutButton: document.getElementById('logoutButton'),
      currentUser: document.getElementById('currentUser'),
      gridContainer: document.getElementById('gridContainer'),
      loadingIndicator: document.getElementById('loadingIndicator'),
      statusMessage: document.getElementById('statusMessage'),
      searchInput: document.getElementById('searchInput'),
      loginSection: document.getElementById('loginSection'),
      loggedInSection: document.getElementById('loggedInSection')
    };
    
    // Application state
    const state = {
      username: null,
      isLoading: false
    };
    
    // Display loading indicator
    function setLoading(isLoading) {
      state.isLoading = isLoading;
      elements.loadingIndicator.style.display = isLoading ? 'flex' : 'none';
    }
    
    // Display status message
    function showMessage(message, isError = false) {
      elements.statusMessage.textContent = message;
      elements.statusMessage.className = `status-message ${isError ? 'error' : 'success'}`;
      elements.statusMessage.style.display = 'block';
      
      // Hide message after 3 seconds
      setTimeout(() => {
        elements.statusMessage.style.display = 'none';
      }, 3000);
    }
    
    // API error handling
    async function handleApiResponse(response) {
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`API ์˜ค๋ฅ˜ (${response.status}): ${errorText}`);
      }
      return response.json();
    }
    
    // Check session status
    async function checkSessionStatus() {
      try {
        const response = await fetch('/api/session-status');
        const data = await handleApiResponse(response);
        
        if (data.logged_in) {
          state.username = data.username;
          elements.currentUser.textContent = data.username;
          elements.loginSection.style.display = 'none';
          elements.loggedInSection.style.display = 'block';
          
          // Load URL list
          loadUrls();
        }
      } catch (error) {
        console.error('์„ธ์…˜ ์ƒํƒœ ํ™•์ธ ์˜ค๋ฅ˜:', error);
      }
    }
    
    // Login process
    async function login(token) {
      if (!token.trim()) {
        showMessage('ํ† ํฐ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.', true);
        return;
      }
      
      setLoading(true);
      
      try {
        const formData = new FormData();
        formData.append('token', token);
        
        const response = await fetch('/api/login', {
          method: 'POST',
          body: formData
        });
        
        const data = await handleApiResponse(response);
        
        if (data.success) {
          state.username = data.username;
          
          elements.currentUser.textContent = state.username;
          elements.loginSection.style.display = 'none';
          elements.loggedInSection.style.display = 'block';
          
          showMessage(`${state.username}๋‹˜์œผ๋กœ ๋กœ๊ทธ์ธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.`);
          
          // Load URL list
          loadUrls();
        } else {
          showMessage(data.message || '๋กœ๊ทธ์ธ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.', true);
        }
      } catch (error) {
        console.error('๋กœ๊ทธ์ธ ์˜ค๋ฅ˜:', error);
        showMessage(`๋กœ๊ทธ์ธ ์˜ค๋ฅ˜: ${error.message}`, true);
      } finally {
        setLoading(false);
      }
    }
    
    // Logout process
    async function logout() {
      setLoading(true);
      
      try {
        const response = await fetch('/api/logout', {
          method: 'POST'
        });
        
        const data = await handleApiResponse(response);
        
        if (data.success) {
          state.username = null;
          
          elements.currentUser.textContent = '๋กœ๊ทธ์ธ๋˜์ง€ ์•Š์Œ';
          elements.tokenInput.value = '';
          elements.loginSection.style.display = 'block';
          elements.loggedInSection.style.display = 'none';
          
          showMessage('๋กœ๊ทธ์•„์›ƒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.');
          
          // Clear grid
          elements.gridContainer.innerHTML = '';
        }
      } catch (error) {
        console.error('๋กœ๊ทธ์•„์›ƒ ์˜ค๋ฅ˜:', error);
        showMessage(`๋กœ๊ทธ์•„์›ƒ ์˜ค๋ฅ˜: ${error.message}`, true);
      } finally {
        setLoading(false);
      }
    }
    
    // Load URL list
    async function loadUrls() {
      setLoading(true);
      
      try {
        const searchText = elements.searchInput.value;
        
        const response = await fetch(`/api/urls?search=${encodeURIComponent(searchText)}`);
        const urls = await handleApiResponse(response);
        
        renderGrid(urls);
      } catch (error) {
        console.error('URL ๋ชฉ๋ก ๋กœ๋“œ ์˜ค๋ฅ˜:', error);
        showMessage(`URL ๋กœ๋“œ ์˜ค๋ฅ˜: ${error.message}`, true);
      } finally {
        setLoading(false);
      }
    }
    
    // Render grid
    function renderGrid(urls) {
      elements.gridContainer.innerHTML = '';
      
      if (!urls || urls.length === 0) {
        const noResultsMsg = document.createElement('p');
        noResultsMsg.textContent = 'ํ‘œ์‹œํ•  URL์ด ์—†์Šต๋‹ˆ๋‹ค.';
        noResultsMsg.style.padding = '1rem';
        noResultsMsg.style.fontStyle = 'italic';
        elements.gridContainer.appendChild(noResultsMsg);
        return;
      }
      
      urls.forEach(item => {
        const { url, embedUrl, title } = item;
        
        // Create grid item
        const gridItem = document.createElement('div');
        gridItem.className = 'grid-item';
        
        // Header with title and link
        const header = document.createElement('div');
        header.className = 'grid-header';
        
        const titleEl = document.createElement('h3');
        titleEl.textContent = title;
        header.appendChild(titleEl);
        
        const linkEl = document.createElement('a');
        linkEl.href = url;
        linkEl.target = '_blank';
        linkEl.className = 'open-link';
        linkEl.textContent = '์ƒˆ ์ฐฝ์—์„œ ์—ด๊ธฐ';
        header.appendChild(linkEl);
        
        // Add header to grid item
        gridItem.appendChild(header);
        
        // Content with iframe
        const content = document.createElement('div');
        content.className = 'grid-content';
        
        // Create iframe to display the content
        const iframe = document.createElement('iframe');
        iframe.src = embedUrl;
        iframe.title = title;
        iframe.allow = 'accelerometer; camera; encrypted-media; geolocation; gyroscope; microphone; midi';
        iframe.setAttribute('allowfullscreen', '');
        iframe.setAttribute('frameborder', '0');
        iframe.loading = 'lazy'; // Lazy load iframes for better performance
        
        content.appendChild(iframe);
        
        // Add content to grid item
        gridItem.appendChild(content);
        
        // Add grid item to container
        elements.gridContainer.appendChild(gridItem);
      });
    }
    
    // Event listeners
    elements.loginButton.addEventListener('click', () => {
      login(elements.tokenInput.value);
    });
    
    elements.logoutButton.addEventListener('click', logout);
    
    // Login with Enter key
    elements.tokenInput.addEventListener('keypress', (event) => {
      if (event.key === 'Enter') {
        login(elements.tokenInput.value);
      }
    });
    
    // Filter event listener
    elements.searchInput.addEventListener('input', () => {
      // Debounce input to prevent API calls on every keystroke
      clearTimeout(state.searchTimeout);
      state.searchTimeout = setTimeout(loadUrls, 300);
    });
    
    // Initialize
    checkSessionStatus();
  </script>
</body>
</html>
''')
    
    # Use port 7860 for Huggingface Spaces
    app.run(host='0.0.0.0', port=7860)