File size: 12,485 Bytes
f731b26
e3245dd
f36e14c
 
 
 
 
 
 
 
 
 
 
 
8115d23
6bc35aa
 
 
 
 
 
 
 
 
 
 
f36e14c
6bc35aa
 
 
 
 
 
 
f36e14c
6bc35aa
 
 
f36e14c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bc35aa
 
 
 
 
f36e14c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bc35aa
f36e14c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bc35aa
f36e14c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bc35aa
f36e14c
6bc35aa
 
 
 
 
 
e3245dd
f731b26
 
6bc35aa
 
 
 
 
 
 
 
 
9242a3c
6bc35aa
 
 
 
f36e14c
 
 
 
6bc35aa
 
 
f36e14c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bc35aa
 
 
 
 
 
9242a3c
 
6bc35aa
9242a3c
6bc35aa
e3245dd
f731b26
 
9242a3c
 
6bc35aa
 
e3245dd
9242a3c
6bc35aa
9242a3c
6bc35aa
 
 
9242a3c
6bc35aa
9242a3c
 
6bc35aa
 
 
 
 
 
 
e3245dd
 
9242a3c
 
6bc35aa
9242a3c
6bc35aa
9242a3c
 
6bc35aa
 
 
 
9242a3c
 
6bc35aa
 
 
9d48d79
 
6bc35aa
 
 
f731b26
9242a3c
6bc35aa
 
 
 
 
 
9242a3c
 
6bc35aa
 
e3245dd
6bc35aa
 
9242a3c
 
f36e14c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bc35aa
9242a3c
6bc35aa
 
9242a3c
 
f36e14c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bc35aa
 
 
 
 
 
 
 
 
 
9242a3c
 
6bc35aa
 
 
9242a3c
 
6bc35aa
 
9242a3c
 
6bc35aa
 
 
 
 
9242a3c
 
6bc35aa
e3245dd
6bc35aa
 
9242a3c
 
 
 
 
6bc35aa
 
 
 
f731b26
9242a3c
6bc35aa
 
 
f731b26
9242a3c
6bc35aa
 
 
 
 
 
 
9242a3c
 
6bc35aa
 
 
 
 
9242a3c
 
 
6bc35aa
 
 
 
9242a3c
 
 
 
 
 
 
 
6bc35aa
 
 
 
 
 
 
 
 
f731b26
f36e14c
 
 
 
 
 
 
 
 
6bc35aa
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
<script lang="ts">
  import Dataframe from '@gradio/dataframe';
  import { onMount } from 'svelte';
  import { pipeline, TextStreamer } from "@huggingface/transformers";

  // Global state to avoid reloading model
  type LLMGlobal = { generator: any | null };
  const g = globalThis as any;
  let __LLM: LLMGlobal = g.__LLM || { generator: null };
  g.__LLM = __LLM;

  let isModelReady = !!__LLM.generator;
  let modelStatus = __LLM.generator ? 'โœ… AI ready! Ask me anything about the data.' : 'Loading AI model...';
  let loadingProgress = __LLM.generator ? 100 : 0;

  // Sample data for the dataframe
  let value: { data: string[][]; headers: string[] } = {
    headers: ['Name', 'Age', 'City', 'Score', 'Status'],
    data: [
      ['Alice Johnson', '28', 'New York', '92.5', 'Active'],
      ['Bob Smith', '34', 'Los Angeles', '87.3', 'Active'],
      ['Carol Davis', '29', 'Chicago', '95.1', 'Inactive'],
      ['David Wilson', '42', 'Houston', '78.9', 'Active'],
      ['Eva Brown', '31', 'Phoenix', '88.7', 'Active'],
      ['Frank Miller', '37', 'Philadelphia', '91.2', 'Inactive'],
      ['Grace Lee', '26', 'San Antonio', '94.8', 'Active'],
      ['Henry Taylor', '45', 'San Diego', '82.6', 'Active']
    ]
  };

  function handleChange(event: CustomEvent) {
    value = event.detail;
  }

  let query = 'How old is Alice?';
  let response = '';
  let isSearching = false;

  onMount(async () => {
    if (__LLM.generator) return; // Already loaded
    
    try {
      modelStatus = '๐Ÿ“ฆ Loading model components...';
      loadingProgress = 10;
      
      const generator = await pipeline("text-generation", "onnx-community/gemma-3-270m-it-ONNX", {
        dtype: "fp32",
        device: "webgpu",
        progress_callback: (item) => {
          if (item.status === "progress" && item.file?.endsWith?.("onnx_data")) {
            loadingProgress = Math.min(100, item.progress || 0);
            modelStatus = `๐Ÿš€ Loading model... ${Math.round(loadingProgress)}%`;
          }
        },
      });
      
      __LLM.generator = generator;
      isModelReady = true;
      loadingProgress = 100;
      modelStatus = 'โœ… AI ready! Ask me anything about the data.';
      
      console.log('Gemma-3 model loaded successfully');
    } catch (error) {
      console.error('Failed to initialize model:', error);
      modelStatus = 'โš ๏ธ Failed to load AI model. Using fallback responses.';
      isModelReady = false;
      loadingProgress = 0;
    }
  });

  async function searchData() {
    if (!query.trim()) return;
    
    isSearching = true;
    response = '';
    
    if (!isModelReady || !__LLM.generator) {
      response = 'โณ AI model is still initializing. Please wait...';
      isSearching = false;
      return;
    }

    const userMessage = query.trim();
    
    try {
      response = '๐Ÿค” Thinking...';
      await new Promise(resolve => requestAnimationFrame(resolve));
      
      const systemPrompt = `You are a helpful AI assistant that answers questions about employee data. Here's the current data:

${value.headers.join(' | ')}
${value.data.map(row => row.join(' | ')).join('\n')}

Keep your responses concise and helpful. Answer questions about the data above. Use emojis to make responses engaging.`;

      const messages = [
        { role: "system", content: systemPrompt },
        { role: "user", content: userMessage }
      ];

      let fullResponse = '';
      const streamer = new TextStreamer(__LLM.generator.tokenizer, {
        skip_prompt: true,
        skip_special_tokens: true,
        callback_function: (token: string) => {
          fullResponse += token;
          response = fullResponse;
        },
      });

      await __LLM.generator(messages, {
        max_new_tokens: 256,
        do_sample: false,
        streamer,
      });

      response = fullResponse || 'Sorry, I couldn\'t generate a response.';
      
    } catch (error) {
      console.error('Generation error:', error);
      
      // Fallback to smart responses based on query analysis
      const lowerQuery = userMessage.toLowerCase();
      
      if (lowerQuery.includes('how many') || lowerQuery.includes('count')) {
        if (lowerQuery.includes('active')) {
          const activeCount = value.data.filter(row => row[4] === 'Active').length;
          response = `๐Ÿ“Š There are ${activeCount} active users in the dataset.`;
        } else if (lowerQuery.includes('inactive')) {
          const inactiveCount = value.data.filter(row => row[4] === 'Inactive').length;
          response = `๐Ÿ“Š There are ${inactiveCount} inactive users in the dataset.`;
        } else {
          response = `๐Ÿ“Š There are ${value.data.length} total records in the dataset.`;
        }
      } else if (lowerQuery.includes('highest score') || lowerQuery.includes('best score')) {
        const scores = value.data.map(row => parseFloat(row[3]));
        const maxScore = Math.max(...scores);
        const topUser = value.data.find(row => parseFloat(row[3]) === maxScore);
        response = `๐Ÿ† ${topUser?.[0]} has the highest score of ${maxScore} from ${topUser?.[2]}.`;
      } else if (lowerQuery.includes('lowest score') || lowerQuery.includes('worst score')) {
        const scores = value.data.map(row => parseFloat(row[3]));
        const minScore = Math.min(...scores);
        const bottomUser = value.data.find(row => parseFloat(row[3]) === minScore);
        response = `๐Ÿ“‰ ${bottomUser?.[0]} has the lowest score of ${minScore} from ${bottomUser?.[2]}.`;
      } else if (lowerQuery.includes('average age') || lowerQuery.includes('mean age')) {
        const ages = value.data.map(row => parseInt(row[1]));
        const avgAge = (ages.reduce((sum, age) => sum + age, 0) / ages.length).toFixed(1);
        response = `๐Ÿ‘ฅ The average age of users is ${avgAge} years old.`;
      } else {
        response = `โš ๏ธ Sorry, I encountered an error processing your request. Please try a different question about the data.`;
      }
    } finally {
      isSearching = false;
    }
  }

  function handleKeyPress(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      searchData();
    }
  }
</script>

<div class="fullscreen-dataframe">
  <div class="dataframe-container">
    <Dataframe
      bind:value={value}
      show_row_numbers={true}
      editable={true}
      on:change={handleChange}
    />
  </div>
  
  <div class="search-panel">
    <div class="search-container">
      <div class="search-header">
        <h2>โœจ Ask me anything about your data</h2>
        <p>Try: "How old is Alice?"</p>
        <div class="built-with">
          โค๏ธŽ &nbsp; Built with Gemma 3 270M Onnx & <a href="https://www.gradio.app/docs/js/dataframe" target="_blank" rel="noopener noreferrer">Gradio's Dataframe.js</a>
        </div>
      </div>
      
      <div class="search-input-container">
        {#if !isModelReady}
          <div class="progress-container">
            <div class="progress-bar">
              <div class="progress-fill" style="width: {loadingProgress}%"></div>
            </div>
            <div class="progress-text">{modelStatus}</div>
          </div>
        {:else}
          <input
            type="text"
            bind:value={query}
            on:keypress={handleKeyPress}
            class="search-input"
            disabled={isSearching}
          />
          <button 
            class="search-button"
            on:click={searchData}
            disabled={isSearching || !query.trim()}
          >
            {#if isSearching}
              <div class="spinner"></div>
            {:else}
              ๐Ÿ” Ask
            {/if}
          </button>
        {/if}
      </div>
      
      {#if response}
        <div class="response-container">
          <div class="response-text">
            {response}
          </div>
        </div>
      {/if}
    </div>
  </div>
</div>

<style>
  :global(*) {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }

  :global(body, html) {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', sans-serif;
  }

  .fullscreen-dataframe {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    background: white;
    display: flex;
    flex-direction: column;
  }

  .dataframe-container {
    flex: 1;
    overflow: hidden;
  }

  .search-panel {
    background: linear-gradient(135deg, #ff6b35 0%, #1a1a1a 100%);
    padding: 2rem;
    box-shadow: 0 -10px 30px rgba(0, 0, 0, 0.1);
  }

  .search-container {
    max-width: 800px;
    margin: 0 auto;
  }

  .search-header {
    text-align: center;
    margin-bottom: 1.5rem;
  }

  .search-header h2 {
    color: white;
    font-size: 1.8rem;
    font-weight: 700;
    margin: 0 0 0.5rem 0;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }

  .search-header p {
    color: rgba(255, 255, 255, 0.9);
    font-size: 1rem;
    margin: 0;
    opacity: 0.9;
  }

  .built-with {
    color: rgba(255, 255, 255, 0.7);
    font-size: 0.85rem;
    margin-top: 0.5rem;
    font-style: italic;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  }

  .built-with a {
    color: rgba(255, 255, 255, 0.9);
    text-decoration: underline;
    text-decoration-color: rgba(255, 255, 255, 0.5);
    transition: all 0.2s ease;
  }

  .built-with a:hover {
    color: white;
    text-decoration-color: white;
  }

  .search-input-container {
    display: flex;
    gap: 1rem;
    margin-bottom: 1.5rem;
  }

  .progress-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
  }

  .progress-bar {
    height: 60px;
    background: rgba(255, 255, 255, 0.2);
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-radius: 50px;
    overflow: hidden;
    backdrop-filter: blur(10px);
    position: relative;
    padding: 0;
  }

  .progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #ff6b35, rgba(255, 255, 255, 0.8));
    border-radius: 0;
    transition: width 0.5s ease-out;
    position: absolute;
    top: 0;
    left: 0;
    overflow: hidden;
  }

  .progress-fill::after {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
    animation: shimmer 2s infinite;
  }

  .progress-text {
    color: white;
    text-align: center;
    font-weight: 600;
    font-size: 1rem;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }

  .search-input {
    flex: 1;
    padding: 1rem 1.5rem;
    border: none;
    border-radius: 50px;
    font-size: 1.1rem;
    background: white;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    outline: none;
    transition: all 0.3s ease;
  }

  .search-input:focus {
    box-shadow: 0 6px 25px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }

  .search-input:disabled {
    opacity: 0.7;
  }

  .search-button {
    padding: 1rem 2rem;
    background: rgba(255, 255, 255, 0.2);
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-radius: 50px;
    color: white;
    font-weight: 600;
    font-size: 1.1rem;
    cursor: pointer;
    transition: all 0.3s ease;
    backdrop-filter: blur(10px);
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  .search-button:hover:not(:disabled) {
    background: rgba(255, 255, 255, 0.3);
    border-color: rgba(255, 255, 255, 0.5);
    transform: translateY(-2px);
  }

  .search-button:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .response-container {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    padding: 1.5rem 2rem;
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    animation: slideUp 0.5s ease-out;
  }

  .response-text {
    font-size: 1.1rem;
    line-height: 1.6;
    color: #2d3748;
    margin: 0;
  }

  .spinner {
    width: 20px;
    height: 20px;
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-top: 2px solid white;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    to { transform: rotate(360deg); }
  }

  @keyframes slideUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  @keyframes shimmer {
    0% {
      left: -100%;
    }
    100% {
      left: 100%;
    }
  }
</style>