-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuploader.js
More file actions
234 lines (203 loc) · 6.5 KB
/
uploader.js
File metadata and controls
234 lines (203 loc) · 6.5 KB
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
let images = []; // [{ id, file, name, date, url, el, description }]
const thumbGridElRef = { current: null };
// OCR worker (lazy-init)
let ocrWorker = null;
async function ensureOCRWorker() {
if (ocrWorker) return ocrWorker;
const { createWorker } = await import("tesseract.js");
ocrWorker = await createWorker({
logger: () => {} // quiet
});
// Try Portuguese first, fallback to English
try {
await ocrWorker.loadLanguage("por");
await ocrWorker.initialize("por");
} catch {
await ocrWorker.loadLanguage("eng");
await ocrWorker.initialize("eng");
}
return ocrWorker;
}
function createThumb(item) {
const wrap = document.createElement("div");
wrap.className = "thumb";
wrap.dataset.id = item.id;
const img = document.createElement("img");
img.alt = item.name;
img.loading = "lazy";
img.src = item.url;
const btn = document.createElement("button");
btn.className = "remove";
btn.type = "button";
btn.title = "Remover";
btn.textContent = "×";
btn.addEventListener("click", () => {
removeImage(item.id);
});
const ocrBadge = document.createElement("span");
ocrBadge.className = "thumb-ocr";
ocrBadge.textContent = "OCR…";
ocrBadge.style.display = item._ocrPending ? "inline-block" : "none";
const desc = document.createElement("textarea");
desc.className = "thumb-desc";
desc.placeholder = "Descrição (nome, características, preço...)";
desc.value = item.description || "";
desc.addEventListener("input", (e) => {
item.description = e.target.value;
});
const mediaWrap = document.createElement("div");
mediaWrap.className = "thumb-media";
mediaWrap.appendChild(img);
mediaWrap.appendChild(btn);
mediaWrap.appendChild(ocrBadge);
wrap.appendChild(mediaWrap);
wrap.appendChild(desc);
return wrap;
}
function refreshGrid() {
const grid = thumbGridElRef.current;
if (!grid) return;
grid.innerHTML = "";
for (const item of images) {
const el = createThumb(item);
item.el = el;
grid.appendChild(el);
}
}
function extractProductDescription(text) {
const cleaned = (text || "").replace(/\s+/g, " ").trim();
if (!cleaned) return "";
// Split into lines/sentences
const lines = cleaned.split(/(?<=\.|\n)|(?=[•\-–])|\n/g).map(s => s.trim()).filter(Boolean);
// Heuristic: product name candidates - short lines with title case or all caps
const candidates = lines
.map(s => s.replace(/[•\-–]+/g, "").trim())
.filter(s => s.length >= 3 && s.length <= 60);
let name = candidates.find(s => /^[A-ZÁÀÂÃÉÊÍÓÔÕÚÇ0-9][A-Za-zÁ-ú0-9\s\-/&]+$/.test(s)) || candidates[0] || "";
// Extract attributes like weight/size
const attrMatch = cleaned.match(/(\d+([.,]\d+)?\s?(ml|l|g|kg|un|cm|mm))/i);
const attrs = attrMatch ? attrMatch[0] : "";
// Price if present
const price = (cleaned.match(/R\$\s?\d{1,3}(\.\d{3})*,\d{2}/) || [])[0] || "";
let desc = name;
if (attrs) desc += ` • ${attrs}`;
if (price) desc += ` • ${price}`;
return desc.trim();
}
async function runOCR(item) {
try {
item._ocrPending = true;
if (item.el) {
const badge = item.el.querySelector(".thumb-ocr");
if (badge) badge.style.display = "inline-block";
}
const worker = await ensureOCRWorker();
// Downscale for OCR for performance
const imgBitmap = await createImageBitmap(item.file);
const maxDim = 1200;
const scale = Math.min(1, maxDim / Math.max(imgBitmap.width, imgBitmap.height));
const w = Math.max(1, Math.round(imgBitmap.width * scale));
const h = Math.max(1, Math.round(imgBitmap.height * scale));
const canvas = document.createElement("canvas");
canvas.width = w; canvas.height = h;
const ctx = canvas.getContext("2d");
ctx.drawImage(imgBitmap, 0, 0, w, h);
const { data: { text } } = await worker.recognize(canvas);
const suggestion = extractProductDescription(text);
if (suggestion && !item.description) {
item.description = suggestion;
}
} catch {
// ignore OCR errors
} finally {
item._ocrPending = false;
if (item.el) {
const badge = item.el.querySelector(".thumb-ocr");
if (badge) badge.style.display = "none";
const ta = item.el.querySelector(".thumb-desc");
if (ta && ta.value !== item.description) {
ta.value = item.description || "";
}
}
}
}
function addFiles(fileList) {
const files = Array.from(fileList || []).filter(f => /image\/(png|jpe?g)/i.test(f.type));
for (const file of files) {
const id = crypto.randomUUID();
const url = URL.createObjectURL(file);
const item = {
id,
file,
name: file.name,
date: file.lastModified || Date.now(),
url,
el: null,
description: "",
_ocrPending: false
};
images.push(item);
// Fire-and-forget OCR (user can edit later)
runOCR(item);
}
refreshGrid();
}
function removeImage(id) {
const idx = images.findIndex(i => i.id === id);
if (idx >= 0) {
URL.revokeObjectURL(images[idx].url);
images.splice(idx, 1);
refreshGrid();
}
}
export function initUploader(fileInputEl, dropZoneEl, thumbGridEl) {
thumbGridElRef.current = thumbGridEl;
fileInputEl.addEventListener("change", (e) => {
addFiles(e.target.files);
fileInputEl.value = "";
});
// Mobile-friendly click to open
dropZoneEl.addEventListener("click", () => fileInputEl.click());
// Drag and drop
["dragenter", "dragover"].forEach(evt =>
dropZoneEl.addEventListener(evt, (e) => {
e.preventDefault();
e.stopPropagation();
dropZoneEl.classList.add("dragover");
})
);
["dragleave", "drop"].forEach(evt =>
dropZoneEl.addEventListener(evt, (e) => {
e.preventDefault();
e.stopPropagation();
dropZoneEl.classList.remove("dragover");
})
);
dropZoneEl.addEventListener("drop", (e) => {
addFiles(e.dataTransfer.files);
});
}
export function getImages() {
// Sync order from DOM
const grid = thumbGridElRef.current;
if (!grid) return images.slice();
const order = Array.from(grid.children).map(el => el.dataset.id);
const map = new Map(images.map(i => [i.id, i]));
const sorted = order.map(id => map.get(id)).filter(Boolean);
return sorted;
}
export function clearImages() {
for (const item of images) {
URL.revokeObjectURL(item.url);
}
images = [];
refreshGrid();
}
export function sortByName() {
images.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }));
refreshGrid();
}
export function sortByDate() {
images.sort((a, b) => a.date - b.date);
refreshGrid();
}