Compare commits
10 Commits
a3a85dfff1
...
86d9b351b1
| Author | SHA1 | Date | |
|---|---|---|---|
| 86d9b351b1 | |||
| 7f6ca4c3de | |||
| e5e75167f0 | |||
| 4ea8eb3805 | |||
| 7e2bbfcca2 | |||
| 8fe75db238 | |||
| 30efdf1a79 | |||
| 6255ebfbea | |||
| 205faeede2 | |||
| 3ff71b0ef9 |
@@ -0,0 +1,2 @@
|
|||||||
|
.claude/
|
||||||
|
.DS_Store
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
FROM nginx:alpine
|
||||||
|
|
||||||
|
# Copier les fichiers statiques
|
||||||
|
COPY . /usr/share/nginx/html/
|
||||||
|
|
||||||
|
# Supprimer les fichiers non destinés au navigateur
|
||||||
|
RUN rm -rf /usr/share/nginx/html/.git \
|
||||||
|
/usr/share/nginx/html/.claude \
|
||||||
|
/usr/share/nginx/html/Dockerfile \
|
||||||
|
/usr/share/nginx/html/docker-compose.yml \
|
||||||
|
/usr/share/nginx/html/.gitignore
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
services:
|
||||||
|
app:
|
||||||
|
build: .
|
||||||
|
image: convertisseur-images:latest
|
||||||
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- web
|
||||||
|
|
||||||
|
networks:
|
||||||
|
web:
|
||||||
|
external: true
|
||||||
+375
-52
@@ -4,90 +4,413 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Convertisseur Images — Matériaux Destock</title>
|
<title>Convertisseur Images — Matériaux Destock</title>
|
||||||
|
<!-- Import map : résout les dépendances bare-specifier de @imgly/background-removal -->
|
||||||
|
<script type="importmap">
|
||||||
|
{
|
||||||
|
"imports": {
|
||||||
|
"onnxruntime-web": "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.21.0/dist/ort.all.min.mjs",
|
||||||
|
"onnxruntime-web/webgpu": "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.21.0/dist/ort.webgpu.min.mjs",
|
||||||
|
"onnxruntime-web/wasm": "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.21.0/dist/ort.wasm.min.mjs"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
<script src="https://cdn.tailwindcss.com"></script>
|
<script src="https://cdn.tailwindcss.com"></script>
|
||||||
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
|
|
||||||
<script src="https://cdn.jsdelivr.net/npm/heic2any@0.0.4/dist/heic2any.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/heic2any@0.0.4/dist/heic2any.min.js"></script>
|
||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
|
||||||
<link rel="stylesheet" href="css/app.css" />
|
<link rel="stylesheet" href="css/app.css" />
|
||||||
</head>
|
</head>
|
||||||
<body class="bg-gray-50 min-h-screen font-sans">
|
<body class="bg-gray-50 min-h-screen font-sans pb-24">
|
||||||
<div x-data="imageApp()" class="max-w-6xl mx-auto px-4 py-8">
|
<div x-data="imageApp" class="max-w-6xl mx-auto px-4 py-8">
|
||||||
<h1 class="text-2xl font-bold text-gray-800 mb-6">
|
|
||||||
Convertisseur Images Shopify
|
|
||||||
</h1>
|
|
||||||
|
|
||||||
<!-- Zone 1: Upload -->
|
<!-- En-tête -->
|
||||||
<div id="upload-zone" class="mb-8">
|
<div class="mb-8">
|
||||||
<p class="text-gray-500 text-center">Zone d'upload (à construire)</p>
|
<h1 class="text-2xl font-bold text-gray-800">Convertisseur Images Shopify</h1>
|
||||||
|
<p class="text-gray-500 text-sm mt-1">HEIC → JPG · Détourage IA · Export ZIP</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Zone 2: Grille -->
|
<!-- ── Zone 1 : Upload ─────────────────────────────────────── -->
|
||||||
<div id="grid-zone" class="mb-8">
|
<div class="mb-8">
|
||||||
<p class="text-gray-500 text-center">Grille d'images (à construire)</p>
|
<!-- Info modèle IA -->
|
||||||
|
<div class="flex items-center gap-2 mb-4 text-xs text-blue-600 bg-blue-50 border border-blue-200 rounded-lg px-3 py-2">
|
||||||
|
<span>🤖</span>
|
||||||
|
<span>Détourage par IA (WebAssembly) — Le modèle (~40 Mo) se télécharge automatiquement au premier traitement et reste en cache.</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Zone 3: Export -->
|
<!-- Zone de dépôt -->
|
||||||
<div id="export-zone">
|
<div
|
||||||
<p class="text-gray-500 text-center">Zone d'export (à construire)</p>
|
class="border-2 border-dashed border-gray-300 rounded-xl p-12 text-center cursor-pointer hover:border-blue-400 transition-colors"
|
||||||
|
@dragover.prevent="$el.classList.add('drop-active')"
|
||||||
|
@dragleave="$el.classList.remove('drop-active')"
|
||||||
|
@drop.prevent="$el.classList.remove('drop-active'); handleFiles($event.dataTransfer.files)"
|
||||||
|
@click="$refs.fileInput.click()"
|
||||||
|
>
|
||||||
|
<svg class="mx-auto w-12 h-12 text-gray-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
|
||||||
|
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
|
||||||
|
</svg>
|
||||||
|
<p class="text-gray-600 font-medium">Glissez vos fichiers ici</p>
|
||||||
|
<p class="text-gray-400 text-sm mt-1">ZIP (dossiers produits) · HEIC · HEIF — ou cliquez pour parcourir</p>
|
||||||
|
<input type="file" x-ref="fileInput"
|
||||||
|
accept=".heic,.heif,.zip,image/heic,image/heif"
|
||||||
|
multiple class="hidden"
|
||||||
|
@change="handleFiles($event.target.files)" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- ── Zone 2 : Grille ─────────────────────────────────────── -->
|
||||||
|
<div class="mb-8">
|
||||||
|
<template x-if="files.length > 0">
|
||||||
|
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
|
<template x-for="file in files" :key="file.id">
|
||||||
|
<div class="image-card bg-white rounded-xl border border-gray-200 overflow-hidden">
|
||||||
|
|
||||||
|
<!-- En-tête de carte -->
|
||||||
|
<div class="px-4 py-3 border-b border-gray-100 flex items-center justify-between">
|
||||||
|
<div class="min-w-0 flex-1 mr-2">
|
||||||
|
<template x-if="file.folder">
|
||||||
|
<span class="text-xs text-blue-400 block truncate" x-text="'📁 ' + file.folder"></span>
|
||||||
|
</template>
|
||||||
|
<span class="text-sm font-medium text-gray-700 truncate block" x-text="file.name"></span>
|
||||||
|
</div>
|
||||||
|
<span class="text-xs px-2 py-1 rounded-full ml-2 shrink-0"
|
||||||
|
:class="{
|
||||||
|
'bg-yellow-100 text-yellow-700': ['pending','converting','processing'].includes(file.status),
|
||||||
|
'bg-green-100 text-green-700': file.status === 'done',
|
||||||
|
'bg-red-100 text-red-700': file.status === 'error',
|
||||||
|
}"
|
||||||
|
x-text="{
|
||||||
|
pending: '⏳ En attente',
|
||||||
|
converting: '⏳ Conversion…',
|
||||||
|
processing: '⏳ Détourage IA…',
|
||||||
|
done: '✅ OK',
|
||||||
|
error: '❌ Erreur',
|
||||||
|
}[file.status]">
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Progression IA (visible pendant le détourage) -->
|
||||||
|
<template x-if="file.status === 'processing' && file.progressLabel">
|
||||||
|
<div class="px-4 py-2 bg-blue-50 border-b border-blue-100">
|
||||||
|
<div class="flex items-center justify-between text-xs text-blue-700 mb-1">
|
||||||
|
<span x-text="file.progressLabel"></span>
|
||||||
|
<span x-text="file.progressPct + '%'"></span>
|
||||||
|
</div>
|
||||||
|
<div class="w-full bg-blue-200 rounded-full h-1.5">
|
||||||
|
<div class="bg-blue-500 h-1.5 rounded-full transition-all duration-200"
|
||||||
|
:style="'width:' + file.progressPct + '%'"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Message d'erreur -->
|
||||||
|
<template x-if="file.status === 'error'">
|
||||||
|
<div class="px-4 py-3 text-sm text-red-600 bg-red-50" x-text="file.error"></div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Avant / Après -->
|
||||||
|
<div class="p-3 grid grid-cols-2 gap-2">
|
||||||
|
<div>
|
||||||
|
<p class="text-xs text-gray-400 text-center mb-1">Avant</p>
|
||||||
|
<div class="bg-gray-100 rounded overflow-hidden aspect-square flex items-center justify-center">
|
||||||
|
<template x-if="file.originalUrl">
|
||||||
|
<img :src="file.originalUrl"
|
||||||
|
class="object-contain w-full h-full cursor-zoom-in"
|
||||||
|
@click="modalUrl = file.originalUrl; modalTitle = file.name + ' — Avant'; modalOpen = true" />
|
||||||
|
</template>
|
||||||
|
<template x-if="!file.originalUrl">
|
||||||
|
<span class="text-gray-300 text-xs">—</span>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p class="text-xs text-gray-400 text-center mb-1">Après</p>
|
||||||
|
<div class="bg-gray-100 rounded overflow-hidden aspect-square flex items-center justify-center">
|
||||||
|
<template x-if="file.processedUrl">
|
||||||
|
<img :src="file.processedUrl"
|
||||||
|
class="object-contain w-full h-full cursor-zoom-in transition-transform duration-200"
|
||||||
|
:style="file.rotation ? 'transform:rotate(' + file.rotation + 'deg)' : ''"
|
||||||
|
@click="modalUrl = file.processedUrl; modalTitle = file.name + ' — Après'; modalRotation = file.rotation; modalOpen = true" />
|
||||||
|
</template>
|
||||||
|
<template x-if="!file.processedUrl">
|
||||||
|
<span class="text-gray-300 text-xs">—</span>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Contrôles -->
|
||||||
|
<template x-if="file.status === 'done' || file.status === 'error'">
|
||||||
|
<div class="px-3 pb-3 border-t border-gray-100 pt-2 space-y-2">
|
||||||
|
<!-- Rotation -->
|
||||||
|
<template x-if="file.status === 'done'">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<span class="text-xs text-gray-500">Rotation</span>
|
||||||
|
<div class="flex items-center gap-1">
|
||||||
|
<button @click="file.rotation = (file.rotation - 90 + 360) % 360"
|
||||||
|
class="w-7 h-7 flex items-center justify-center rounded bg-gray-100 hover:bg-gray-200 text-gray-600 text-sm transition-colors"
|
||||||
|
title="Rotation -90°">↺</button>
|
||||||
|
<span class="text-xs text-gray-500 w-8 text-center" x-text="file.rotation + '°'"></span>
|
||||||
|
<button @click="file.rotation = (file.rotation + 90) % 360"
|
||||||
|
class="w-7 h-7 flex items-center justify-center rounded bg-gray-100 hover:bg-gray-200 text-gray-600 text-sm transition-colors"
|
||||||
|
title="Rotation +90°">↻</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<!-- Slider récupération des bords -->
|
||||||
|
<div>
|
||||||
|
<div class="flex items-center justify-between text-xs text-gray-500 mb-1">
|
||||||
|
<label>Récupération des bords</label>
|
||||||
|
<span x-text="file.feather + ' px'"></span>
|
||||||
|
</div>
|
||||||
|
<input type="range" min="0" max="5" step="1"
|
||||||
|
x-model.number="file.feather"
|
||||||
|
class="w-full h-1.5 accent-blue-500 cursor-pointer" />
|
||||||
|
<div class="flex justify-between text-xs text-gray-300 mt-0.5">
|
||||||
|
<span>Strict</span><span>Doux</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
@click="reprocess(file)"
|
||||||
|
:disabled="file.status === 'processing'"
|
||||||
|
class="w-full text-xs bg-blue-50 hover:bg-blue-100 disabled:opacity-50 text-blue-700 border border-blue-200 rounded-lg py-1.5 px-2 transition-colors"
|
||||||
|
>
|
||||||
|
🔄 Retraiter
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ── Zone 3 : Export ─────────────────────────────────────── -->
|
||||||
|
<template x-if="files.length > 0">
|
||||||
|
<div class="fixed bottom-4 left-0 right-0 flex justify-center z-50">
|
||||||
|
<div class="bg-white border border-gray-200 rounded-2xl shadow-lg px-6 py-4 flex items-center gap-6">
|
||||||
|
<span class="text-sm text-gray-600">
|
||||||
|
<span class="font-semibold text-gray-800" x-text="readyCount"></span>
|
||||||
|
/
|
||||||
|
<span x-text="files.length"></span>
|
||||||
|
images prêtes
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
@click="downloadAll()"
|
||||||
|
:disabled="readyCount === 0"
|
||||||
|
class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed text-white font-medium px-5 py-2 rounded-xl transition-colors text-sm"
|
||||||
|
>
|
||||||
|
⬇️ Télécharger tout en ZIP
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- ── Modal plein écran ─────────────────────────────────── -->
|
||||||
|
<div
|
||||||
|
x-show="modalOpen"
|
||||||
|
x-transition:enter="transition ease-out duration-150"
|
||||||
|
x-transition:enter-start="opacity-0"
|
||||||
|
x-transition:enter-end="opacity-100"
|
||||||
|
x-transition:leave="transition ease-in duration-100"
|
||||||
|
x-transition:leave-start="opacity-100"
|
||||||
|
x-transition:leave-end="opacity-0"
|
||||||
|
class="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4"
|
||||||
|
@click.self="modalOpen = false"
|
||||||
|
@keydown.escape.window="modalOpen = false"
|
||||||
|
style="display:none"
|
||||||
|
>
|
||||||
|
<div class="relative">
|
||||||
|
<button
|
||||||
|
@click="modalOpen = false"
|
||||||
|
class="absolute -top-10 right-0 text-white text-3xl font-light leading-none hover:text-gray-300 transition-colors"
|
||||||
|
aria-label="Fermer"
|
||||||
|
>✕</button>
|
||||||
|
<p class="absolute -top-8 left-0 text-white text-sm font-medium truncate max-w-sm" x-text="modalTitle"></p>
|
||||||
|
<img :src="modalUrl" alt=""
|
||||||
|
class="object-contain rounded-lg shadow-2xl bg-white transition-transform duration-200"
|
||||||
|
style="max-width:85vmin; max-height:85vmin;"
|
||||||
|
:style="modalRotation ? 'transform:rotate(' + modalRotation + 'deg); max-width:85vmin; max-height:85vmin;' : 'max-width:85vmin; max-height:85vmin;'" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div><!-- fin x-data -->
|
||||||
|
|
||||||
<script type="module">
|
<script type="module">
|
||||||
|
import Alpine from 'https://cdn.jsdelivr.net/npm/alpinejs@3/dist/module.esm.min.js';
|
||||||
import { convertHeicToJpeg } from './js/heicConverter.js';
|
import { convertHeicToJpeg } from './js/heicConverter.js';
|
||||||
import { removeBackground, pickColorFromCanvas } from './js/bgRemover.js';
|
import { removeBackground } from './js/bgRemover.js';
|
||||||
import { processBatch } from './js/imageProcessor.js';
|
import { processBatch } from './js/imageProcessor.js';
|
||||||
import { downloadAllAsZip } from './js/zipExporter.js';
|
import { downloadAllAsZip } from './js/zipExporter.js';
|
||||||
|
import { readImagesFromZip } from './js/zipImporter.js';
|
||||||
|
import { rotateBlob } from './js/imageRotator.js';
|
||||||
|
|
||||||
// Helper: charge un Blob comme Image sur un Canvas, applique removeBackground, retourne un Blob JPEG
|
// ── App Alpine.js ──────────────────────────────────────────────
|
||||||
async function processImage(blob, seedColor, tolerance) {
|
Alpine.data('imageApp', () => ({
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const img = new Image();
|
|
||||||
img.onload = () => {
|
|
||||||
const canvas = document.createElement('canvas');
|
|
||||||
canvas.width = img.width;
|
|
||||||
canvas.height = img.height;
|
|
||||||
canvas.getContext('2d').drawImage(img, 0, 0);
|
|
||||||
try {
|
|
||||||
removeBackground(canvas, seedColor ?? null, tolerance);
|
|
||||||
canvas.toBlob(b => {
|
|
||||||
URL.revokeObjectURL(img.src);
|
|
||||||
b ? resolve(b) : reject(new Error('canvas.toBlob a retourné null'));
|
|
||||||
}, 'image/jpeg', 0.92);
|
|
||||||
} catch (e) {
|
|
||||||
reject(e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
img.onerror = () => reject(new Error("Impossible de charger l'image"));
|
|
||||||
img.src = URL.createObjectURL(blob);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
window.imageApp = function () {
|
|
||||||
return {
|
|
||||||
files: [],
|
files: [],
|
||||||
globalTolerance: 30,
|
modalOpen: false,
|
||||||
|
modalUrl: null,
|
||||||
|
modalTitle: '',
|
||||||
|
modalRotation: 0,
|
||||||
|
|
||||||
get readyCount() {
|
get readyCount() {
|
||||||
return this.files.filter(f => f.status === 'done').length;
|
return this.files.filter(f => f.status === 'done').length;
|
||||||
},
|
},
|
||||||
|
|
||||||
async handleFiles(fileList) {
|
async handleFiles(fileList) {
|
||||||
// TODO: Tâche 7
|
const heicExts = ['.heic', '.heif'];
|
||||||
|
const allFiles = Array.from(fileList);
|
||||||
|
|
||||||
|
const zipFiles = allFiles.filter(f => f.name.toLowerCase().endsWith('.zip'));
|
||||||
|
const heicFiles = allFiles.filter(f => heicExts.some(ext => f.name.toLowerCase().endsWith(ext)));
|
||||||
|
const skipped = allFiles.filter(f =>
|
||||||
|
!f.name.toLowerCase().endsWith('.zip') &&
|
||||||
|
!heicExts.some(ext => f.name.toLowerCase().endsWith(ext))
|
||||||
|
);
|
||||||
|
|
||||||
|
if (skipped.length > 0) {
|
||||||
|
alert(
|
||||||
|
`${skipped.length} fichier(s) ignoré(s) — seuls .heic, .heif et .zip sont acceptés.\n` +
|
||||||
|
`Ignorés : ${skipped.map(f => f.name).join(', ')}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Construire la liste unifiée de fichiers à traiter ──────
|
||||||
|
const newFiles = [];
|
||||||
|
|
||||||
|
// 1. Fichiers HEIC/HEIF déposés directement
|
||||||
|
for (const file of heicFiles) {
|
||||||
|
newFiles.push({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
name: file.name.replace(/\.[^.]+$/, ''),
|
||||||
|
folder: '',
|
||||||
|
isHeic: true,
|
||||||
|
status: 'pending',
|
||||||
|
originalFile: file,
|
||||||
|
originalBlob: null,
|
||||||
|
processedBlob: null,
|
||||||
|
originalUrl: null,
|
||||||
|
processedUrl: null,
|
||||||
|
progressLabel: '',
|
||||||
|
progressPct: 0,
|
||||||
|
feather: 2,
|
||||||
|
rotation: 0,
|
||||||
|
error: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Images extraites des ZIPs
|
||||||
|
for (const zipFile of zipFiles) {
|
||||||
|
let images;
|
||||||
|
try {
|
||||||
|
images = await readImagesFromZip(zipFile);
|
||||||
|
} catch (e) {
|
||||||
|
alert(`Erreur lors de la lecture du ZIP "${zipFile.name}" : ${e.message}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (images.length === 0) {
|
||||||
|
alert(`Aucune image trouvée dans "${zipFile.name}".`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const img of images) {
|
||||||
|
newFiles.push({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
name: img.name,
|
||||||
|
folder: img.folder,
|
||||||
|
isHeic: img.isHeic,
|
||||||
|
status: 'pending',
|
||||||
|
originalFile: null,
|
||||||
|
originalBlob: img.blob,
|
||||||
|
processedBlob: null,
|
||||||
|
originalUrl: img.isHeic ? null : URL.createObjectURL(img.blob),
|
||||||
|
processedUrl: null,
|
||||||
|
progressLabel: '',
|
||||||
|
progressPct: 0,
|
||||||
|
feather: 2,
|
||||||
|
rotation: 0,
|
||||||
|
error: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newFiles.length === 0) return;
|
||||||
|
this.files.push(...newFiles);
|
||||||
|
|
||||||
|
// ── Pipeline de traitement ─────────────────────────────────
|
||||||
|
await processBatch(newFiles, async (orig) => {
|
||||||
|
const f = this.files.find(x => x.id === orig.id);
|
||||||
|
if (!f) return;
|
||||||
|
|
||||||
|
// Étape 1 : HEIC → JPEG (uniquement pour les fichiers HEIC/HEIF)
|
||||||
|
if (f.isHeic) {
|
||||||
|
f.status = 'converting';
|
||||||
|
try {
|
||||||
|
const source = f.originalFile ?? f.originalBlob;
|
||||||
|
f.originalBlob = await convertHeicToJpeg(source);
|
||||||
|
f.originalUrl = URL.createObjectURL(f.originalBlob);
|
||||||
|
} catch (e) {
|
||||||
|
f.status = 'error';
|
||||||
|
f.error = `Conversion échouée : ${e.message}`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Étape 2 : détourage IA
|
||||||
|
f.status = 'processing';
|
||||||
|
f.progressLabel = 'Chargement modèle…';
|
||||||
|
f.progressPct = 0;
|
||||||
|
try {
|
||||||
|
f.processedBlob = await removeBackground(f.originalBlob, ({ key, percent }) => {
|
||||||
|
f.progressPct = percent;
|
||||||
|
f.progressLabel = key.includes('model') ? 'Téléchargement modèle IA…' : 'Détourage en cours…';
|
||||||
|
}, f.feather);
|
||||||
|
f.processedUrl = URL.createObjectURL(f.processedBlob);
|
||||||
|
f.status = 'done';
|
||||||
|
} catch (e) {
|
||||||
|
f.status = 'error';
|
||||||
|
f.error = `Détourage échoué : ${e.message}`;
|
||||||
|
}
|
||||||
|
}, 3);
|
||||||
},
|
},
|
||||||
|
|
||||||
async reprocess(file) {
|
async reprocess(file) {
|
||||||
// TODO: Tâche 8
|
if (!file.originalBlob) return;
|
||||||
},
|
file.status = 'processing';
|
||||||
|
file.error = null;
|
||||||
async startColorPick(file) {
|
file.progressLabel = 'Chargement modèle…';
|
||||||
// TODO: Tâche 8
|
file.progressPct = 0;
|
||||||
|
if (file.processedUrl) {
|
||||||
|
URL.revokeObjectURL(file.processedUrl);
|
||||||
|
file.processedUrl = null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
file.processedBlob = await removeBackground(file.originalBlob, ({ key, percent }) => {
|
||||||
|
file.progressPct = percent;
|
||||||
|
file.progressLabel = key.includes('model') ? 'Téléchargement modèle IA…' : 'Détourage en cours…';
|
||||||
|
}, file.feather);
|
||||||
|
file.processedUrl = URL.createObjectURL(file.processedBlob);
|
||||||
|
file.status = 'done';
|
||||||
|
} catch (e) {
|
||||||
|
file.status = 'error';
|
||||||
|
file.error = `Détourage échoué : ${e.message}`;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
async downloadAll() {
|
async downloadAll() {
|
||||||
// TODO: Tâche 9
|
const done = this.files.filter(f => f.status === 'done' && f.processedBlob);
|
||||||
|
if (done.length === 0) return;
|
||||||
|
const readyFiles = await Promise.all(
|
||||||
|
done.map(async f => ({
|
||||||
|
name: `${f.name}.jpg`,
|
||||||
|
blob: f.rotation ? await rotateBlob(f.processedBlob, f.rotation) : f.processedBlob,
|
||||||
|
folder: f.folder,
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
await downloadAllAsZip(readyFiles);
|
||||||
},
|
},
|
||||||
};
|
}));
|
||||||
};
|
|
||||||
|
Alpine.start();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+98
-15
@@ -1,18 +1,101 @@
|
|||||||
export function chebyshevDistance(c1, c2) {
|
/**
|
||||||
throw new Error('Not implemented');
|
* Suppression de fond par IA — @imgly/background-removal (WebAssembly).
|
||||||
|
* Le modèle est téléchargé depuis staticimgly.com au premier lancement.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const CDN_VERSION = '1.7.0';
|
||||||
|
const CDN = `https://cdn.jsdelivr.net/npm/@imgly/background-removal@${CDN_VERSION}/dist/`;
|
||||||
|
|
||||||
|
let _removeBg = null;
|
||||||
|
|
||||||
|
async function loadLib() {
|
||||||
|
if (_removeBg) return _removeBg;
|
||||||
|
const mod = await import(CDN + 'index.mjs');
|
||||||
|
_removeBg = mod.removeBackground;
|
||||||
|
return _removeBg;
|
||||||
}
|
}
|
||||||
export function createFloodFillMask(imageData, seedColor, tolerance) {
|
|
||||||
throw new Error('Not implemented');
|
/**
|
||||||
|
* Supprime le fond d'un Blob image via IA puis composite sur blanc.
|
||||||
|
* @param {Blob} blob — image source (JPEG)
|
||||||
|
* @param {function} [onProgress] — callback({ key, percent })
|
||||||
|
* @param {number} [feather=2] — récupération de bords en px (0 = strict, 5 = doux)
|
||||||
|
* @returns {Promise<Blob>} Blob JPEG fond blanc
|
||||||
|
*/
|
||||||
|
export async function removeBackground(blob, onProgress, feather = 2) {
|
||||||
|
const removeBg = await loadLib();
|
||||||
|
|
||||||
|
const pngBlob = await removeBg(blob, {
|
||||||
|
// publicPath omis → utilise staticimgly.com par défaut
|
||||||
|
output: {
|
||||||
|
format: 'image/png',
|
||||||
|
type: 'foreground',
|
||||||
|
quality: 1,
|
||||||
|
},
|
||||||
|
progress: (key, current, total) => {
|
||||||
|
if (onProgress && total > 0) {
|
||||||
|
onProgress({ key, percent: Math.round((current / total) * 100) });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return compositeOnWhite(pngBlob, feather);
|
||||||
}
|
}
|
||||||
export function applyMaskToImageData(imageData, mask, replacementColor) {
|
|
||||||
throw new Error('Not implemented');
|
/**
|
||||||
}
|
* Composite un PNG transparent sur fond blanc.
|
||||||
export function softEdges(imageData, mask) {
|
* Si feather > 0, dilate légèrement le contour du sujet (récupère les bords
|
||||||
throw new Error('Not implemented');
|
* que l'IA a pu couper trop agressivement).
|
||||||
}
|
* @param {Blob} pngBlob
|
||||||
export function removeBackground(canvas, seedColor, tolerance = 30) {
|
* @param {number} feather — rayon de dilation en pixels (0–5)
|
||||||
throw new Error('Not implemented');
|
* @returns {Promise<Blob>} JPEG fond blanc
|
||||||
}
|
*/
|
||||||
export async function pickColorFromCanvas(canvas) {
|
async function compositeOnWhite(pngBlob, feather) {
|
||||||
throw new Error('Not implemented');
|
const objectUrl = URL.createObjectURL(pngBlob);
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const img = new Image();
|
||||||
|
|
||||||
|
img.onload = () => {
|
||||||
|
const { width, height } = img;
|
||||||
|
|
||||||
|
// ── Canvas intermédiaire : premier plan avec bords optionnels ──
|
||||||
|
const fgCanvas = document.createElement('canvas');
|
||||||
|
fgCanvas.width = width;
|
||||||
|
fgCanvas.height = height;
|
||||||
|
const fgCtx = fgCanvas.getContext('2d');
|
||||||
|
|
||||||
|
// 1. Dessin net du premier plan
|
||||||
|
fgCtx.drawImage(img, 0, 0);
|
||||||
|
|
||||||
|
if (feather > 0) {
|
||||||
|
// 2. On dessine une version floutée DERRIÈRE le dessin net
|
||||||
|
// (destination-over = "derrière le contenu existant")
|
||||||
|
// → les zones transparentes proches des bords du sujet deviennent
|
||||||
|
// semi-transparentes, récupérant les détails coupés par l'IA.
|
||||||
|
fgCtx.globalCompositeOperation = 'destination-over';
|
||||||
|
fgCtx.filter = `blur(${feather}px)`;
|
||||||
|
fgCtx.drawImage(img, 0, 0);
|
||||||
|
fgCtx.filter = 'none';
|
||||||
|
fgCtx.globalCompositeOperation = 'source-over';
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Canvas final : fond blanc + premier plan ───────────────────
|
||||||
|
const out = document.createElement('canvas');
|
||||||
|
out.width = width;
|
||||||
|
out.height = height;
|
||||||
|
const ctx = out.getContext('2d');
|
||||||
|
ctx.fillStyle = '#ffffff';
|
||||||
|
ctx.fillRect(0, 0, width, height);
|
||||||
|
ctx.drawImage(fgCanvas, 0, 0);
|
||||||
|
|
||||||
|
URL.revokeObjectURL(objectUrl);
|
||||||
|
out.toBlob(b => {
|
||||||
|
b ? resolve(b) : reject(new Error('canvas.toBlob a retourné null'));
|
||||||
|
}, 'image/jpeg', 0.92);
|
||||||
|
};
|
||||||
|
|
||||||
|
img.onerror = () => reject(new Error('Impossible de charger le résultat IA'));
|
||||||
|
img.src = objectUrl;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+24
-11
@@ -1,29 +1,42 @@
|
|||||||
/**
|
/**
|
||||||
* Convertit un fichier HEIC/HEIF en Blob JPEG.
|
* Convertit un fichier/blob HEIC/HEIF en Blob JPEG.
|
||||||
* @param {File} file
|
* @param {File|Blob} fileOrBlob — fichier HEIC/HEIF (File depuis l'input, ou Blob extrait d'un ZIP)
|
||||||
* @returns {Promise<Blob>}
|
* @returns {Promise<Blob>}
|
||||||
* @throws {TypeError} si l'entrée n'est pas un fichier HEIC/HEIF
|
* @throws {TypeError} si l'entrée n'est pas un Blob HEIC/HEIF
|
||||||
* @throws {Error} si la conversion échoue
|
* @throws {Error} si la conversion échoue ou dépasse 30s
|
||||||
*/
|
*/
|
||||||
export async function convertHeicToJpeg(file) {
|
export async function convertHeicToJpeg(fileOrBlob) {
|
||||||
if (!(file instanceof File)) {
|
if (!(fileOrBlob instanceof Blob)) {
|
||||||
throw new TypeError("L'entrée doit être un objet File");
|
throw new TypeError("L'entrée doit être un Blob ou un File");
|
||||||
}
|
}
|
||||||
// Certains iPhone envoient un type MIME vide pour les HEIC — on l'autorise
|
// Certains iPhone envoient un type MIME vide pour les HEIC — on l'autorise
|
||||||
const type = file.type.toLowerCase();
|
const type = fileOrBlob.type.toLowerCase();
|
||||||
if (type !== '' && !['image/heic', 'image/heif'].includes(type)) {
|
if (type !== '' && !['image/heic', 'image/heif'].includes(type)) {
|
||||||
throw new TypeError(`Format attendu : HEIC/HEIF. Reçu : ${file.type}`);
|
throw new TypeError(`Format attendu : HEIC/HEIF. Reçu : ${fileOrBlob.type || '(vide)'}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await heic2any({
|
const label = fileOrBlob instanceof File
|
||||||
blob: file,
|
? `${fileOrBlob.name} (${fileOrBlob.type || 'type vide'}, ${(fileOrBlob.size / 1024).toFixed(0)} Ko)`
|
||||||
|
: `blob HEIC (${(fileOrBlob.size / 1024).toFixed(0)} Ko)`;
|
||||||
|
console.log(`[heicConverter] Début conversion : ${label}`);
|
||||||
|
|
||||||
|
const timeout = new Promise((_, reject) =>
|
||||||
|
setTimeout(() => reject(new Error('Timeout : conversion > 120s. Vérifiez que le fichier est bien un HEIC valide.')), 120_000)
|
||||||
|
);
|
||||||
|
|
||||||
|
const conversion = heic2any({
|
||||||
|
blob: fileOrBlob,
|
||||||
toType: 'image/jpeg',
|
toType: 'image/jpeg',
|
||||||
quality: 0.92,
|
quality: 0.92,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const result = await Promise.race([conversion, timeout]);
|
||||||
|
|
||||||
const blob = Array.isArray(result) ? result[0] : result;
|
const blob = Array.isArray(result) ? result[0] : result;
|
||||||
if (!(blob instanceof Blob)) {
|
if (!(blob instanceof Blob)) {
|
||||||
throw new Error("heic2any n'a pas retourné un Blob");
|
throw new Error("heic2any n'a pas retourné un Blob");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log(`[heicConverter] ✅ Conversion réussie → ${(blob.size / 1024).toFixed(0)} Ko`);
|
||||||
return blob;
|
return blob;
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-1
@@ -1,3 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* Traite un tableau d'items avec au plus `concurrency` appels simultanés.
|
||||||
|
* @param {any[]} items
|
||||||
|
* @param {(item: any) => Promise<void>} processFn
|
||||||
|
* @param {number} concurrency
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function processBatch(items, processFn, concurrency = 3) {
|
export async function processBatch(items, processFn, concurrency = 3) {
|
||||||
throw new Error('Not implemented');
|
const queue = [...items];
|
||||||
|
const workers = Array.from({ length: concurrency }, async () => {
|
||||||
|
while (queue.length > 0) {
|
||||||
|
const item = queue.shift();
|
||||||
|
if (item !== undefined) await processFn(item);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await Promise.all(workers);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
/**
|
||||||
|
* Rotation d'un Blob image via Canvas.
|
||||||
|
* @param {Blob} blob — image source (JPEG)
|
||||||
|
* @param {number} degrees — angle de rotation en degrés (0, 90, 180, 270)
|
||||||
|
* @returns {Promise<Blob>} Blob JPEG pivoté, ou le blob original si degrees === 0
|
||||||
|
*/
|
||||||
|
export async function rotateBlob(blob, degrees) {
|
||||||
|
const norm = ((degrees % 360) + 360) % 360;
|
||||||
|
if (norm === 0) return blob;
|
||||||
|
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const img = new Image();
|
||||||
|
|
||||||
|
img.onload = () => {
|
||||||
|
// Pour 90° ou 270°, largeur et hauteur sont inversées
|
||||||
|
const swap = norm === 90 || norm === 270;
|
||||||
|
const w = swap ? img.naturalHeight : img.naturalWidth;
|
||||||
|
const h = swap ? img.naturalWidth : img.naturalHeight;
|
||||||
|
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
canvas.width = w;
|
||||||
|
canvas.height = h;
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
|
||||||
|
ctx.translate(w / 2, h / 2);
|
||||||
|
ctx.rotate((norm * Math.PI) / 180);
|
||||||
|
ctx.drawImage(img, -img.naturalWidth / 2, -img.naturalHeight / 2);
|
||||||
|
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
canvas.toBlob(
|
||||||
|
b => b ? resolve(b) : reject(new Error('rotateBlob : toBlob a retourné null')),
|
||||||
|
'image/jpeg',
|
||||||
|
0.92
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
img.onerror = () => {
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
reject(new Error('rotateBlob : impossible de charger le blob'));
|
||||||
|
};
|
||||||
|
|
||||||
|
img.src = url;
|
||||||
|
});
|
||||||
|
}
|
||||||
+22
-1
@@ -1,3 +1,24 @@
|
|||||||
|
/**
|
||||||
|
* Compresse les fichiers en ZIP et déclenche le téléchargement.
|
||||||
|
* Si un fichier possède un `folder`, il est placé dans le sous-dossier correspondant.
|
||||||
|
* @param {{ name: string, blob: Blob, folder?: string }[]} processedFiles
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function downloadAllAsZip(processedFiles) {
|
export async function downloadAllAsZip(processedFiles) {
|
||||||
throw new Error('Not implemented');
|
const zip = new JSZip();
|
||||||
|
for (const { name, blob, folder } of processedFiles) {
|
||||||
|
const path = folder ? `${folder}/${name}` : name;
|
||||||
|
zip.file(path, blob);
|
||||||
|
}
|
||||||
|
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
||||||
|
const url = URL.createObjectURL(zipBlob);
|
||||||
|
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = `photos-produits-${new Date().toISOString().slice(0, 10)}.zip`;
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
/**
|
||||||
|
* Lecture d'un ZIP produits.
|
||||||
|
* Attend une structure : dossier-produit/image.heic (ou jpg/png).
|
||||||
|
* JSZip est chargé comme script global dans index.html.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const IMAGE_EXTS = new Set(['heic', 'heif', 'jpg', 'jpeg', 'png']);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extrait toutes les images d'un fichier ZIP.
|
||||||
|
* @param {File} zipFile
|
||||||
|
* @returns {Promise<Array<{folder:string, name:string, ext:string, blob:Blob, isHeic:boolean}>>}
|
||||||
|
*/
|
||||||
|
export async function readImagesFromZip(zipFile) {
|
||||||
|
const zip = await JSZip.loadAsync(zipFile);
|
||||||
|
|
||||||
|
// Collecter les entrées fichier (pas les dossiers)
|
||||||
|
const entries = [];
|
||||||
|
zip.forEach((relativePath, entry) => {
|
||||||
|
if (!entry.dir) entries.push({ relativePath, entry });
|
||||||
|
});
|
||||||
|
|
||||||
|
const results = [];
|
||||||
|
|
||||||
|
for (const { relativePath, entry } of entries) {
|
||||||
|
// Ignorer les métadonnées macOS et fichiers cachés
|
||||||
|
if (relativePath.startsWith('__MACOSX/')) continue;
|
||||||
|
|
||||||
|
const parts = relativePath.split('/').filter(p => p.length > 0);
|
||||||
|
const filename = parts[parts.length - 1];
|
||||||
|
if (filename.startsWith('.')) continue;
|
||||||
|
|
||||||
|
// Extension
|
||||||
|
const dotIdx = filename.lastIndexOf('.');
|
||||||
|
if (dotIdx === -1) continue;
|
||||||
|
const ext = filename.slice(dotIdx + 1).toLowerCase();
|
||||||
|
if (!IMAGE_EXTS.has(ext)) continue;
|
||||||
|
|
||||||
|
const name = filename.slice(0, dotIdx);
|
||||||
|
// Premier segment du chemin = dossier produit (ex: "12345")
|
||||||
|
const folder = parts.length > 1 ? parts[0] : '';
|
||||||
|
|
||||||
|
const isHeic = ext === 'heic' || ext === 'heif';
|
||||||
|
const mimeType = isHeic ? 'image/heic'
|
||||||
|
: (ext === 'jpg' || ext === 'jpeg') ? 'image/jpeg'
|
||||||
|
: 'image/png';
|
||||||
|
|
||||||
|
// JSZip retourne des Blobs sans type MIME — on le définit explicitement
|
||||||
|
// pour que heic2any puisse détecter le format correctement.
|
||||||
|
const rawBlob = await entry.async('blob');
|
||||||
|
const blob = new Blob([rawBlob], { type: mimeType });
|
||||||
|
|
||||||
|
results.push({ folder, name, ext, blob, isHeic });
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user