File size: 17,748 Bytes
d3f86d8
 
d11eae0
d3f86d8
d11eae0
a4093da
d6b0699
d3f86d8
33b2a07
d6b0699
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1e134e
d6b0699
 
b1e134e
d6b0699
 
b1e134e
d6b0699
 
 
 
89b56c4
4c355e8
 
 
b29b26f
c3ec5b9
 
e459198
33b2a07
d3f86d8
c3ec5b9
 
 
 
 
 
 
 
 
000ec77
33b2a07
b1e134e
 
 
 
 
 
 
 
33b2a07
d3f86d8
 
 
 
 
33b2a07
d3f86d8
68d4ca1
d3f86d8
 
33b2a07
e459198
 
 
 
 
 
 
 
 
 
 
b29b26f
89b56c4
 
0393294
 
33b2a07
b29b26f
 
 
33b2a07
b29b26f
 
b59748f
89b56c4
 
 
 
 
 
 
b59748f
89b56c4
b59748f
89b56c4
 
 
 
b59748f
 
89b56c4
 
 
 
 
 
b29b26f
 
89b56c4
b29b26f
33b2a07
b29b26f
 
 
 
 
 
d3f86d8
 
33b2a07
89b56c4
 
 
8e2dc77
d3f86d8
89b56c4
 
b59748f
d3f86d8
33b2a07
d3f86d8
89b56c4
 
 
 
b59748f
 
89b56c4
 
 
 
8e2dc77
d3f86d8
 
 
 
 
 
 
 
 
b59748f
89b56c4
33b2a07
a4093da
 
 
2fad28f
a4093da
2fad28f
a4093da
 
 
 
 
b29b26f
d3f86d8
68d4ca1
 
 
 
 
 
 
 
 
 
 
d3f86d8
 
 
a4093da
 
 
d3f86d8
68d4ca1
 
 
 
 
 
 
 
 
 
a45e6a8
68d4ca1
a4093da
 
 
 
68d4ca1
 
 
b29b26f
 
 
 
68d4ca1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c355e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33b2a07
 
4c355e8
 
 
 
0393294
b59748f
89b56c4
 
 
 
 
 
b59748f
89b56c4
b59748f
89b56c4
 
 
 
b59748f
 
89b56c4
 
 
 
 
 
 
 
 
4c355e8
 
 
 
 
d3f86d8
 
 
 
 
 
33b2a07
d11eae0
33b2a07
 
 
d11eae0
d3f86d8
 
33b2a07
 
 
d3f86d8
 
33b2a07
 
a4093da
 
33b2a07
d11eae0
 
d3f86d8
d11eae0
d3f86d8
 
 
d11eae0
33b2a07
d11eae0
 
 
 
d3f86d8
d11eae0
d3f86d8
d11eae0
33b2a07
d3f86d8
 
 
 
 
 
 
33b2a07
d3f86d8
 
 
 
 
 
 
33b2a07
d3f86d8
 
 
 
 
 
 
33b2a07
d3f86d8
 
 
 
 
 
 
33b2a07
a4093da
 
c3ec5b9
d3f86d8
a4093da
 
d3f86d8
a4093da
 
d3f86d8
a4093da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3f86d8
33b2a07
d3f86d8
 
a4093da
 
 
 
 
 
 
d3f86d8
 
4c355e8
 
 
 
 
 
33b2a07
4c355e8
 
b29b26f
4c355e8
 
33b2a07
 
 
 
 
 
4c355e8
 
b29b26f
 
33b2a07
 
b29b26f
 
4c355e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33b2a07
c3ec5b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<script>
  import '../app.css';
  import { Home, Settings, Github, Menu, Mic, Layout, Code } from 'lucide-svelte';
  import { onMount } from 'svelte';
  import { page } from '$app/stores';
  import Navbar from '$lib/components/Navbar.svelte';

  let sidebarOpen = true;

  // Initialize from server-injected data
  let initialUser = { authenticated: false };
  let isLoggedIn = false;
  let username = '';

  function setUserFromInitialData(userData) {
    initialUser = userData;
    isLoggedIn = userData?.authenticated || false;
    if (userData?.authenticated && userData?.user_info) {
      const userInfo = userData.user_info;
      const fullName =
        userInfo.name || userInfo.fullname || userInfo.login || userInfo.username || 'User';
      username = fullName.split(' ')[0];
    }
  }

  // Listen for the initial data immediately (before onMount)
  if (typeof window !== 'undefined') {
    // Check if data already exists
    if (window.__INITIAL_USER__) {
      console.log('Found initial user data:', window.__INITIAL_USER__);
      setUserFromInitialData(window.__INITIAL_USER__);
    } else {
      console.log('No initial user data found, listening for event');
      // Listen for the event
      window.addEventListener('initial-user-loaded', (e) => {
        console.log('Received initial user event:', e.detail);
        setUserFromInitialData(e.detail);
      });
    }
  }

  let showTokenInput = false;
  let tokenInput = '';
  let tokenError = '';
  let isLocalEnvironment = false;
  let showLoginPrompt = false;
  let flashButton = false;
  let isSpaces = false;

  onMount(() => {
    // Listen for event to show login prompt
    window.addEventListener('show-login-prompt', () => {
      if (!isLoggedIn) {
        showLoginPrompt = true;
        flashButton = true;
        setTimeout(() => {
          flashButton = false;
        }, 1600);
      }
    });

    // Check if running on Spaces first
    checkSpacesStatus().then(() => {
      // If we don't have initial user data (development mode), check auth status
      if (!window.__INITIAL_USER__ && !initialUser?.authenticated) {
        console.log('No server data available, checking auth status via API');
        checkLoginStatus();
      }
    });

    document.addEventListener('visibilitychange', () => {
      if (!document.hidden) {
        checkLoginStatus();
      }
    });

    return () => {
      // Cleanup function
    };
  });

  async function checkSpacesStatus() {
    try {
      const response = await fetch('/api/status');
      const data = await response.json();
      isSpaces = data.is_spaces || false;
    } catch (error) {
      console.error('Error checking Spaces status:', error);
      isSpaces = false;
    }
  }

  async function checkLocalTokenAvailability() {
    // Only check if not already authenticated
    if (isLoggedIn) {
      return;
    }

    try {
      const response = await fetch('/api/auth/local-token');
      const data = await response.json();

      if (data.available) {
        isLocalEnvironment = true;

        // For local tokens, create session via manual token endpoint if not already authenticated
        if (data.token && !isLoggedIn) {
          try {
            const tokenResponse = await fetch('/api/auth/manual-token', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              credentials: 'include',
              body: JSON.stringify({ token: data.token }),
            });

            if (tokenResponse.ok) {
              const tokenData = await tokenResponse.json();
              isLoggedIn = true;
              const userInfo = tokenData.user_info;
              const fullName =
                userInfo.name || userInfo.fullname || userInfo.login || userInfo.username || 'User';
              username = fullName.split(' ')[0];
            }
          } catch (error) {
            console.error('Local token session creation failed:', error);
          }
        } else if (data.user_info && data.user_info.name !== 'Local User' && !isLoggedIn) {
          isLoggedIn = true;
          username = data.user_info.name.split(' ')[0];
        } else if (!isLoggedIn) {
          isLoggedIn = true;
          username = 'Local User';
        }
      } else {
        isLocalEnvironment = false;
      }
    } catch (error) {
      isLocalEnvironment = false;
    }
  }

  async function checkLoginStatus() {
    // Only check if we don't have initial data or need to refresh
    if (initialUser?.authenticated && isLoggedIn) return;

    try {
      // Check session-based auth via backend
      const response = await fetch('/api/auth/user', {
        credentials: 'include', // Include cookies
      });

      if (response.ok) {
        const data = await response.json();
        if (data.authenticated) {
          isLoggedIn = true;
          const userInfo = data.user_info;
          const fullName =
            userInfo.name || userInfo.fullname || userInfo.login || userInfo.username || 'User';
          username = fullName.split(' ')[0];
        } else {
          isLoggedIn = false;
          username = '';
        }
      } else {
        isLoggedIn = false;
        username = '';
      }
    } catch (error) {
      isLoggedIn = false;
      username = '';
    }
  }

  // Removed old localStorage-based functions

  function getPageTitle(pathname) {
    switch (pathname) {
      case '/':
        return 'Text to Speech Playground';
      case '/voice-cloning':
        return 'Voice Cloning Playground';
      default:
        return 'HFStudio';
    }
  }

  async function handleAuthAction() {
    if (isLoggedIn) {
      // Call backend logout endpoint to clear session
      try {
        await fetch('/api/auth/logout', {
          method: 'POST',
          credentials: 'include',
        });
      } catch (error) {
        console.error('Logout error:', error);
      }

      // Clear any legacy storage
      sessionStorage.removeItem('oauth_state');
      isLoggedIn = false;
      username = '';

      // Refresh the page to ensure clean state
      window.location.reload();
    } else {
      // Always use OAuth flow for authentication
      try {
        const response = await fetch('/api/auth/oauth-config');
        const config = await response.json();
        const scopes = config.scopes || 'inference-api';

        // For local development, use backend port for callback
        let redirectUri = window.location.origin + '/auth/callback';
        if (window.location.hostname === 'localhost' && window.location.port === '11111') {
          redirectUri = 'http://localhost:7860/auth/callback';
        }

        // Store current path to return to after auth
        const returnPath = window.location.pathname;

        const oauthUrl = `https://huggingface.co/oauth/authorize?client_id=${config.client_id}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent(scopes)}&response_type=code&state=${encodeURIComponent(returnPath)}`;
        window.location.href = oauthUrl;
      } catch (error) {
        // Fallback to manual token input if OAuth config fails
        showTokenInput = true;
        tokenInput = '';
        tokenError = '';
      }

      // Old approach - commented out
      // if (isSpaces) {
      //   try {
      //     const response = await fetch('/api/auth/oauth-config');
      //     const config = await response.json();
      //     const scopes = config.scopes || 'read-repos write-repos manage-repos inference-api';
      //     const oauthUrl = `https://huggingface.co/oauth/authorize?client_id=${config.client_id}&redirect_uri=${encodeURIComponent(window.location.origin + '/auth/callback')}&scope=${encodeURIComponent(scopes)}&response_type=code&state=${Date.now()}`;
      //     window.location.href = oauthUrl;
      //   } catch (error) {
      //     showTokenInput = true;
      //     tokenInput = '';
      //     tokenError = '';
      //   }
      // } else {
      //   showTokenInput = true;
      //   tokenInput = '';
      //   tokenError = '';
      // }
    }
  }

  function closeTokenInput() {
    showTokenInput = false;
    tokenInput = '';
    tokenError = '';
  }

  async function submitToken() {
    if (!tokenInput.trim()) {
      tokenError = 'Please enter a token';
      return;
    }

    if (!tokenInput.startsWith('hf_')) {
      tokenError = 'Token should start with "hf_"';
      return;
    }

    try {
      const response = await fetch('https://huggingface.co/api/whoami-v2', {
        headers: {
          Authorization: `Bearer ${tokenInput.trim()}`,
        },
      });

      if (response.ok) {
        const userData = await response.json();
        const token = tokenInput.trim();

        // Send token to backend for validation and session creation
        try {
          const tokenResponse = await fetch('/api/auth/manual-token', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            credentials: 'include',
            body: JSON.stringify({ token: token }),
          });

          if (tokenResponse.ok) {
            const tokenData = await tokenResponse.json();
            isLoggedIn = true;
            const userInfo = tokenData.user_info;
            const fullName =
              userInfo.name || userInfo.fullname || userInfo.login || userInfo.username || 'User';
            username = fullName.split(' ')[0];
            closeTokenInput();
          } else {
            const errorData = await tokenResponse.json();
            tokenError = errorData.detail || 'Token validation failed';
          }
        } catch (error) {
          tokenError = 'Failed to validate token. Please try again.';
        }
      } else {
        tokenError = `Invalid token (${response.status}). Please check your token and try again.`;
      }
    } catch (error) {
      tokenError = 'Error validating token. Please try again.';
    }
  }
</script>

<div class="flex h-screen bg-white">
  <!-- Sidebar -->
  <aside
    class="w-56 border-r border-gray-200 bg-white flex-shrink-0 flex flex-col h-full relative {sidebarOpen
      ? ''
      : 'hidden'}"
  >
    <div class="px-4 py-4 border-b border-gray-200 min-h-[73px] flex items-center">
      <div class="flex items-center gap-3">
        <img src="/assets/hf-studio-logo.png" alt="HF Logo" class="w-8 h-8" />
        <h1 class="text-xl font-semibold">
          HFStudio<sup class="text-xs text-gray-500 ml-1">BETA</sup>
        </h1>
      </div>
    </div>

    <nav class="p-2 text-sm flex-1">
      <!-- Audio Section -->
      <div class="mt-2 mb-1 px-2 text-xs font-medium text-gray-500 uppercase">Audio</div>

      <a
        href="/"
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-gray-100 transition-colors text-left
               {$page.url.pathname === '/' ? 'bg-gray-100' : ''}"
      >
        <span>πŸŽ™οΈ</span>
        <span>Text to Speech</span>
      </a>

      <a
        href="/voice-cloning"
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-gray-100 transition-colors text-left
               {$page.url.pathname === '/voice-cloning' ? 'bg-gray-100' : ''}"
      >
        <Mic size={16} />
        <span>Voice Cloning</span>
      </a>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>🎧</span>
        <span>Speech to Text</span>
      </button>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>🎼</span>
        <span>Sound Effects</span>
      </button>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>🎸</span>
        <span>Music Generation</span>
      </button>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>πŸ”Š</span>
        <span>Audio Enhancement</span>
      </button>

      <!-- Image Section -->
      <div class="mt-4 mb-1 px-2 text-xs font-medium text-gray-500 uppercase">Image</div>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>🎨</span>
        <span>Text to Image</span>
      </button>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>πŸ–ΌοΈ</span>
        <span>Image to Image</span>
      </button>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>βœ‚οΈ</span>
        <span>Remove Background</span>
      </button>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>πŸ”</span>
        <span>Upscale Image</span>
      </button>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>🎭</span>
        <span>Face Swap</span>
      </button>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>πŸ“</span>
        <span>Image to Text</span>
      </button>

      <!-- Video Section -->
      <div class="mt-4 mb-1 px-2 text-xs font-medium text-gray-500 uppercase">Video</div>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>🎬</span>
        <span>Text to Video</span>
      </button>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>🎞️</span>
        <span>Image to Video</span>
      </button>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>✨</span>
        <span>Video Enhancement</span>
      </button>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>🎀</span>
        <span>Lip Sync</span>
      </button>

      <button
        class="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left opacity-40 cursor-not-allowed"
        disabled
      >
        <span>πŸ—£οΈ</span>
        <span>Video Dubbing</span>
      </button>
    </nav>
  </aside>

  <!-- Main content -->
  <main class="flex-1 overflow-auto">
    <Navbar
      {isLoggedIn}
      {username}
      {handleAuthAction}
      {flashButton}
      pageTitle={getPageTitle($page.url.pathname)}
    />
    <slot />
  </main>

  <!-- Token Input Modal -->
  {#if showTokenInput}
    <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-6 max-w-md w-full mx-4 shadow-xl">
        <h2 class="text-xl font-semibold mb-4">Sign In with HuggingFace Token</h2>

        <div class="mb-4 p-3 bg-blue-50 rounded-md text-sm">
          <p class="text-blue-800 mb-2">
            <strong>Manual Token Entry:</strong> Please enter your HuggingFace token.
          </p>
          <p class="text-blue-700">
            1. Go to <a
              href="https://huggingface.co/settings/tokens"
              target="_blank"
              class="underline text-blue-600">HuggingFace Settings</a
            ><br />
            2. Create a new token with "Inference API" permissions<br />
            3. Copy and paste it below
          </p>
          {#if isLocalEnvironment}
            <p class="text-blue-600 mt-2">
              <strong>Tip:</strong> You can also run <code>huggingface-cli login</code> in your terminal
              to automatically use your local token.
            </p>
          {/if}
        </div>

        <div class="mb-4">
          <label for="token" class="block text-sm font-medium text-gray-700 mb-2">
            HuggingFace Token
          </label>
          <input
            id="token"
            type="password"
            bind:value={tokenInput}
            placeholder="hf_..."
            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent"
            on:keydown={(e) => e.key === 'Enter' && submitToken()}
          />
          {#if tokenError}
            <p class="text-red-600 text-sm mt-1">{tokenError}</p>
          {/if}
        </div>

        <div class="flex justify-end gap-3">
          <button
            on:click={closeTokenInput}
            class="px-4 py-2 text-gray-600 hover:text-gray-800 transition-colors"
          >
            Cancel
          </button>
          <button
            on:click={submitToken}
            class="px-4 py-2 bg-orange-500 text-white rounded-md hover:bg-orange-600 transition-colors"
          >
            Sign In
          </button>
        </div>
      </div>
    </div>
  {/if}
</div>

<style>
  @keyframes sweep {
    from {
      transform: translateX(-100%);
    }
    to {
      transform: translateX(300%);
    }
  }

  .animate-sweep {
    animation: sweep 1.6s linear forwards;
  }
</style>