File size: 13,852 Bytes
8a86087
0580361
 
 
 
 
 
 
 
 
 
 
 
99045dc
8a86087
99045dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a86087
 
0580361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a86087
 
 
 
0580361
8a86087
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0580361
 
 
 
 
 
 
8a86087
 
 
 
 
 
 
 
 
 
 
 
99045dc
8a86087
99045dc
 
8a86087
99045dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a86087
99045dc
 
 
 
 
 
 
8a86087
 
 
0580361
 
 
 
8a86087
 
0580361
8a86087
 
 
 
99045dc
8a86087
99045dc
 
8a86087
99045dc
8a86087
 
 
 
99045dc
 
 
 
 
8a86087
 
 
 
 
99045dc
8a86087
 
 
 
 
99045dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a86087
99045dc
8a86087
 
 
99045dc
8a86087
 
 
 
 
 
0580361
8a86087
0580361
 
 
 
 
 
 
8a86087
0580361
 
 
8a86087
 
 
 
 
 
 
0580361
8a86087
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0580361
 
 
 
 
 
8a86087
 
 
 
 
 
0580361
 
8a86087
 
 
 
 
 
 
 
 
 
 
 
 
0580361
8a86087
0580361
 
8a86087
0580361
 
 
 
 
8a86087
0580361
 
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

document.addEventListener('DOMContentLoaded', function() {
    // DOM Elements
    const dropZone = document.getElementById('dropZone');
    const fileInput = document.getElementById('fileInput');
    const imagePreview = document.getElementById('imagePreview');
    const imagePreviewContainer = document.getElementById('imagePreviewContainer');
    const annotationCanvas = document.getElementById('annotationCanvas');
    const analyzeBtn = document.getElementById('analyzeBtn');
    const exportBtn = document.getElementById('exportBtn');
    const detectedFields = document.getElementById('detectedFields');
    const noFieldsMessage = document.getElementById('noFieldsMessage');
    const templateField = document.getElementById('templateField');
    // Enhanced chemical label field patterns with better matching
    const FIELD_PATTERNS = {
        productName: /(product|item|name|chemical)\s*[::]\s*/i,
        manufacturer: /(manufacturer|producer|supplier|made by|company)\s*[::]\s*/i,
        casNumber: /(cas\s*(no|number|#)|chemical\s*abstracts\s*service)\s*[::]\s*/i,
        unNumber: /(un\s*(no|number|#)|un\s*id|transport\s*id)\s*[::]\s*/i,
        hazardSymbols: /(ghs|hazard|warning|symbol|pictogram|danger)\s*[::]\s*/i,
        concentration: /(concentration|purity|grade|assay|content)\s*[::]\s*/i,
        batchNumber: /(batch\s*(no|number|#)|lot\s*(no|number|#)|serial)\s*[::]\s*/i,
        expiryDate: /(expiry|expiration|best\s*before|use\s*by|valid\s*until)\s*[::]\s*/i,
        hazardStatements: /(hazard\s*statement|h\s*phrase|risk\s*phrase)\s*[::]\s*/i,
        precautionaryStatements: /(precautionary\s*statement|p\s*phrase|safety\s*phrase)\s*[::]\s*/i,
        signalWord: /(signal\s*word|warning|danger|caution)\s*[::]\s*/i,
        molecularFormula: /(molecular\s*formula|formula)\s*[::]\s*/i,
        molecularWeight: /(molecular\s*weight|m\.w\.|mw)\s*[::]\s*/i,
        density: /(density|specific\s*gravity)\s*[::]\s*/i,
        storageConditions: /(storage|store)\s*[::]\s*/i
    };
// Event listeners for drag and drop
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        dropZone.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, unhighlight, false);
    });

    function highlight() {
        dropZone.classList.add('drag-over');
    }

    function unhighlight() {
        dropZone.classList.remove('drag-over');
    }

    dropZone.addEventListener('drop', handleDrop, false);
    fileInput.addEventListener('change', handleFiles, false);

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        handleFiles({target: {files}});
    }

    function handleFiles(e) {
        const files = e.target.files;
        if (!files.length) return;

        const file = files[0];
        if (!file.type.match('image.*')) {
            alert('Please upload an image file');
            return;
        }

        const reader = new FileReader();
        reader.onload = function(e) {
            imagePreview.src = e.target.result;
            imagePreview.onload = function() {
                imagePreviewContainer.classList.remove('hidden');
                dropZone.classList.add('hidden');
                
                // Set canvas dimensions to match the image
                annotationCanvas.width = imagePreview.width;
                annotationCanvas.height = imagePreview.height;
                
                analyzeBtn.disabled = false;
            };
        };
        reader.readAsDataURL(file);
    }
    // Analyze button click handler
    analyzeBtn.addEventListener('click', async function() {
        analyzeBtn.disabled = true;
        analyzeBtn.textContent = 'Analyzing...';
        
        try {
            // Get the image data
            const imageData = await getImageData();
            
            // Call Google Cloud Vision API (or your preferred vision service)
            const results = await analyzeImageWithVisionAPI(imageData);
            
            // Process the results
            processVisionResults(results);
            
            // Enable export button
            exportBtn.disabled = false;
        } catch (error) {
            console.error('Analysis error:', error);
            alert('Analysis failed. Please try again.');
        } finally {
            analyzeBtn.disabled = false;
            analyzeBtn.textContent = 'Analyze Label';
        }
    });

    // Export button click handler
    exportBtn.addEventListener('click', function() {
        exportData();
    });

    // Get image data as base64
    async function getImageData() {
        return new Promise((resolve) => {
            const reader = new FileReader();
            reader.onload = function(e) {
                // Remove data URL prefix
                const base64Data = e.target.result.split(',')[1];
                resolve(base64Data);
            };
            reader.readAsDataURL(fileInput.files[0]);
        });
    }
    // Analyze image with OCR.space API
    async function analyzeImageWithVisionAPI(imageData) {
        const apiKey = 'K87299170688957'; // Free public demo key (rate limited)
        const apiUrl = 'https://api.ocr.space/parse/image';
        
        try {
            const formData = new FormData();
            formData.append('base64Image', `data:image/jpeg;base64,${imageData}`);
            formData.append('language', 'eng');
            formData.append('isOverlayRequired', 'true');
            formData.append('OCREngine', '2'); // Engine 2 is more accurate
            
            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'apikey': apiKey
                },
                body: formData
            });
            
            const data = await response.json();
            
            if (!data.IsErroredOnProcessing) {
                // Format response to match our expected structure
                const parsedText = data.ParsedResults[0].ParsedText;
                const textOverlay = data.ParsedResults[0].TextOverlay;
                
                // Get bounding box of all text
                let minX = Infinity, minY = Infinity, maxX = 0, maxY = 0;
                textOverlay.Lines.forEach(line => {
                    line.Words.forEach(word => {
                        minX = Math.min(minX, word.Left);
                        minY = Math.min(minY, word.Top);
                        maxX = Math.max(maxX, word.Left + word.Width);
                        maxY = Math.max(maxY, word.Top + word.Height);
                    });
                });
                
                return {
                    textAnnotations: [{
                        description: parsedText,
                        boundingPoly: {
                            vertices: [
                                {x: minX, y: minY},
                                {x: maxX, y: minY},
                                {x: maxX, y: maxY},
                                {x: minX, y: maxY}
                            ]
                        }
                    }]
                };
            } else {
                throw new Error(data.ErrorMessage || 'OCR processing failed');
            }
        } catch (error) {
            console.error('OCR API error:', error);
            throw error;
        }
    }
    // Process vision API results
    function processVisionResults(results) {
        // Clear previous fields
        detectedFields.innerHTML = '';
        noFieldsMessage.classList.add('hidden');
        
        // Extract full text
        const fullText = results.textAnnotations[0].description;
        
        // Split into lines and process each line
        const lines = fullText.split('\n');
        const detectedFieldsMap = new Map();
        
        // Improved text processing with better pattern matching
        lines.forEach(line => {
            if (!line.trim()) return;
            
            // Try to match against known field patterns
            let matched = false;
            for (const [fieldType, pattern] of Object.entries(FIELD_PATTERNS)) {
                const match = line.match(pattern);
                if (match) {
                    // Extract the field value (text after the label)
                    let value = line.substring(match.index + match[0].length).trim();
                    
                    // Clean up value (remove special characters at start/end)
                    value = value.replace(/^[^a-zA-Z0-9]+/, '').replace(/[^a-zA-Z0-9]+$/, '');
                    
                    if (value) {
                        detectedFieldsMap.set(fieldType, {
                            label: match[0].trim(),
                            value: value
                        });
                        matched = true;
                        break;
                    }
                }
            }
            
            // If no field label matched, check if it might be a value continuing from previous line
            if (!matched && detectedFieldsMap.size > 0) {
                const lastEntry = Array.from(detectedFieldsMap.entries()).pop();
                const lastValue = lastEntry[1].value;
                
                // If previous value ends with incomplete punctuation or looks truncated
                if (!/[.!?]$/.test(lastValue) || lastValue.length < 30) {
                    detectedFieldsMap.set(lastEntry[0], {
                        ...lastEntry[1],
                        value: `${lastValue} ${line.trim()}`
                    });
                }
            }
            
            // Check for GHS symbols (improved matching)
            const ghsMatch = line.match(/(corrosive|flammable|toxic|health hazard|environmental hazard|explosive|oxidizing|irritant|gas under pressure|acute toxicity)/i);
            if (ghsMatch) {
                const symbol = ghsMatch[0].toLowerCase().replace(/\s+/g, '_');
                detectedFieldsMap.set(`ghs_${symbol}`, {
                    label: 'GHS Symbol',
                    value: ghsMatch[0]
                });
            }
        });
// Add detected fields to UI
        detectedFieldsMap.forEach((fieldData, fieldName) => {
            addDetectedField(fieldName, fieldData.value);
        });
        
        // Draw bounding boxes (simplified for demo)
        drawBoundingBoxes(results.textAnnotations[0].boundingPoly.vertices);
    }
function addDetectedField(name, value) {
        const fieldElement = templateField.cloneNode(true);
        fieldElement.classList.remove('hidden');
        fieldElement.querySelector('#fieldName').textContent = name;
        fieldElement.querySelector('#fieldValue').textContent = value;
        fieldElement.removeAttribute('id');
        detectedFields.appendChild(fieldElement);
    }
    function drawBoundingBoxes(vertices) {
        const ctx = annotationCanvas.getContext('2d');
        ctx.clearRect(0, 0, annotationCanvas.width, annotationCanvas.height);
        
        // Calculate bounding box dimensions
        const minX = Math.min(...vertices.map(v => v.x || 0));
        const maxX = Math.max(...vertices.map(v => v.x || 0));
        const minY = Math.min(...vertices.map(v => v.y || 0));
        const maxY = Math.max(...vertices.map(v => v.y || 0));
        const width = maxX - minX;
        const height = maxY - minY;
        
        // Draw main bounding box
        ctx.strokeStyle = '#818cf8';
        ctx.lineWidth = 2;
        ctx.strokeRect(minX, minY, width, height);
        
        // Fill with semi-transparent color
        ctx.fillStyle = 'rgba(99, 102, 241, 0.1)';
        ctx.fillRect(minX, minY, width, height);
        
        // Draw label
        ctx.fillStyle = '#4b5563';
        ctx.fillRect(minX, minY - 20, 100, 20);
        ctx.fillStyle = 'white';
        ctx.font = '12px sans-serif';
        ctx.fillText('Detected Label', minX + 5, minY - 5);
    }
    function exportData() {
        const fields = [];
        document.querySelectorAll('#detectedFields > div').forEach(field => {
            const name = field.querySelector('span').textContent;
            const value = field.querySelector('div').textContent;
            fields.push({
                field: name,
                value: value,
                confidence: 0.95, // Would come from API in real implementation
                timestamp: new Date().toISOString()
            });
        });
        
        // Create more comprehensive JSON structure
        const exportData = {
            metadata: {
                analyzedAt: new Date().toISOString(),
                imageDimensions: {
                    width: imagePreview.naturalWidth,
                    height: imagePreview.naturalHeight
                },
                version: '1.0'
            },
            fields: fields
        };
        
        // Create JSON download
        const dataStr = JSON.stringify(exportData, null, 2);
        const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);
        
        const exportFileDefaultName = `chemical_label_${Date.now()}.json`;
        const linkElement = document.createElement('a');
        linkElement.setAttribute('href', dataUri);
        linkElement.setAttribute('download', exportFileDefaultName);
        linkElement.click();
    }
// Initialize feather icons
    feather.replace();
});