ivanoctaviogaitansantos commited on
Commit
d369456
verified
1 Parent(s): b7429f8

Upload index.js with huggingface_hub

Browse files
Files changed (1) hide show
  1. index.js +179 -67
index.js CHANGED
@@ -1,76 +1,188 @@
1
- import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/[email protected]';
2
-
3
- // Reference the elements that we will need
4
- const status = document.getElementById('status');
5
- const fileUpload = document.getElementById('upload');
6
- const imageContainer = document.getElementById('container');
7
- const example = document.getElementById('example');
8
-
9
- const EXAMPLE_URL = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/city-streets.jpg';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- // Create a new object detection pipeline
12
- status.textContent = 'Loading model...';
13
- const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50');
14
- status.textContent = 'Ready';
 
 
 
15
 
16
- example.addEventListener('click', (e) => {
17
- e.preventDefault();
18
- detect(EXAMPLE_URL);
19
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- fileUpload.addEventListener('change', function (e) {
22
- const file = e.target.files[0];
23
- if (!file) {
 
 
 
 
 
24
  return;
25
  }
26
-
27
- const reader = new FileReader();
28
-
29
- // Set up a callback when the file is loaded
30
- reader.onload = e2 => detect(e2.target.result);
31
-
32
- reader.readAsDataURL(file);
33
- });
34
-
35
-
36
- // Detect objects in the image
37
- async function detect(img) {
38
- imageContainer.innerHTML = '';
39
- imageContainer.style.backgroundImage = `url(${img})`;
40
-
41
- status.textContent = 'Analysing...';
42
- const output = await detector(img, {
43
- threshold: 0.5,
44
- percentage: true,
45
- });
46
- status.textContent = '';
47
- output.forEach(renderBox);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  }
49
 
50
- // Render a bounding box and label on the image
51
- function renderBox({ box, label }) {
52
- const { xmax, xmin, ymax, ymin } = box;
53
-
54
- // Generate a random color for the box
55
- const color = '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, 0);
56
-
57
- // Draw the box
58
- const boxElement = document.createElement('div');
59
- boxElement.className = 'bounding-box';
60
- Object.assign(boxElement.style, {
61
- borderColor: color,
62
- left: 100 * xmin + '%',
63
- top: 100 * ymin + '%',
64
- width: 100 * (xmax - xmin) + '%',
65
- height: 100 * (ymax - ymin) + '%',
66
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
- // Draw label
69
- const labelElement = document.createElement('span');
70
- labelElement.textContent = label;
71
- labelElement.className = 'bounding-box-label';
72
- labelElement.style.backgroundColor = color;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
- boxElement.appendChild(labelElement);
75
- imageContainer.appendChild(boxElement);
76
- }
 
1
+ // index.js
2
+ import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/[email protected]';
3
+
4
+ // DOM elements
5
+ const taskSelect = document.getElementById('task-select');
6
+ const deviceSelect = document.getElementById('device-select');
7
+ const inputText = document.getElementById('input-text');
8
+ const runBtn = document.getElementById('run-btn');
9
+ const outputContainer = document.getElementById('output');
10
+
11
+ // Model mapping
12
+ const modelMap = {
13
+ 'text-classification': 'distilbert-base-uncased-finetuned-sst-2-english',
14
+ 'sentiment-analysis': 'distilbert-base-uncased-finetuned-sst-2-english',
15
+ 'question-answering': 'deepset/roberta-base-squad2',
16
+ 'text-generation': 'gpt2',
17
+ 'translation': 't5-small'
18
+ };
19
+
20
+ // Initialize pipeline
21
+ let currentPipeline = null;
22
+ let currentTask = null;
23
+
24
+ // Check WebGPU support
25
+ function checkWebGPUSupport() {
26
+ return 'gpu' in navigator;
27
+ }
28
 
29
+ // Update device options based on support
30
+ if (!checkWebGPUSupport()) {
31
+ const option = document.querySelector('#device-select option[value="webgpu"]');
32
+ option.disabled = true;
33
+ option.textContent = 'GPU (WebGPU) - Not Supported';
34
+ deviceSelect.value = 'cpu';
35
+ }
36
 
37
+ // Function to create pipeline
38
+ async function createPipeline(task, device) {
39
+ const modelName = modelMap[task];
40
+
41
+ // Show loading state
42
+ outputContainer.innerHTML = '<p class="loading">Loading model...</p>';
43
+
44
+ try {
45
+ // Create pipeline with selected device
46
+ if (device === 'webgpu' && checkWebGPUSupport()) {
47
+ return await pipeline(task, modelName, { device: 'webgpu' });
48
+ } else {
49
+ return await pipeline(task, modelName);
50
+ }
51
+ } catch (error) {
52
+ console.error('Error creating pipeline:', error);
53
+ outputContainer.innerHTML = `<p class="error">Error loading model: ${error.message}</p>`;
54
+ return null;
55
+ }
56
+ }
57
 
58
+ // Function to run the model
59
+ async function runModel() {
60
+ const task = taskSelect.value;
61
+ const device = deviceSelect.value;
62
+ const text = inputText.value.trim();
63
+
64
+ if (!text) {
65
+ outputContainer.innerHTML = '<p class="error">Please enter some text to process.</p>';
66
  return;
67
  }
68
+
69
+ // Check if pipeline needs to be recreated
70
+ if (!currentPipeline || currentTask !== task) {
71
+ currentPipeline = await createPipeline(task, device);
72
+ currentTask = task;
73
+ }
74
+
75
+ if (!currentPipeline) {
76
+ return;
77
+ }
78
+
79
+ // Show processing state
80
+ outputContainer.innerHTML = '<p class="loading">Processing...</p>';
81
+
82
+ try {
83
+ let result;
84
+
85
+ switch (task) {
86
+ case 'text-classification':
87
+ case 'sentiment-analysis':
88
+ result = await currentPipeline(text);
89
+ break;
90
+ case 'question-answering':
91
+ // For QA, we need context and question
92
+ const [context, question] = text.split('\n').length > 1
93
+ ? [text.split('\n').slice(0, -1).join(' '), text.split('\n').pop()]
94
+ : ['The sky is blue.', text];
95
+ result = await currentPipeline(question, context);
96
+ break;
97
+ case 'text-generation':
98
+ result = await currentPipeline(text, { max_new_tokens: 50 });
99
+ break;
100
+ case 'translation':
101
+ result = await currentPipeline(text, {
102
+ src_lang: 'en',
103
+ tgt_lang: 'de'
104
+ });
105
+ break;
106
+ default:
107
+ throw new Error('Unsupported task');
108
+ }
109
+
110
+ // Display results
111
+ displayResults(result, task);
112
+ } catch (error) {
113
+ console.error('Error running model:', error);
114
+ outputContainer.innerHTML = `<p class="error">Error processing text: ${error.message}</p>`;
115
+ }
116
  }
117
 
118
+ // Function to display results based on task
119
+ function displayResults(result, task) {
120
+ let content = '';
121
+
122
+ switch (task) {
123
+ case 'text-classification':
124
+ case 'sentiment-analysis':
125
+ content = `
126
+ <h4>Classification Results:</h4>
127
+ <ul>
128
+ ${result.map(item => `
129
+ <li>
130
+ <strong>${item.label}:</strong> ${(item.score * 100).toFixed(2)}%
131
+ </li>
132
+ `).join('')}
133
+ </ul>
134
+ `;
135
+ break;
136
+ case 'question-answering':
137
+ content = `
138
+ <h4>Answer:</h4>
139
+ <p>${result.answer}</p>
140
+ <p><strong>Confidence:</strong> ${(result.score * 100).toFixed(2)}%</p>
141
+ `;
142
+ break;
143
+ case 'text-generation':
144
+ content = `
145
+ <h4>Generated Text:</h4>
146
+ <p>${result[0].generated_text}</p>
147
+ `;
148
+ break;
149
+ case 'translation':
150
+ content = `
151
+ <h4>Translation:</h4>
152
+ <p>${result[0].translation_text}</p>
153
+ `;
154
+ break;
155
+ default:
156
+ content = `<pre>${JSON.stringify(result, null, 2)}</pre>`;
157
+ }
158
+
159
+ outputContainer.innerHTML = content;
160
+ }
161
 
162
+ // Event listeners
163
+ runBtn.addEventListener('click', runModel);
164
+
165
+ // Handle task change
166
+ taskSelect.addEventListener('change', () => {
167
+ // Reset pipeline when task changes
168
+ currentPipeline = null;
169
+ currentTask = null;
170
+
171
+ // Update placeholder text based on task
172
+ switch (taskSelect.value) {
173
+ case 'question-answering':
174
+ inputText.placeholder = "Enter context and question separated by a new line\nContext: The sky is blue.\nQuestion: What color is the sky?";
175
+ break;
176
+ case 'text-generation':
177
+ inputText.placeholder = "Enter a prompt to generate text from...";
178
+ break;
179
+ case 'translation':
180
+ inputText.placeholder = "Enter text to translate from English to German...";
181
+ break;
182
+ default:
183
+ inputText.placeholder = "Enter your text here...";
184
+ }
185
+ });
186
 
187
+ // Initialize with default task
188
+ taskSelect.dispatchEvent(new Event('change'));