Spaces:
Sleeping
Sleeping
first commit
Browse filesFiles changed (39)
- .dockerignoreAdded+12
- .gitattributes+2
- .gitignoreAdded+43
- DockerfileAdded+34
- README.md+16-6
- babel.config.jsAdded+5
- index.htmlAdded+14
- jsconfig.jsonAdded+19
- package-lock.jsonAdded
- package.jsonAdded+48
- public/favicon.icoAdded
- public/index.htmlAdded+17
- src/App.vueAdded+31
- src/assets/football.mp4Added+3
- src/assets/imgFoot.jpgAdded
- src/assets/logo.jpgAdded
- src/components/AnnotationsRawView.vueAdded+288
- src/components/EmptyView.vueAdded+277
- src/components/EnrichedSection.vueAdded+186
- src/components/LabelingView.vueAdded+255
- src/components/ObjectItem.vueAdded+357
- src/components/ObjectTimeline.vueAdded+70
- src/components/ObjectsTimelineSection.vueAdded+166
- src/components/SegmentationSidebar.vueAdded+217
- src/components/ShortcutsView.vueAdded+137
- src/components/TimelineSection.vueAdded+481
- src/components/VideoProgressTimeline.vueAdded+82
- src/components/VideoSection.vueAdded+1852
- src/components/VideoTimeline.vueAdded+30
- src/components/ZoomSection.vueAdded+198
- src/components/ZoomView.vueAdded+354
- src/components/tools/ToolBar.vueAdded+86
- src/components/tools/ToolButton.vueAdded+70
- src/main.jsAdded+11
- src/router/index.jsAdded+21
- src/stores/annotationStore.jsAdded+285
- src/stores/videoStore.jsAdded+96
- src/views/SegmentationView.vueAdded+132
- vue.config.jsAdded+5
123456789101112node_modules
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.git
.gitignore
README.md
.env
.nyc_output
coverage
.vscode
.DS_Store32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textsrc/assets/football.mp4 filter=lfs diff=lfs merge=lfs -textsrc/assets/imgFoot.jpg filter=lfs diff=lfs merge=lfs -text
12345678910111213141516171819202122232425262728293031323334353637383940414243.DS_Storenode_modules/dist
# local env files.env.local.env.*.local
# Log filesnpm-debug.log*yarn-debug.log*yarn-error.log*pnpm-debug.log*
# Editor directories and files.idea.vscode*.suo*.ntvs**.njsproj*.sln*.sw?
#Electron-builder output/dist_electron
*.exe*.blockmap*.dmg*.deb*.rpm*.AppImage*.snap*.tar.gz*/bundled*/mac*/mac_arm64*/mac_x64*/mac_arm64_x64*/mac_arm64_x64_x64*/mac_arm64_x64_x64_x64*/win-unpacked12345678910111213141516171819202122232425262728293031323334# Stage 1: Build
FROM node:20.18.0-alpine AS build-stage
WORKDIR /app
# Copier les fichiers de dépendances
COPY package*.json ./
# Installer les dépendances (sans --only=production=false qui est obsolète)
RUN npm ci
# Copier le code source
COPY . .
# Construire l'application
RUN npm run build
# Stage 2: Production
FROM node:20.18.0-alpine AS production-stage
# Installer serve globalement
RUN npm install -g serve
# Créer un utilisateur non-root pour la sécurité
USER node
WORKDIR /home/node
# Copier les fichiers buildés depuis le stage précédent
COPY --chown=node:node --from=build-stage /app/dist ./dist
# Exposer le port 7860 (requis par Hugging Face Spaces)
EXPOSE 7860
# Commande pour servir l'application
CMD ["serve", "-s", "dist", "-l", "7860"]12345678910---title: PointTrackAppemoji: 🔥colorFrom: pinkcolorTo: bluesdk: dockerpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567891011121314151617181920---title: Point Tracker Appemoji: ⚽colorFrom: bluecolorTo: greensdk: dockerapp_port: 7860---# Point Tracker AppApplication Vue.js pour l'annotation et le suivi de points dans des vidéos de football.## Fonctionnalités- 🎯 Annotation de points sur vidéo- 🏷️ Système de labellisation (Player Team 1, Player Team 2, Ball)- ⌨️ Raccourcis clavier pour une utilisation rapide- 📊 Export des annotations au format JSON- 🔍 Vue zoom et timeline
12345module.exports = { presets: [ '@vue/cli-plugin-babel/preset' ]}1234567891011121314<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html> 12345678910111213141516171819{ "compilerOptions": { "target": "es5", "module": "esnext", "baseUrl": "./", "moduleResolution": "node", "paths": { "@/*": [ "src/*" ] }, "lib": [ "esnext", "dom", "dom.iterable", "scripthost" ] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748{
"name": "point-tracker-app",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"core-js": "^3.8.3",
"js-yaml": "^4.1.0",
"konva": "^9.3.20",
"pinia": "^3.0.2",
"vue": "^3.2.13",
"vue-konva": "^3.2.1",
"vue-router": "^4.5.0"
},
"devDependencies": {
"@babel/core": "^7.12.16",
"@babel/eslint-parser": "^7.12.16",
"@vue/cli-plugin-babel": "~5.0.0",
"@vue/cli-plugin-eslint": "~5.0.0",
"@vue/cli-service": "~5.0.0",
"eslint": "^7.32.0",
"eslint-plugin-vue": "^8.0.3"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "@babel/eslint-parser"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead",
"not ie 11"
]
}1234567891011121314151617<!DOCTYPE html><html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <title><%= htmlWebpackPlugin.options.title %></title> </head> <body> <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <!-- built files will be auto injected --> </body></html>12345678910111213141516171819202122232425262728293031<template>
<div id="app">
<router-view />
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
#app {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
height: 100vh;
overflow: hidden;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
</style>
<!-- npm run electron:serve -->
<!-- uvicorn main:app --reload -->123version https://git-lfs.github.com/spec/v1oid sha256:f9a5a4d58029c92484c0ca7ed7abeae32e710115386f078f4da4236b2bc551f6size 144517071123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288<template>
<div class="annotations-raw-view">
<div class="raw-header">
<h4>Annotations Brutes</h4>
<div class="frame-info">
<span>Frame {{ currentFrameNumber }}</span>
<span v-if="selectedObject">{{ selectedObject.name }}</span>
</div>
</div>
<div class="raw-content" v-if="selectedAnnotations.length > 0">
<div
v-for="annotation in selectedAnnotations"
:key="annotation.id"
class="annotation-item"
:class="`annotation-${annotation.type}`"
>
<div class="annotation-header">
<span class="annotation-type">{{ getAnnotationTypeLabel(annotation.type) }}</span>
<span class="annotation-id">ID: {{ annotation.id.slice(0, 8) }}...</span>
</div>
<div class="annotation-data">
<div v-if="annotation.type === 'rectangle'" class="rectangle-data">
<div class="data-row">
<span class="data-label">Position:</span>
<span class="data-value">{{ Math.round(annotation.x) }}, {{ Math.round(annotation.y) }}</span>
</div>
<div class="data-row">
<span class="data-label">Dimensions:</span>
<span class="data-value">{{ Math.round(annotation.width) }} × {{ Math.round(annotation.height) }}</span>
</div>
</div>
<div v-else-if="annotation.type === 'point'" class="point-data">
<div class="data-row">
<span class="data-label">Position:</span>
<span class="data-value">{{ Math.round(annotation.x) }}, {{ Math.round(annotation.y) }}</span>
</div>
<div class="data-row">
<span class="data-label">Type:</span>
<span class="data-value" :class="`point-${annotation.pointType}`">
{{ annotation.pointType === 'positive' ? 'Positif (+)' : 'Négatif (-)' }}
</span>
</div>
</div>
<div v-else-if="annotation.type === 'mask'" class="mask-data">
<div class="data-row">
<span class="data-label">Score:</span>
<span class="data-value">{{ (annotation.maskScore * 100).toFixed(1) }}%</span>
</div>
<div class="data-row">
<span class="data-label">Taille image:</span>
<span class="data-value">{{ annotation.maskImageSize?.width }} × {{ annotation.maskImageSize?.height }}</span>
</div>
<div class="data-row">
<span class="data-label">Points:</span>
<span class="data-value">{{ annotation.points?.length || 0 }} points</span>
</div>
<div v-if="annotation.points && annotation.points.length > 0" class="points-details">
<div v-for="(point, pointIndex) in annotation.points" :key="pointIndex" class="point-detail">
<span class="point-coords">{{ Math.round(point.x) }}, {{ Math.round(point.y) }}</span>
<span class="point-type" :class="`point-${point.type}`">{{ point.type }}</span>
</div>
</div>
</div>
<div v-else class="generic-data">
<div class="data-row">
<span class="data-label">Données:</span>
<span class="data-value">{{ JSON.stringify(annotation, null, 2) }}</span>
</div>
</div>
</div>
</div>
</div>
<div v-else class="no-annotations">
<div class="no-annotations-content">
<svg width="48" height="48" viewBox="0 0 24 24" fill="currentColor">
<path d="M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,4A8,8 0 0,1 20,12A8,8 0 0,1 12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4M11,16.5L6.5,12L7.91,10.59L11,13.67L16.59,8.09L18,9.5L11,16.5Z" opacity="0.3"/>
</svg>
<p v-if="!selectedObject">Aucun objet sélectionné</p>
<p v-else>Aucune annotation pour cet objet sur cette frame</p>
</div>
</div>
</div>
</template>
<script>
import { useAnnotationStore } from '@/stores/annotationStore'
import { useVideoStore } from '@/stores/videoStore'
import { computed } from 'vue'
export default {
name: 'AnnotationsRawView',
setup() {
const annotationStore = useAnnotationStore()
const videoStore = useVideoStore()
const getCurrentFrameNumber = () => {
const frameRate = annotationStore.currentSession?.frameRate || 30
return Math.round(videoStore.currentTime * frameRate)
}
const currentFrameNumber = computed(() => getCurrentFrameNumber())
const selectedObject = computed(() => {
if (!annotationStore.selectedObjectId) return null
return annotationStore.objects[annotationStore.selectedObjectId]
})
const selectedAnnotations = computed(() => {
const currentFrame = getCurrentFrameNumber()
const frameAnnotations = annotationStore.getAnnotationsForFrame(currentFrame) || []
return frameAnnotations.filter(
annotation => annotation && annotation.objectId === annotationStore.selectedObjectId
)
})
return {
currentFrameNumber,
selectedObject,
selectedAnnotations
}
},
methods: {
getAnnotationTypeLabel(type) {
const labels = {
'rectangle': 'Rectangle',
'point': 'Point',
'mask': 'Masque',
'polygon': 'Polygone'
}
return labels[type] || type.charAt(0).toUpperCase() + type.slice(1)
}
}
}
</script>
<style scoped>
.annotations-raw-view {
height: 100%;
display: flex;
flex-direction: column;
color: white;
}
.raw-header {
padding: 12px;
border-bottom: 1px solid #4a4a4a;
}
.raw-header h4 {
margin: 0 0 4px 0;
font-size: 0.9rem;
color: #fff;
}
.frame-info {
display: flex;
gap: 12px;
font-size: 0.8rem;
color: #ccc;
}
.raw-content {
flex: 1;
padding: 8px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 8px;
}
.annotation-item {
background: #3c3c3c;
border-radius: 6px;
padding: 8px;
border-left: 3px solid #4ecdc4;
}
.annotation-item.annotation-rectangle {
border-left-color: #00ff00;
}
.annotation-item.annotation-point {
border-left-color: #ff6b35;
}
.annotation-item.annotation-mask {
border-left-color: #a55eea;
}
.annotation-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 6px;
}
.annotation-type {
font-weight: 500;
font-size: 0.8rem;
color: #fff;
}
.annotation-id {
font-size: 0.7rem;
color: #999;
font-family: monospace;
}
.annotation-data {
font-size: 0.8rem;
}
.data-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 4px;
}
.data-label {
color: #ccc;
font-weight: 500;
}
.data-value {
color: #fff;
font-family: monospace;
}
.point-positive {
color: #00ff00;
}
.point-negative {
color: #ff0000;
}
.points-details {
margin-top: 6px;
padding-left: 8px;
border-left: 1px solid #555;
}
.point-detail {
display: flex;
justify-content: space-between;
font-size: 0.7rem;
margin-bottom: 2px;
}
.point-coords {
color: #ccc;
font-family: monospace;
}
.point-type {
font-weight: 500;
}
.no-annotations {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
.no-annotations-content {
text-align: center;
color: #666;
}
.no-annotations-content svg {
margin-bottom: 16px;
}
.no-annotations-content p {
margin: 0;
font-style: italic;
}
</style> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277<template>
<div class="export-view">
<div class="export-content">
<div class="export-header">
<h3>Export</h3>
</div>
<div class="export-info">
<div class="info-row">
<span>{{ objectCount }} objets, {{ annotationCount }} annotations</span>
</div>
<div class="info-row filename">
<span>{{ fileName }}</span>
</div>
</div>
<div class="export-actions">
<button
class="export-button"
@click="exportAnnotations"
:disabled="!hasAnnotations"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<path d="M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z"/>
</svg>
Télécharger
</button>
<p v-if="!hasAnnotations" class="no-data-message">
Aucune donnée à exporter
</p>
</div>
</div>
</div>
</template>
<script>
import { useAnnotationStore } from '@/stores/annotationStore'
import { useVideoStore } from '@/stores/videoStore'
import { computed } from 'vue'
export default {
name: 'EmptyView',
setup() {
const annotationStore = useAnnotationStore()
const videoStore = useVideoStore()
const videoName = computed(() => {
if (videoStore.selectedVideo?.name) {
return videoStore.selectedVideo.name.replace(/\.[^/.]+$/, '') // Enlever l'extension
}
return 'default_video'
})
const fileName = computed(() => {
return `${videoName.value}_config.json`
})
const objectCount = computed(() => {
return Object.keys(annotationStore.objects).length
})
const annotationCount = computed(() => {
let count = 0
Object.values(annotationStore.frameAnnotations).forEach(frameAnnotations => {
count += frameAnnotations.length
})
return count
})
const hasAnnotations = computed(() => {
return annotationCount.value > 0
})
const exportAnnotations = () => {
// Créer la structure objects selon le format demandé
const objects = Object.values(annotationStore.objects).map(obj => {
const objData = {
obj_id: parseInt(obj.id)
}
// Analyser le label pour extraire le type et l'équipe
if (obj.label) {
const label = obj.label.toLowerCase()
if (label.includes('ball')) {
objData.obj_type = 'ball'
objData.team = null
} else if (label.includes('player')) {
objData.obj_type = 'player'
// Extraire le numéro d'équipe
if (label.includes('team 1') || label.includes('team1')) {
objData.team = 1
} else if (label.includes('team 2') || label.includes('team2')) {
objData.team = 2
} else {
objData.team = null
}
} else {
objData.obj_type = null
objData.team = null
}
} else {
objData.obj_type = null
objData.team = null
}
return objData
})
// Créer la structure initial_annotations selon le format demandé
const initial_annotations = []
// Parcourir toutes les frames qui ont des annotations
Object.keys(annotationStore.frameAnnotations).forEach(frameNumber => {
const frameAnnotations = annotationStore.frameAnnotations[frameNumber]
const frameData = {
frame: parseInt(frameNumber),
annotations: []
}
// Grouper les annotations par objet pour cette frame
const annotationsByObject = {}
frameAnnotations.forEach(annotation => {
if (!annotationsByObject[annotation.objectId]) {
annotationsByObject[annotation.objectId] = []
}
// Extraire les points selon le type d'annotation
if (annotation.type === 'point') {
annotationsByObject[annotation.objectId].push({
x: Math.round(annotation.x),
y: Math.round(annotation.y),
label: annotation.pointType === 'positive' ? 1 : 0
})
} else if (annotation.type === 'mask' && annotation.points) {
// Ajouter tous les points du masque
annotation.points.forEach(point => {
annotationsByObject[annotation.objectId].push({
x: Math.round(point.x),
y: Math.round(point.y),
label: point.type === 'positive' ? 1 : 0
})
})
}
})
// Créer les annotations pour cette frame
Object.keys(annotationsByObject).forEach(objectId => {
const points = annotationsByObject[objectId]
if (points.length > 0) {
frameData.annotations.push({
obj_id: parseInt(objectId),
points: points
})
}
})
// Ajouter la frame seulement si elle a des annotations
if (frameData.annotations.length > 0) {
initial_annotations.push(frameData)
}
})
// Structure finale selon le format demandé
const exportData = {
objects: objects,
initial_annotations: initial_annotations
}
// Créer le blob et le télécharger
const jsonString = JSON.stringify(exportData, null, 2)
const blob = new Blob([jsonString], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = fileName.value
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(url)
console.log('Annotations exportées:', fileName.value)
}
return {
videoName,
fileName,
objectCount,
annotationCount,
hasAnnotations,
exportAnnotations
}
}
}
</script>
<style scoped>
.export-view {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
color: white;
padding: 20px;
}
.export-content {
text-align: center;
width: 100%;
}
.export-header {
margin-bottom: 20px;
}
.export-header h3 {
margin: 0;
font-size: 1rem;
color: #fff;
font-weight: 500;
}
.export-info {
margin-bottom: 20px;
}
.info-row {
margin-bottom: 8px;
color: #ccc;
font-size: 0.9rem;
}
.info-row.filename {
color: #fff;
font-family: monospace;
font-size: 0.8rem;
}
.export-actions {
text-align: center;
}
.export-button {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 8px 16px;
background: #4a4a4a;
color: white;
border: none;
border-radius: 4px;
font-size: 0.8rem;
cursor: pointer;
transition: background 0.2s;
}
.export-button:hover:not(:disabled) {
background: #5a5a5a;
}
.export-button:disabled {
background: #3c3c3c;
color: #666;
cursor: not-allowed;
}
.no-data-message {
margin: 12px 0 0 0;
color: #666;
font-size: 0.8rem;
font-style: italic;
}
</style> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186<template>
<div class="enriched-section">
<div class="enriched-header">
<div class="view-navigation">
<button
class="nav-button"
@click="previousView"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
</svg>
</button>
<span class="view-indicator">
{{ currentViewIndex + 1 }} / {{ views.length }}
</span>
<button
class="nav-button"
@click="nextView"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
</svg>
</button>
</div>
</div>
<div class="enriched-content">
<transition :name="transitionName" mode="out-in">
<component
:is="currentView.component"
:key="currentViewIndex"
class="view-content"
/>
</transition>
</div>
</div>
</template>
<script>
import LabelingView from './LabelingView.vue'
import EmptyView from './EmptyView.vue'
import ShortcutsView from './ShortcutsView.vue'
export default {
name: 'EnrichedSection',
components: {
LabelingView,
EmptyView,
ShortcutsView
},
data() {
return {
currentViewIndex: 0,
transitionName: 'slide-right',
views: [
{
name: 'Labeling',
component: 'LabelingView'
},
{
name: 'Export',
component: 'EmptyView'
},
{
name: 'Shortcuts',
component: 'ShortcutsView'
}
]
}
},
computed: {
currentView() {
return this.views[this.currentViewIndex]
}
},
methods: {
nextView() {
this.transitionName = 'slide-right'
this.currentViewIndex = (this.currentViewIndex + 1) % this.views.length
},
previousView() {
this.transitionName = 'slide-left'
this.currentViewIndex = this.currentViewIndex === 0
? this.views.length - 1
: this.currentViewIndex - 1
}
}
}
</script>
<style scoped>
.enriched-section {
width: 100%;
height: 100%;
background: #2c2c2c;
border-radius: 8px;
display: flex;
flex-direction: column;
overflow: hidden;
}
.enriched-header {
padding: 8px 12px;
background: #3c3c3c;
border-bottom: 1px solid #4a4a4a;
display: flex;
justify-content: center;
align-items: center;
}
.view-navigation {
display: flex;
align-items: center;
gap: 8px;
}
.nav-button {
background: #4a4a4a;
border: none;
border-radius: 4px;
color: white;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s;
}
.nav-button:hover:not(:disabled) {
background: #5a5a5a;
}
.view-indicator {
color: #ccc;
font-size: 0.8rem;
min-width: 40px;
text-align: center;
}
.enriched-content {
flex: 1;
position: relative;
overflow: hidden;
}
.view-content {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
/* Animations de transition */
.slide-right-enter-active, .slide-right-leave-active,
.slide-left-enter-active, .slide-left-leave-active {
transition: transform 0.3s ease;
}
/* Animation vers la droite */
.slide-right-enter-from {
transform: translateX(100%);
}
.slide-right-leave-to {
transform: translateX(-100%);
}
/* Animation vers la gauche */
.slide-left-enter-from {
transform: translateX(-100%);
}
.slide-left-leave-to {
transform: translateX(100%);
}
</style> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255<template>
<div class="labeling-view">
<div class="labels-container" v-if="selectedObject">
<div class="label-options">
<div class="label-list">
<div
v-for="label in predefinedLabels"
:key="label.name"
class="label-item"
>
<button
class="label-btn"
:class="{ active: selectedObject.label === label.name }"
:style="{
backgroundColor: label.color,
border: selectedObject.label === label.name ? '3px solid #fff' : '3px solid transparent'
}"
@click="assignLabel(label.name)"
>
<span class="label-text">{{ label.name }}</span>
<span class="shortcut-key">{{ getShortcutKey(label.name) }}</span>
</button>
<input
type="color"
:value="label.color"
@input="updateLabelColor(label.name, $event.target.value)"
class="color-picker"
:title="`Changer la couleur de ${label.name}`"
/>
</div>
</div>
</div>
</div>
<div v-else class="no-object-message">
<p>Sélectionnez un objet dans la timeline pour lui attribuer un label</p>
</div>
</div>
</template>
<script>
import { useAnnotationStore } from '@/stores/annotationStore'
export default {
name: 'LabelingView',
data() {
return {
predefinedLabels: [
{ name: 'Player Team 1', color: '#dc3545' },
{ name: 'Player Team 2', color: '#000000' },
{ name: 'Ball', color: '#28a745' }
]
}
},
setup() {
const annotationStore = useAnnotationStore()
return {
annotationStore
}
},
mounted() {
// Ajouter l'écouteur d'événement clavier
window.addEventListener('keydown', this.handleKeyPress)
},
beforeUnmount() {
// Supprimer l'écouteur d'événement clavier
window.removeEventListener('keydown', this.handleKeyPress)
},
computed: {
selectedObject() {
if (!this.annotationStore.selectedObjectId) return null
return this.annotationStore.objects[this.annotationStore.selectedObjectId]
}
},
methods: {
assignLabel(labelName) {
if (!this.selectedObject) return
// Mettre à jour l'objet avec le nouveau label
this.annotationStore.objects[this.selectedObject.id] = {
...this.selectedObject,
label: labelName
}
console.log(`Label "${labelName}" assigné à l'objet ${this.selectedObject.name}`)
},
updateLabelColor(labelName, newColor) {
const labelIndex = this.predefinedLabels.findIndex(label => label.name === labelName)
if (labelIndex !== -1) {
this.predefinedLabels[labelIndex].color = newColor
}
},
removeLabel() {
if (!this.selectedObject) return
// Supprimer le label de l'objet
const updatedObject = { ...this.selectedObject }
delete updatedObject.label
this.annotationStore.objects[this.selectedObject.id] = updatedObject
console.log(`Label supprimé de l'objet ${this.selectedObject.name}`)
},
getLabelColor(labelName) {
const predefinedLabel = this.predefinedLabels.find(label => label.name === labelName)
return predefinedLabel ? predefinedLabel.color : '#6c757d'
},
getShortcutKey(labelName) {
const shortcuts = {
'Player Team 1': '1',
'Player Team 2': '2',
'Ball': '3'
}
return shortcuts[labelName] || ''
},
handleKeyPress(event) {
// Vérifier que nous ne sommes pas dans un champ de saisie
if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
return
}
// Vérifier qu'un objet est sélectionné
if (!this.selectedObject) {
return
}
// Gérer les raccourcis clavier
switch(event.key) {
case '1':
event.preventDefault()
this.assignLabel('Player Team 1')
break
case '2':
event.preventDefault()
this.assignLabel('Player Team 2')
break
case '3':
event.preventDefault()
this.assignLabel('Ball')
break
}
}
}
}
</script>
<style scoped>
.labeling-view {
height: 100%;
padding: 16px;
color: white;
overflow-y: auto;
}
.labels-container {
display: flex;
flex-direction: column;
gap: 20px;
}
.label-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.label-item {
display: flex;
align-items: center;
gap: 8px;
}
.label-btn {
flex: 1;
padding: 8px 12px;
border-radius: 4px;
color: white;
font-size: 0.8rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.label-btn:hover {
opacity: 0.8;
transform: translateY(-1px);
}
.label-btn.active {
box-shadow: 0 0 0 1px #fff;
}
.color-picker {
width: 32px;
height: 32px;
border: none;
border-radius: 4px;
cursor: pointer;
background: none;
padding: 0;
}
.color-picker::-webkit-color-swatch-wrapper {
padding: 0;
border-radius: 4px;
}
.color-picker::-webkit-color-swatch {
border: none;
border-radius: 4px;
}
.label-text {
flex: 1;
text-align: left;
}
.shortcut-key {
background-color: rgba(255, 255, 255, 0.2);
border-radius: 3px;
padding: 2px 6px;
font-size: 11px;
font-weight: bold;
min-width: 16px;
text-align: center;
}
.no-object-message {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
text-align: center;
}
.no-object-message p {
color: #999;
font-style: italic;
}
</style> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357<template>
<div
class="object-item"
:class="{ 'selected': isSelected }"
@click="toggleSelection"
>
<div class="object-id">
<span>{{ objectId }}</span>
</div>
<div class="object-timeline" ref="timelineRef">
<div class="timeline-line"></div>
<!-- Points pour chaque annotation -->
<div
v-for="(frameKey, index) in annotatedFrames"
:key="index"
class="annotation-point"
:style="{
left: `${calculatePositionExact(parseInt(frameKey))}%`,
backgroundColor: getObjectColor
}"
:title="`Frame ${frameKey}`"
@click.stop="goToFrame(parseInt(frameKey))"
></div>
</div>
</div>
<!-- Popup de confirmation simplifiée -->
<div v-if="showDeleteConfirm" class="delete-overlay" @click="cancelDelete">
<div class="delete-modal" @click.stop>
<h3>Supprimer {{ objectId }} ?</h3>
<p>Cette action est irréversible.</p>
<div class="delete-actions">
<button class="btn-cancel" @click="cancelDelete">Annuler</button>
<button class="btn-delete" @click="confirmDelete">Supprimer</button>
</div>
</div>
</div>
</template>
<script>
import { useAnnotationStore } from '@/stores/annotationStore'
import { useVideoStore } from '@/stores/videoStore'
import { computed, ref, onMounted, onUnmounted } from 'vue'
export default {
name: 'ObjectItem',
props: {
objectId: {
type: String,
default: 'object1'
},
colorIndex: {
type: Number,
default: 0
}
},
setup(props) {
const annotationStore = useAnnotationStore()
const videoStore = useVideoStore()
const timelineRef = ref(null)
const showDeleteConfirm = ref(false)
// Keyboard shortcut handler
const handleKeyDown = (event) => {
// Add new object when pressing 'N' key
if (event.key === 'n' || event.key === 'N') {
// Prevent default behavior (like typing 'n' in an input field)
event.preventDefault()
// Only process the event if this is the first object item
// This prevents multiple objects from being created when multiple ObjectItems exist
if (props.objectId !== Object.keys(annotationStore.objects)[0]) {
return;
}
// Check available methods and use the correct one
if (typeof annotationStore.addObject === 'function') {
annotationStore.addObject();
} else if (typeof annotationStore.createNewObject === 'function') {
annotationStore.createNewObject();
} else {
// Fallback: Create a new object ID based on the last object ID + 1
const objectIds = Object.keys(annotationStore.objects);
let lastId = 0;
// Find the highest numeric ID
objectIds.forEach(id => {
// Extract numeric part from objectX format
const numericPart = parseInt(id.replace('object', ''));
if (!isNaN(numericPart) && numericPart > lastId) {
lastId = numericPart;
}
});
// Create new object with ID = last ID + 1
const newObjectId = `object${lastId + 1}`;
annotationStore.objects[newObjectId] = {
id: newObjectId,
color: annotationStore.getNextColor(),
// Add any other required properties
};
console.log(`Created new object: ${newObjectId}`);
}
}
// Delete selected object when pressing Ctrl+Delete key
if (event.key === 'Delete' && event.ctrlKey && annotationStore.selectedObjectId === props.objectId) {
event.preventDefault()
showDeleteConfirm.value = true
}
// Fermer la popup avec Escape
if (event.key === 'Escape' && showDeleteConfirm.value) {
event.preventDefault()
showDeleteConfirm.value = false
}
}
// Add and remove event listeners
onMounted(() => {
window.addEventListener('keydown', handleKeyDown)
})
onUnmounted(() => {
window.removeEventListener('keydown', handleKeyDown)
})
// Vérifier si cet objet est actuellement sélectionné
const isSelected = computed(() => {
return annotationStore.selectedObjectId === props.objectId
})
// Fonction pour basculer la sélection de l'objet
const toggleSelection = () => {
if (isSelected.value) {
annotationStore.deselectObject()
} else {
annotationStore.selectObject(props.objectId)
}
}
// Fonctions pour la popup de confirmation
const confirmDelete = () => {
annotationStore.deleteObject(props.objectId)
showDeleteConfirm.value = false
}
const cancelDelete = () => {
showDeleteConfirm.value = false
}
// Récupérer toutes les frames où cet objet a des annotations
const annotatedFrames = computed(() => {
const frames = []
Object.keys(annotationStore.frameAnnotations).forEach(frameKey => {
const hasObjectAnnotation = annotationStore.frameAnnotations[frameKey].some(
annotation => annotation.objectId === props.objectId
)
if (hasObjectAnnotation) {
frames.push(frameKey)
}
})
return frames
})
// Obtenir la couleur de l'objet
const getObjectColor = computed(() => {
return annotationStore.objects[props.objectId]?.color || '#4CAF50'
})
// Calculer la position en pourcentage pour une frame donnée
const calculatePositionExact = (frameNumber) => {
const frameRate = annotationStore.currentSession.frameRate || 30
const timeInSeconds = frameNumber / frameRate
const videoDuration = videoStore.duration || videoStore.selectedVideo?.duration || 0
if (!videoDuration || videoDuration <= 0) {
console.warn('Attention: Durée de vidéo non disponible, utilisation d\'une valeur par défaut')
return 0 // Ou retourner une position par défaut
}
return (timeInSeconds / videoDuration) * 100
}
// Fonction pour naviguer vers une frame spécifique
const goToFrame = (frameNumber) => {
// Convertir le numéro de frame en temps (secondes)
const frameRate = annotationStore.currentSession.frameRate || 30
// Utiliser une valeur exacte pour le temps en secondes
// Ajouter un petit décalage (0.001) pour éviter les problèmes d'arrondi
const timeInSeconds = frameNumber / frameRate + 0.001
// Mettre à jour le temps courant dans le videoStore
videoStore.setCurrentTime(timeInSeconds)
// Utiliser la méthode seek si disponible
if (videoStore.seek) {
videoStore.seek(timeInSeconds)
} else {
// Fallback: essayer d'accéder directement à l'élément vidéo
const videoElement = document.querySelector('video')
if (videoElement) {
videoElement.currentTime = timeInSeconds
}
}
// Forcer la mise à jour de l'interface
videoStore.updateProgressBar(timeInSeconds)
}
return {
annotatedFrames,
calculatePositionExact,
getObjectColor,
timelineRef,
isSelected,
toggleSelection,
goToFrame,
showDeleteConfirm,
confirmDelete,
cancelDelete
}
}
}
</script>
<style scoped>
.object-item {
display: flex;
height: 24px;
margin-bottom: 18px;
align-items: center;
gap: 14px;
cursor: pointer;
transition: background-color 0.2s ease;
border-radius: 4px;
padding: 2px 4px;
position: relative;
}
.object-item:hover {
background-color: rgba(255, 255, 255, 0.1);
}
.object-item.selected {
background-color: rgba(255, 255, 255, 0.2);
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.5);
}
.object-id {
width: 35px;
font-weight: bold;
font-size: 0.9rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: white;
}
.object-timeline {
flex-grow: 1;
height: 100%;
position: relative;
border-radius: 4px;
display: flex;
align-items: center;
border-color: white;
}
.timeline-line {
height: 1px;
width: 100%;
background-color: white;
}
.annotation-point {
position: absolute;
width: 8px;
height: 8px;
background-color: #4CAF50;
border-radius: 50%;
transform: translateX(-50%);
z-index: 2;
}
/* Popup de confirmation simplifiée */
.delete-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.6);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.delete-modal {
background: #2c2c2c;
border-radius: 8px;
padding: 20px;
max-width: 300px;
width: 90%;
text-align: center;
color: white;
}
.delete-modal h3 {
margin: 0 0 12px 0;
font-size: 1.1rem;
color: #fff;
}
.delete-modal p {
margin: 0 0 20px 0;
color: #ccc;
font-size: 0.9rem;
}
.delete-actions {
display: flex;
gap: 12px;
justify-content: center;
}
.btn-cancel,
.btn-delete {
padding: 8px 16px;
border: none;
border-radius: 4px;
font-size: 0.9rem;
cursor: pointer;
transition: all 0.2s ease;
}
.btn-cancel {
background: #555;
color: white;
}
.btn-cancel:hover {
background: #666;
}
.btn-delete {
background: #dc3545;
color: white;
}
.btn-delete:hover {
background: #c82333;
}
</style> 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970<template>
<div class="object-timeline">
<div class="object-info">
<span class="object-name">{{ object.name }}</span>
</div>
<div class="timeline-segments">
<div
v-for="segment in object.segments"
:key="segment.id"
class="segment"
:style="{
left: `${(segment.start / videoDuration) * 100}%`,
width: `${((segment.end - segment.start) / videoDuration) * 100}%`
}"
></div>
</div>
</div>
</template>
<script>
export default {
name: 'ObjectTimeline',
props: {
object: {
type: Object,
required: true
},
videoDuration: {
type: Number,
required: true
}
}
}
</script>
<style scoped>
.object-timeline {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 0;
}
.object-info {
width: 120px;
flex-shrink: 0;
}
.object-name {
color: #ffffff;
font-size: 0.875rem;
}
.timeline-segments {
flex-grow: 1;
height: 24px;
background: #2c2c2c;
border-radius: 4px;
position: relative;
}
.segment {
position: absolute;
height: 100%;
background: #4CAF50;
opacity: 0.7;
border-radius: 2px;
}
</style> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166<template>
<div class="objects-timeline-section">
<div class="timeline-container">
<div class="objects-container">
<object-item
v-for="object in objects"
:key="object.id"
:object-id="object.id"
:object-name="object.name"
:color="object.color"
:is-selected="annotationStore.selectedObjectId === object.id"
@click="selectObject(object.id)"
/>
<div class="add-object" v-if="objects.length === 0 || showAddButton">
<button class="add-button" @click="addNewObject">+</button>
</div>
<div class="empty-state" v-if="objects.length === 0">
<p>Aucun objet créé</p>
<p>Cliquez sur + pour ajouter un objet</p>
</div>
</div>
<div class="timeline-tools"></div>
</div>
</div>
</template>
<script>
import ObjectItem from './ObjectItem.vue'
import { useAnnotationStore } from '@/stores/annotationStore'
import { storeToRefs } from 'pinia'
export default {
name: 'ObjectsTimelineSection',
components: {
ObjectItem
},
setup() {
const annotationStore = useAnnotationStore()
const { objects } = storeToRefs(annotationStore)
return {
annotationStore,
objects
}
},
data() {
return {
showAddButton: true
}
},
methods: {
selectObject(objectId) {
this.annotationStore.selectObject(objectId)
this.$emit('object-selected', objectId)
},
addNewObject() {
const newObjectId = this.annotationStore.addObject()
this.$emit('object-selected', newObjectId)
}
}
}
</script>
<style scoped>
.objects-timeline-section {
background: #363636;
border-radius: 8px;
height: 100%;
display: flex;
flex-direction: column;
overflow: hidden; /* Contenir tout le contenu */
}
.timeline-container {
display: flex;
gap: 10px;
flex: 1;
min-height: 0; /* Crucial pour que le scroll fonctionne dans un conteneur flex */
overflow: hidden; /* Contenir les enfants */
}
.objects-container {
flex-grow: 1;
overflow-y: auto; /* Activer le défilement vertical */
padding: 8px;
background: #2a2a2a;
border-radius: 4px;
/* Stylisation de la scrollbar */
scrollbar-width: thin;
scrollbar-color: #555 #2c2c2c;
direction: rtl; /* Déplace la scrollbar à gauche */
}
.objects-container > * {
direction: ltr; /* Rétablit la direction normale pour le contenu */
}
/* Stylisation de la scrollbar pour Chrome/Safari/Edge */
.objects-container::-webkit-scrollbar {
width: 8px;
}
.objects-container::-webkit-scrollbar-track {
background: #2c2c2c;
border-radius: 4px;
}
.objects-container::-webkit-scrollbar-thumb {
background-color: #555;
border-radius: 4px;
}
.timeline-tools {
width: 50px;
background: #2c2c2c;
border-radius: 4px;
height: 100%;
}
h3 {
color: #ffffff;
margin: 0 0 12px 0;
font-size: 1rem;
font-weight: 500;
}
.add-object {
display: flex;
justify-content: center;
margin-top: 8px;
}
.add-button {
width: 30px;
height: 30px;
border-radius: 50%;
background: #2c2c2c;
border: none;
color: white;
font-size: 20px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: background-color 0.2s;
}
.add-button:hover {
background: #3c3c3c;
}
.empty-state {
text-align: center;
color: #888;
padding: 20px 0;
font-size: 0.9rem;
}
.empty-state p {
margin: 5px 0;
}
</style> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217<template>
<div class="segmentation-sidebar">
<button class="upload-video-btn" @click="uploadVideo">
<span>Upload Video</span>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
<path d="m17 8-5-5-5 5"/>
<path d="M12 3v12"/>
</svg>
</button>
<!-- Input file caché -->
<input
ref="fileInput"
type="file"
accept="video/*"
@change="handleVideoUpload"
style="display: none;"
/>
<div class="video-list" v-if="videoStore.videos.length">
<div
v-for="video in videoStore.videos"
:key="video.path"
class="video-item"
:class="{ active: videoStore.selectedVideo?.path === video.path }"
@click="selectVideo(video)"
>
{{ video.name }}
</div>
</div>
</div>
</template>
<script>
import { useVideoStore } from '../stores/videoStore'
export default {
name: 'SegmentationSidebar',
data() {
const videoStore = useVideoStore()
return {
videoStore
}
},
watch: {
'videoStore.selectedVideo': {
handler(newVideo) {
console.log('Vidéo sélectionnée:', newVideo)
},
deep: true
}
},
mounted() {
// Plus besoin de charger un dossier par défaut - l'utilisateur uploadera une vidéo
console.log('SegmentationSidebar mounted - prêt pour l\'upload de vidéo')
},
methods: {
uploadVideo() {
// Déclencher le clic sur l'input file caché
this.$refs.fileInput.click()
},
handleVideoUpload(event) {
const file = event.target.files[0]
if (file) {
console.log('Vidéo sélectionnée:', file.name)
// Créer un URL blob pour la vidéo
const videoUrl = URL.createObjectURL(file)
// Créer un objet vidéo pour le store
const videoObject = {
name: file.name,
path: videoUrl,
file: file,
size: file.size,
type: file.type
}
// Mettre à jour le store avec la nouvelle vidéo
this.videoStore.setVideos([videoObject])
this.videoStore.setSelectedVideo(videoObject)
// Émettre l'événement pour informer les autres composants
this.$emit('video-selected', videoObject)
console.log('Vidéo uploadée et sélectionnée:', videoObject)
}
},
selectVideo(video) {
this.videoStore.setSelectedVideo(video)
this.$emit('video-selected', video)
}
}
}
</script>
<style scoped>
.segmentation-sidebar {
background: #363636;
height: 100%;
width: 200px;
padding: 16px;
display: flex;
flex-direction: column;
gap: 16px;
}
.navigation-menu {
display: flex;
flex-direction: column;
gap: 8px;
margin-bottom: 8px;
}
.nav-item {
display: flex;
align-items: center;
padding: 12px;
color: white;
text-decoration: none;
border-radius: 8px;
transition: all 0.2s ease;
background: #424242;
}
.nav-item:hover {
background: #4a4a4a;
}
.nav-item.active {
background: #3a3a3a;
color: #4CAF50;
}
.nav-icon {
margin-right: 12px;
font-size: 1.2rem;
}
.nav-text {
font-size: 0.9rem;
}
.upload-video-btn {
background: #424242;
border: none;
border-radius: 8px;
color: white;
padding: 12px 16px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
font-size: 1rem;
flex-shrink: 0;
transition: background-color 0.2s ease;
}
.upload-video-btn:hover {
background: #4a4a4a;
}
.video-list {
height: 20vh;
background: #424242;
border-radius: 8px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 4px;
padding: 4px;
}
/* Styles pour Firefox */
.video-list {
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
}
/* Styles pour Chrome/Safari/Edge */
.video-list::-webkit-scrollbar {
width: 4px;
}
.video-list::-webkit-scrollbar-track {
background: transparent;
}
.video-list::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 2px;
}
.video-item {
padding: 8px 12px;
border-radius: 4px;
cursor: pointer;
color: white;
transition: background-color 0.2s;
}
.video-item:hover {
background: #4a4a4a;
}
.video-item.active {
background: #3a3a3a;
}
</style> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137<template>
<div class="shortcuts-view">
<div class="shortcuts-header">
<h3>Raccourcis Clavier</h3>
</div>
<div class="shortcuts-content">
<div class="shortcuts-section">
<h4>Labellisation</h4>
<div class="shortcut-list">
<div class="shortcut-item">
<div class="shortcut-key">1</div>
<div class="shortcut-description">Player Team 1</div>
</div>
<div class="shortcut-item">
<div class="shortcut-key">2</div>
<div class="shortcut-description">Player Team 2</div>
</div>
<div class="shortcut-item">
<div class="shortcut-key">3</div>
<div class="shortcut-description">Ball</div>
</div>
</div>
</div>
<div class="shortcuts-section">
<h4>Objets</h4>
<div class="shortcut-list">
<div class="shortcut-item">
<div class="shortcut-key">N</div>
<div class="shortcut-description">Créer un nouvel objet</div>
</div>
<div class="shortcut-item">
<div class="shortcut-key">Ctrl + Suppr</div>
<div class="shortcut-description">Supprimer l'objet sélectionné</div>
</div>
</div>
</div>
<div class="shortcuts-section">
<h4>Navigation</h4>
<div class="shortcut-list">
<div class="shortcut-item">
<div class="shortcut-key">Espace</div>
<div class="shortcut-description">Lecture/Pause vidéo</div>
</div>
<div class="shortcut-item">
<div class="shortcut-key">←/→</div>
<div class="shortcut-description">Avancer/Reculer dans la vidéo</div>
</div>
<div class="shortcut-item">
<div class="shortcut-key">Échap</div>
<div class="shortcut-description">Fermer les popups</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'ShortcutsView'
}
</script>
<style scoped>
.shortcuts-view {
height: 100%;
padding: 16px;
color: white;
overflow-y: auto;
}
.shortcuts-header {
margin-bottom: 20px;
text-align: center;
}
.shortcuts-header h3 {
margin: 0;
font-size: 1.2rem;
color: #fff;
}
.shortcuts-content {
display: flex;
flex-direction: column;
gap: 24px;
}
.shortcuts-section h4 {
margin: 0 0 12px 0;
font-size: 1rem;
border-bottom: 1px solid #4a4a4a;
padding-bottom: 4px;
}
.shortcut-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.shortcut-item {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
background: #3c3c3c;
border-radius: 6px;
transition: background 0.2s;
}
.shortcut-item:hover {
background: #4a4a4a;
}
.shortcut-key {
background: #555;
color: white;
padding: 4px 8px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.8rem;
font-weight: bold;
min-width: 60px;
text-align: center;
border: 1px solid #666;
}
.shortcut-description {
flex: 1;
color: #e2e8f0;
font-size: 0.9rem;
}
</style> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481<template>
<div class="timeline-section">
<div class="timeline-container">
<div class="controls">
<button class="play-pause-btn" @click="togglePlayPause">
<!-- Triangle creux pour le bouton play -->
<svg v-if="!isPlaying" viewBox="0 0 24 24" width="20" height="20">
<polygon points="5,3 19,12 5,21" fill="none" stroke="white" stroke-width="1.5"/>
</svg>
<!-- Icône pause -->
<svg v-else viewBox="0 0 24 24" width="20" height="20">
<rect x="6" y="4" width="4" height="16" fill="white"/>
<rect x="14" y="4" width="4" height="16" fill="white"/>
</svg>
</button>
</div>
<div class="video-timeline">
<div class="timeline-track">
<div class="time-marker" :style="{ left: progressPercentage + '%' }">
<div class="time-indicator">{{ formatTimeSimple(preciseTime) }}</div>
<div class="marker-head"></div>
<div class="marker-line"></div>
</div>
<!-- Suppression des marqueurs d'annotation -->
<div class="frames-container">
<div
class="frame"
v-for="(thumbnail, index) in thumbnails"
:key="index"
:style="{ backgroundImage: `url(${thumbnail})` }"
></div>
</div>
<input
type="range"
min="0"
:max="duration"
step="0.01"
v-model="currentTime"
@input="seekVideo"
class="timeline-slider"
/>
</div>
</div>
<div class="timeline-tools"></div>
</div>
</div>
</template>
<script>
import { useVideoStore } from '@/stores/videoStore'
import { useAnnotationStore } from '@/stores/annotationStore'
export default {
name: 'TimelineSection',
data() {
return {
videoStore: useVideoStore(),
annotationStore: useAnnotationStore(),
isPlaying: false,
currentTime: 0,
duration: 100, // Valeur par défaut, sera mise à jour quand la vidéo sera chargée
videoElement: null,
thumbnails: [],
thumbnailCount: 6,
timeUpdateInterval: null,
keyboardListener: null,
unsubscribeTimeUpdate: null,
frameRate: 30, // Taux d'images par défaut, à mettre à jour lors du chargement de la vidéo
currentFrame: 0 // Numéro de frame actuel
}
},
computed: {
progressPercentage() {
// Utiliser directement la valeur du store pour s'assurer que les mises à jour sont reflétées
const storeTime = this.videoStore.currentTime || this.currentTime
return (storeTime / this.duration) * 100 || 0
},
// Calculer le temps exact basé sur le numéro de frame
preciseTime() {
return this.currentFrame / this.frameRate
},
// Récupérer toutes les frames qui ont des annotations
annotationFrames() {
return this.annotationStore.frameAnnotations || {}
}
},
mounted() {
// Ajouter un écouteur d'événement pour les touches Entrée et Espace
this.keyboardListener = (event) => {
if (event.key === ' ' || event.code === 'Space') {
// Empêcher le comportement par défaut (comme le défilement de la page avec la barre d'espace)
event.preventDefault();
this.togglePlayPause();
}
};
document.addEventListener('keydown', this.keyboardListener);
// S'abonner aux changements de temps dans le store
this.unsubscribeTimeUpdate = this.videoStore.$subscribe((mutation, state) => {
if (state.currentTime !== this.currentTime) {
this.currentTime = state.currentTime
// Mettre à jour également le numéro de frame
this.currentFrame = this.getCurrentFrame()
}
})
},
watch: {
'videoStore.selectedVideo': {
handler(newVideo) {
if (newVideo) {
console.log('Nouvelle vidéo sélectionnée dans Timeline:', newVideo)
this.resetPlayer()
this.loadVideo(newVideo.path)
// Mettre à jour le frameRate dans le store d'annotation
if (this.annotationStore.currentSession) {
this.annotationStore.currentSession.videoId = newVideo.id || newVideo.path
this.annotationStore.currentSession.frameRate = this.frameRate
}
}
},
immediate: true
}
},
methods: {
async loadVideo(videoPath) {
try {
// Utiliser la méthode du store pour charger la vidéo
const { duration, videoElement, frameRate } = await this.videoStore.loadVideoMetadata(videoPath)
// Mettre à jour les propriétés locales
this.duration = duration
this.videoElement = videoElement
this.frameRate = frameRate || 30 // Utiliser 30 fps par défaut si non spécifié
// Mettre à jour le frameRate dans le store d'annotation
if (this.annotationStore.currentSession) {
this.annotationStore.currentSession.frameRate = this.frameRate
}
// Générer les vignettes
this.generateThumbnails(videoElement)
} catch (error) {
console.error('Erreur lors du chargement de la vidéo:', error)
}
},
// Calculer la position d'une frame sur la timeline (en pourcentage)
getFramePosition(frameNumber) {
const timeInSeconds = frameNumber / this.frameRate
return (timeInSeconds / this.duration) * 100
},
// Obtenir la couleur pour un marqueur d'annotation
getAnnotationColor(frameNumber) {
const annotations = this.annotationStore.getAnnotationsForFrame(frameNumber)
if (annotations.length > 0) {
// Utiliser la couleur du premier objet annoté
const objectId = annotations[0].objectId
const object = this.annotationStore.objects[objectId]
return object ? object.color : '#FFFFFF'
}
return '#FFFFFF' // Couleur par défaut
},
async generateThumbnails(videoEl) {
this.thumbnails = []
// Créer un canvas pour dessiner les vignettes
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
// Définir la taille du canvas
canvas.width = 160 // Largeur de la vignette
canvas.height = 90 // Hauteur de la vignette (ratio 16:9)
// Générer les vignettes à intervalles réguliers
for (let i = 0; i < this.thumbnailCount; i++) {
const timePoint = (i / (this.thumbnailCount - 1)) * this.duration
// Positionner la vidéo au point temporel
videoEl.currentTime = timePoint
// Attendre que la vidéo soit positionnée
await new Promise(resolve => {
videoEl.addEventListener('seeked', resolve, { once: true })
})
// Dessiner l'image sur le canvas
ctx.drawImage(videoEl, 0, 0, canvas.width, canvas.height)
// Convertir le canvas en URL de données
const thumbnailUrl = canvas.toDataURL('image/jpeg')
this.thumbnails.push(thumbnailUrl)
}
},
// Méthode pour aller à une frame spécifique
goToFrame(frameNumber) {
this.currentFrame = frameNumber
const preciseTime = frameNumber / this.frameRate
// Mettre à jour le temps avec une précision à l'image près
this.currentTime = preciseTime
this.videoStore.currentTime = preciseTime
if (this.videoElement) {
// Utiliser requestAnimationFrame pour s'assurer que le DOM est prêt
requestAnimationFrame(() => {
this.videoElement.currentTime = preciseTime
})
}
// Mettre à jour l'interface
this.seekVideo()
},
// Méthode pour obtenir le numéro de frame actuel à partir du temps
getCurrentFrame() {
// Utiliser Math.round au lieu de Math.floor pour une meilleure précision
return Math.round(this.currentTime * this.frameRate)
},
togglePlayPause() {
this.isPlaying = !this.isPlaying
// Mettre à jour le store pour que VideoSection soit informé
this.videoStore.isPlaying = this.isPlaying
if (this.videoElement) {
if (this.isPlaying) {
// S'assurer que la vidéo commence à la position exacte de la frame actuelle
const preciseTime = this.currentFrame / this.frameRate
this.videoElement.currentTime = preciseTime
this.videoElement.play()
this.startTimeUpdate()
} else {
this.videoElement.pause()
this.stopTimeUpdate()
// Capturer le numéro de frame exact lors de la pause
this.currentFrame = this.getCurrentFrame()
}
} else {
// Mode simulation
if (this.isPlaying) {
// Commencer la simulation à partir de la frame actuelle
this.startTimeUpdate()
} else {
this.stopTimeUpdate()
// Capturer le numéro de frame exact lors de la pause
this.currentFrame = this.getCurrentFrame()
}
}
},
seekVideo() {
// Calculer le numéro de frame exact
this.currentFrame = this.getCurrentFrame()
// Calculer le temps précis basé sur le numéro de frame
const preciseTime = this.currentFrame / this.frameRate
if (this.videoElement) {
this.videoElement.currentTime = preciseTime
}
// Mettre à jour le store avec le temps précis
this.videoStore.currentTime = preciseTime
},
startTimeUpdate() {
// Utiliser requestAnimationFrame pour une meilleure fluidité
const updateTime = () => {
if (this.videoElement) {
this.currentTime = this.videoElement.currentTime
// Mettre à jour le numéro de frame actuel
this.currentFrame = this.getCurrentFrame()
// Mettre à jour le store à chaque frame
this.videoStore.currentTime = this.currentTime
} else {
// Simulation pour test - avancer d'une frame à la fois
this.currentFrame += 1
this.currentTime = this.currentFrame / this.frameRate
// Vérifier si on a atteint la fin
if (this.currentTime >= this.duration) {
this.isPlaying = false
this.videoStore.isPlaying = false
this.stopTimeUpdate()
return
}
// Mettre à jour le store même en mode simulation
this.videoStore.currentTime = this.currentTime
}
if (this.isPlaying) {
this.animationFrameId = requestAnimationFrame(updateTime)
}
}
this.animationFrameId = requestAnimationFrame(updateTime)
},
stopTimeUpdate() {
if (this.animationFrameId) {
cancelAnimationFrame(this.animationFrameId)
this.animationFrameId = null
}
},
resetPlayer() {
this.isPlaying = false
this.currentTime = 0
this.stopTimeUpdate()
this.thumbnails = []
},
formatTimeSimple(seconds) {
const secs = Math.floor(seconds)
const cs = Math.floor((seconds - secs) * 100)
// Ajouter le numéro de frame pour plus de précision
const frame = this.getCurrentFrame()
return `${secs}:${cs < 10 ? '0' : ''}${cs} (f:${frame})`
}
},
beforeUnmount() {
this.stopTimeUpdate()
if (this.videoElement) {
this.videoElement.pause()
this.videoElement.src = ''
this.videoElement = null
}
// Supprimer l'écouteur d'événement lors du démontage du composant
if (this.keyboardListener) {
document.removeEventListener('keydown', this.keyboardListener);
}
// Désabonner de l'écoute des changements dans le store
if (this.unsubscribeTimeUpdate) {
this.unsubscribeTimeUpdate()
}
}
}
</script>
<style scoped>
.timeline-section {
padding-top: 25px;
width: 100%;
}
.timeline-container {
display: flex;
align-items: center;
gap: 20px;
height: 100%;
}
.controls {
display: flex;
align-items: center;
}
.play-pause-btn {
width: 40px;
height: 40px;
background: transparent;
border: none;
color: white;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
}
.video-timeline {
flex-grow: 1;
position: relative;
}
.timeline-track {
position: relative;
height: 50px;
}
.frames-container {
display: flex;
width: 100%;
height: 100%;
border-radius: 8px;
overflow: hidden;
}
.frame {
flex: 1;
height: 100%;
background-size: cover;
background-position: center;
border-right: 2px solid black;
}
.frame:last-child {
border-right: none;
}
.time-marker {
position: absolute;
bottom: 0;
transform: translateX(-50%);
z-index: 10;
display: flex;
flex-direction: column;
align-items: center;
}
.time-indicator {
color: white;
padding: 2px 6px;
border-radius: 4px;
font-size: 12px;
margin-bottom: 4px;
white-space: nowrap;
}
.marker-head {
width: 6px;
height: 3px;
background: white;
}
.marker-line {
width: 2px;
height: 50px;
background: white;
}
.timeline-slider {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
z-index: 5;
}
.timeline-tools {
width: 50px;
height: 50px;
}
.annotation-marker {
position: absolute;
bottom: 0;
transform: translateX(-50%);
z-index: 8;
cursor: pointer;
}
.annotation-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background-color: white;
margin-bottom: 2px;
}
</style> 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182<template>
<div class="video-progress">
<div
class="timeline-bar"
ref="timelineBar"
@click="handleTimelineClick"
>
<div
class="progress-indicator"
:style="{ left: `${(currentTime / duration) * 100}%` }"
></div>
</div>
<div class="time-display">
{{ formatTime(currentTime) }} / {{ formatTime(duration) }}
</div>
</div>
</template>
<script>
export default {
name: 'VideoProgressTimeline',
props: {
duration: {
type: Number,
required: true
},
currentTime: {
type: Number,
required: true
}
},
methods: {
handleTimelineClick(event) {
const rect = this.$refs.timelineBar.getBoundingClientRect()
const clickPosition = event.clientX - rect.left
const percentage = clickPosition / rect.width
const newTime = this.duration * percentage
this.$emit('seek', newTime)
},
formatTime(seconds) {
const minutes = Math.floor(seconds / 60)
const remainingSeconds = Math.floor(seconds % 60)
return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}
}
}
</script>
<style scoped>
.video-progress {
display: flex;
flex-direction: column;
gap: 8px;
}
.timeline-bar {
height: 8px;
background: #666666;
border-radius: 4px;
position: relative;
cursor: pointer;
}
.progress-indicator {
position: absolute;
width: 12px;
height: 12px;
background: #4CAF50;
border-radius: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.time-display {
color: #ffffff;
font-size: 0.875rem;
text-align: center;
}
</style> 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852<template>
<div class="video-section">
<tool-bar
:current-tool="currentTool"
@tool-selected="selectTool"
/>
<div class="video-container" ref="container">
<div class="video-wrapper">
<video
ref="videoRef"
class="video-element"
crossorigin="anonymous"
muted
></video>
</div>
<div class="canvas-wrapper">
<v-stage
ref="stage"
:config="stageConfig"
@mousedown="handleMouseDown"
@mousemove="handleMouseMove"
@mouseup="handleMouseUp"
class="canvas-overlay"
>
<v-layer ref="layer">
<!-- Fond transparent explicite -->
<v-rect
:config="{
x: position.x,
y: position.y,
width: imageWidth,
height: imageHeight,
fill: 'transparent'
}"
/>
<!-- Lignes de guidage -->
<v-line
v-if="mousePosition.x !== null && isInsideImage(mousePosition)"
:config="{
points: [
position.x, mousePosition.y,
position.x + imageWidth, mousePosition.y
],
stroke: '#ffffff',
strokeWidth: 1,
dash: [5, 5],
opacity: 0.5
}"
/>
<v-line
v-if="mousePosition.y !== null && isInsideImage(mousePosition)"
:config="{
points: [
mousePosition.x, position.y,
mousePosition.x, position.y + imageHeight
],
stroke: '#ffffff',
strokeWidth: 1,
dash: [5, 5],
opacity: 0.5
}"
/>
<!-- Rectangle en cours de dessin -->
<v-rect
v-if="isDrawing && currentTool === 'rectangle'"
:config="{
x: rectangleStart.x,
y: rectangleStart.y,
width: rectangleSize.width,
height: rectangleSize.height,
stroke: getObjectColor(annotationStore.selectedObjectId),
strokeWidth: 1,
fill: null,
dash: []
}"
/>
<!-- Rectangles sauvegardés -->
<v-rect
v-for="rect in rectangles"
:key="rect.id"
:config="{
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
stroke: selectedId === rect.id ? '#FFD700' : rect.color,
strokeWidth: selectedId === rect.id ? 3 : (rect.objectId === annotationStore.selectedObjectId ? 2 : 1),
fill: null,
dash: rect.type === 'proxy' ? [5, 5] : [],
id: rect.id,
objectId: rect.objectId
}"
@mousedown="handleShapeMouseDown($event, rect.id)"
/>
<!-- Halo de sélection pour le rectangle sélectionné -->
<v-rect
v-if="selectedId && rectangles.find(r => r.id === selectedId)"
:key="`halo-${selectedId}`"
:config="{
x: rectangles.find(r => r.id === selectedId).x - 3,
y: rectangles.find(r => r.id === selectedId).y - 3,
width: rectangles.find(r => r.id === selectedId).width + 6,
height: rectangles.find(r => r.id === selectedId).height + 6,
stroke: '#FFD700',
strokeWidth: 1,
fill: null,
dash: [6, 6],
opacity: 0.6,
listening: false
}"
/>
<!-- Poignées de redimensionnement pour le rectangle sélectionné -->
<template v-if="selectedId && currentTool === 'arrow'">
<v-circle
v-for="handle in getResizeHandles()"
:key="handle.position"
:config="{
x: handle.x,
y: handle.y,
radius: 4,
fill: 'white',
stroke: '#4CAF50',
strokeWidth: 1,
draggable: true
}"
@dragmove="handleResize($event, handle.position)"
/>
</template>
<!-- Points existants -->
<v-group
v-for="point in points"
:key="point.id"
:config="{
x: point.x,
y: point.y,
objectId: point.objectId,
listening: true,
id: point.id
}"
@mousedown="handlePointClick(point.id, $event)"
>
<!-- Halo de sélection pour le point sélectionné -->
<v-circle
v-if="selectedId === point.id"
:config="{
radius: 12,
fill: 'transparent',
stroke: '#FFD700',
strokeWidth: 2,
dash: [4, 4],
opacity: 0.8
}"
/>
<v-circle
:config="{
radius: selectedId === point.id ? 7 : (point.objectId === annotationStore.selectedObjectId ? 6 : 5),
fill: point.color,
stroke: selectedId === point.id ? '#FFD700' : 'white',
strokeWidth: selectedId === point.id ? 3 : (point.objectId === annotationStore.selectedObjectId ? 2 : 1)
}"
/>
<v-line
:config="{
points: [-2, 0, 2, 0],
stroke: selectedId === point.id ? '#FFD700' : 'white',
strokeWidth: selectedId === point.id ? 2 : 1
}"
/>
<v-line
v-if="point.type === 'positive'"
:config="{
points: [0, -2, 0, 2],
stroke: selectedId === point.id ? '#FFD700' : 'white',
strokeWidth: selectedId === point.id ? 2 : 1
}"
/>
</v-group>
<!-- Masques de segmentation -->
<v-shape
v-for="annotation in maskedAnnotations"
:key="`mask-${annotation.id}`"
:config="{
sceneFunc: (context, shape) => drawMask(context, shape, annotation),
fill: annotation.objectId === annotationStore.selectedObjectId ?
`${getObjectColor(annotation.objectId)}88` :
`${getObjectColor(annotation.objectId)}44`,
stroke: getObjectColor(annotation.objectId),
strokeWidth: annotation.objectId === annotationStore.selectedObjectId ? 2 : 1,
opacity: 0.8,
listening: true,
id: annotation.id
}"
@mousedown="handleMaskClick(annotation.id)"
/>
<!-- Bounding boxes de tous les objets -->
<v-rect
v-for="bbox in allBoundingBoxes"
v-show="showAllBoundingBoxes && bbox"
:key="bbox.id"
:config="{
x: bbox.x,
y: bbox.y,
width: bbox.width,
height: bbox.height,
stroke: bbox.color,
strokeWidth: bbox.objectId === annotationStore.selectedObjectId ? 2 : 1,
fill: null,
dash: [4, 2], // Trait pointillé uniforme pour tous les rectangles
opacity: 0.8,
listening: false // Ne pas intercepter les clics sur les bbox d'affichage
}"
/>
</v-layer>
</v-stage>
</div>
</div>
</div>
</template>
<script>
import { useVideoStore } from '@/stores/videoStore'
import { useAnnotationStore } from '@/stores/annotationStore'
import ToolBar from './tools/ToolBar.vue'
/*
FONCTIONNALITÉS DES BOUNDING BOXES :
1. Affichage automatique des bounding boxes pour tous les objets sur chaque frame :
- Annotations en cours : rectangles et masques créés dans cette session
- Objet sélectionné : trait plus épais pour mise en évidence
2. Différenciation visuelle :
- Annotations rectangles : trait continu []
- Annotations masques : trait pointillé court [- - -]
- Couleurs : selon la couleur de l'objet définie
3. Contrôles clavier :
- Touche 'b' : Basculer l'affichage des bounding boxes (on/off)
- Touche 'd' : Afficher les informations de débogage dans la console
- Par défaut : affichage activé
4. Sources de données :
- Store d'annotations (this.annotationStore) : annotations créées en temps réel
5. Stockage des bounding boxes :
- Rectangles : coordonnées directes (x, y, width, height)
- Masques de segmentation : bbox calculée à partir des points ou du masque
6. Débogage :
- Appel automatique de debugBoundingBoxes() à chaque changement de frame
- Informations détaillées sur les annotations trouvées
*/
export default {
name: 'VideoSection',
components: {
ToolBar
},
props: {
selectedObjectId: {
type: String,
default: null
}
},
setup() {
const videoStore = useVideoStore()
const annotationStore = useAnnotationStore()
return { videoStore, annotationStore }
},
data() {
return {
videoElement: null,
imageWidth: 0,
imageHeight: 0,
position: { x: 0, y: 0 },
stageConfig: {
width: 0,
height: 0
},
currentTool: 'arrow',
isDrawing: false,
rectangleStart: { x: 0, y: 0 },
rectangleSize: { width: 0, height: 0 },
mousePosition: { x: null, y: null },
selectedId: null,
isDragging: false,
dragStartPos: { x: 0, y: 0 },
resizing: false,
resizeTimeout: null,
animationId: null,
currentFrameNumber: 0,
originalVideoPath: null,
proxyVideoPath: null,
isUsingProxy: true,
originalVideoDimensions: { width: 0, height: 0 },
maskCache: {},
showAllBoundingBoxes: true, // Nouvelle propriété pour contrôler l'affichage des bbox
}
},
mounted() {
// Réactiver l'élément vidéo
this.videoElement = this.$refs.videoRef
this.videoElement.muted = true
this.videoElement.addEventListener('loadedmetadata', this.handleVideoLoaded)
this.videoElement.addEventListener('timeupdate', this.updateCurrentFrame)
// S'abonner aux changements de vidéo dans le store
this.subscribeToVideoStore()
window.addEventListener('resize', this.handleWindowResize)
window.addEventListener('keydown', this.handleKeyDown)
},
beforeUnmount() {
window.removeEventListener('resize', this.handleWindowResize)
window.removeEventListener('keydown', this.handleKeyDown)
if (this.videoElement) {
this.videoElement.removeEventListener('loadedmetadata', this.handleVideoLoaded)
this.videoElement.pause()
}
this.stopAnimation()
// Supprimer l'écouteur d'événement
this.videoElement.removeEventListener('timeupdate', this.updateCurrentFrame)
},
computed: {
availableObjects() {
return Object.values(this.annotationStore.objects)
},
hasSelectedObject() {
return !!this.annotationStore.selectedObjectId
},
rectangles() {
const frameAnnotations = this.annotationStore.getAnnotationsForFrame(this.currentFrameNumber) || []
// Convertir les annotations en rectangles pour l'affichage
return frameAnnotations
.filter(annotation => annotation && annotation.type === 'rectangle')
.map(annotation => {
const object = this.annotationStore.objects[annotation.objectId]
const color = object ? object.color : '#4CAF50'
// Convertir les coordonnées originales en coordonnées d'affichage
const displayX = this.position.x + (annotation.x / this.scaleX)
const displayY = this.position.y + (annotation.y / this.scaleY)
const displayWidth = annotation.width / this.scaleX
const displayHeight = annotation.height / this.scaleY
return {
id: annotation.id,
objectId: annotation.objectId,
x: displayX,
y: displayY,
width: displayWidth,
height: displayHeight,
color: color
}
})
},
points() {
const frameAnnotations = this.annotationStore.getAnnotationsForFrame(this.currentFrameNumber) || []
// Points directs de type "point" (nouveau système)
const directPoints = frameAnnotations
.filter(annotation => annotation && annotation.type === 'point')
.map(annotation => ({
id: annotation.id,
objectId: annotation.objectId,
x: this.position.x + (annotation.x / this.scaleX),
y: this.position.y + (annotation.y / this.scaleY),
type: annotation.pointType,
color: this.getObjectColor(annotation.objectId),
isDirect: true
}))
// Points des annotations de type "mask" qui contiennent des points (ancien système)
const annotationPoints = frameAnnotations
.filter(annotation => annotation && annotation.type === 'mask' && annotation.points)
.flatMap(annotation => annotation.points.map(point => ({
id: `${annotation.id}-point-${point.x}-${point.y}`,
objectId: annotation.objectId,
x: this.position.x + (point.x / this.scaleX),
y: this.position.y + (point.y / this.scaleY),
type: point.type,
color: this.getObjectColor(annotation.objectId),
fromAnnotation: annotation.id
})))
// Points temporaires (ne devrait plus être utilisé mais gardé pour sécurité)
const tempPoints = (this.annotationStore.temporaryPoints || []).map(point => ({
id: `temp-point-${point.id}`,
objectId: point.objectId,
x: this.position.x + (point.x / this.scaleX),
y: this.position.y + (point.y / this.scaleY),
type: point.pointType,
color: this.getObjectColor(point.objectId),
isTemporary: true
}))
return [...directPoints, ...annotationPoints, ...tempPoints]
},
scaleX() {
if (this.originalVideoDimensions.width && this.imageWidth) {
return this.originalVideoDimensions.width / this.imageWidth
}
if (!this.videoElement || !this.imageWidth) return 1
return this.videoElement.videoWidth / this.imageWidth
},
scaleY() {
if (this.originalVideoDimensions.height && this.imageHeight) {
return this.originalVideoDimensions.height / this.imageHeight
}
if (!this.videoElement || !this.imageHeight) return 1
return this.videoElement.videoHeight / this.imageHeight
},
maskedAnnotations() {
const frameAnnotations = this.annotationStore.getAnnotationsForFrame(this.currentFrameNumber) || [];
return frameAnnotations.filter(annotation => annotation && annotation.mask && annotation.maskImageSize);
},
// Nouvelle computed property pour toutes les bounding boxes
allBoundingBoxes() {
// Temporairement désactivé pour isoler l'erreur
return []
// Le code original sera restauré une fois l'erreur identifiée
/*
const frameAnnotations = this.annotationStore.getAnnotationsForFrame(this.currentFrameNumber) || []
const boundingBoxes = []
// 1. BOUNDING BOXES DES ANNOTATIONS EN COURS (STORE D'ANNOTATIONS)
frameAnnotations.forEach(annotation => {
if (!annotation) return // Vérifier que l'annotation existe
const object = this.annotationStore.objects[annotation.objectId]
const color = object ? object.color : '#CCCCCC'
const objectName = object ? object.name : `Objet ${annotation.objectId}`
if (annotation.type === 'rectangle') {
// Pour les rectangles, utiliser directement leurs coordonnées
const displayX = this.position.x + (annotation.x / this.scaleX)
const displayY = this.position.y + (annotation.y / this.scaleY)
const displayWidth = annotation.width / this.scaleX
const displayHeight = annotation.height / this.scaleY
boundingBoxes.push({
id: `bbox-${annotation.id}`,
objectId: annotation.objectId,
x: displayX,
y: displayY,
width: displayWidth,
height: displayHeight,
color: color,
name: objectName,
type: 'rectangle',
annotationId: annotation.id,
source: 'current' // Annotations en cours
})
} else if (annotation.type === 'mask' && annotation.mask) {
// Pour les masques, calculer la bounding box ou utiliser celle stockée
let bbox = null
if (annotation.bbox && annotation.bbox.output) {
// Si la bbox est déjà stockée, l'utiliser
bbox = annotation.bbox.output
} else if (annotation.bbox) {
// Si c'est juste bbox sans output
bbox = annotation.bbox
} else {
// Sinon, essayer de calculer une bbox approximative à partir des dimensions du masque
// Cette méthode n'est pas parfaite mais donne une approximation
const maskSize = annotation.maskImageSize || { width: this.originalVideoDimensions.width, height: this.originalVideoDimensions.height }
// Pour une approximation, on peut supposer que le masque couvre une région significative
// En attendant une vraie bbox calculée côté serveur
bbox = {
x: Math.round(maskSize.width * 0.1), // 10% du bord gauche
y: Math.round(maskSize.height * 0.1), // 10% du bord haut
width: Math.round(maskSize.width * 0.8), // 80% de la largeur
height: Math.round(maskSize.height * 0.8) // 80% de la hauteur
}
}
if (bbox) {
// Convertir les coordonnées originales en coordonnées d'affichage
const displayX = this.position.x + (bbox.x / this.scaleX)
const displayY = this.position.y + (bbox.y / this.scaleY)
const displayWidth = bbox.width / this.scaleX
const displayHeight = bbox.height / this.scaleY
boundingBoxes.push({
id: `bbox-${annotation.id}`,
objectId: annotation.objectId,
x: displayX,
y: displayY,
width: displayWidth,
height: displayHeight,
color: color,
name: objectName,
type: 'mask',
annotationId: annotation.id,
source: 'current' // Annotations en cours
})
}
}
})
// Filtrer les bounding boxes invalides avant de retourner
return boundingBoxes.filter(bbox => bbox && bbox.type && bbox.id)
*/
},
},
methods: {
subscribeToVideoStore() {
const videoStore = useVideoStore()
// Observer les changements dans le store
this.$watch(
() => videoStore.selectedVideo,
(newVideo) => {
if (newVideo) {
console.log('Nouvelle vidéo sélectionnée dans VideoSection:', newVideo)
this.loadVideo(newVideo.path)
}
},
{ immediate: true }
)
// Observer les changements de temps dans la timeline
this.$watch(
() => videoStore.currentTime,
(newTime) => {
if (this.videoElement && newTime !== undefined) {
// Seulement mettre à jour si la différence est significative
if (Math.abs(this.videoElement.currentTime - newTime) > 0.05) {
this.videoElement.currentTime = newTime
}
}
}
)
// Observer l'état de lecture (play/pause)
this.$watch(
() => videoStore.isPlaying,
(isPlaying) => {
// console.log('État de lecture changé dans VideoSection:', isPlaying)
if (isPlaying) {
this.playVideo()
} else {
this.pauseVideo()
}
}
)
},
loadVideo(videoPath) {
if (!videoPath) return
// Arrêter toute animation en cours
this.stopAnimation()
this.originalVideoPath = videoPath
// Si l'élément vidéo est commenté, ne pas essayer de charger la vidéo
if (!this.videoElement) {
console.log("Mode test: élément vidéo non disponible, simulation uniquement")
// Simuler des dimensions pour le test
this.imageWidth = 640
this.imageHeight = 360
this.updateDimensions()
return
}
// Si c'est une URL blob (vidéo uploadée), charger directement sans proxy
if (videoPath.startsWith('blob:')) {
console.log("Chargement direct d'une vidéo uploadée (blob URL)")
this.videoElement.src = videoPath
this.videoElement.load()
return
}
// Si c'est un fichier média par défaut depuis les assets, le charger directement
if (videoPath.includes('/assets/') || videoPath.includes('assets/') ||
videoPath.includes('.jpg') || videoPath.includes('.png') ||
videoPath.includes('.jpeg') || videoPath.includes('.mp4') ||
videoPath.includes('.webm') || videoPath.includes('.mov')) {
console.log("Chargement direct d'un fichier média par défaut")
this.videoElement.src = videoPath
this.videoElement.load()
return
}
// Pour les fichiers locaux, utiliser le système de proxy existant
this.getOriginalVideoDimensions(videoPath)
.then(dimensions => {
console.log("Dimensions de la vidéo originale:", dimensions.width, "x", dimensions.height)
// Stocker les dimensions originales pour les utiliser dans les calculs de coordonnées
this.originalVideoDimensions = dimensions
// Vérifier si un proxy existe déjà ou en créer un
this.createOrLoadProxy(videoPath)
.then(proxyPath => {
this.proxyVideoPath = proxyPath
// Charger le proxy si l'option est activée, sinon charger l'original
const sourceToLoad = this.isUsingProxy ? proxyPath : videoPath
this.videoElement.src = sourceToLoad
this.videoElement.load()
})
.catch(err => {
console.error("Erreur lors de la création du proxy:", err)
// En cas d'erreur, charger la vidéo originale
this.videoElement.src = videoPath
this.videoElement.load()
})
})
.catch(err => {
console.error("Erreur lors de l'obtention des dimensions de la vidéo originale:", err)
// Continuer avec le chargement normal
this.videoElement.src = videoPath
this.videoElement.load()
})
},
async getOriginalVideoDimensions(videoPath) {
return new Promise((resolve, reject) => {
// Créer un élément vidéo temporaire pour obtenir les dimensions
const tempVideo = document.createElement('video')
tempVideo.style.display = 'none'
// Configurer les gestionnaires d'événements
tempVideo.onloadedmetadata = () => {
const dimensions = {
width: tempVideo.videoWidth,
height: tempVideo.videoHeight
}
// Nettoyer
document.body.removeChild(tempVideo)
resolve(dimensions)
}
tempVideo.onerror = (error) => {
// Nettoyer
if (document.body.contains(tempVideo)) {
document.body.removeChild(tempVideo)
}
reject(error)
}
// Ajouter l'élément au DOM et charger la vidéo
document.body.appendChild(tempVideo)
tempVideo.src = videoPath
})
},
async createOrLoadProxy(originalPath) {
// Générer un nom de fichier pour le proxy
const proxyPath = this.generateProxyPath(originalPath)
// Vérifier si le proxy existe déjà
const proxyExists = await this.checkIfFileExists(proxyPath)
if (proxyExists) {
console.log("Proxy vidéo existant trouvé:", proxyPath)
return proxyPath
}
// Créer un nouveau proxy
console.log("Création d'un nouveau proxy vidéo...")
return this.createVideoProxy(originalPath, proxyPath)
},
generateProxyPath(originalPath) {
// Exemple: transformer "/videos/original.mp4" en "/videos/original_proxy.mp4"
const pathParts = originalPath.split('.')
const extension = pathParts.pop()
return `${pathParts.join('.')}_proxy.${extension}`
},
async checkIfFileExists() {
// DÉSACTIVÉ - utilisation de vidéo statique dans assets
console.log("Vérification de fichier désactivée - utilisation de vidéo statique");
return true; // Toujours vrai pour la vidéo statique
},
async createVideoProxy(originalPath) {
// DÉSACTIVÉ - utilisation de vidéo statique dans assets
console.log("Création de proxy désactivée - utilisation de vidéo statique");
return originalPath; // Retourner le chemin original
},
toggleProxyMode() {
this.isUsingProxy = !this.isUsingProxy
// Sauvegarder la position actuelle
const currentTime = this.videoElement.currentTime
// Charger la vidéo appropriée
this.videoElement.src = this.isUsingProxy ? this.proxyVideoPath : this.originalVideoPath
this.videoElement.load()
// Restaurer la position après le chargement
this.videoElement.addEventListener('loadedmetadata', () => {
this.videoElement.currentTime = currentTime
}, { once: true })
},
handleVideoLoaded() {
console.log('Vidéo chargée, dimensions:', this.videoElement.videoWidth, 'x', this.videoElement.videoHeight)
// Vérifier que les dimensions sont valides
if (!this.videoElement.videoWidth || !this.videoElement.videoHeight) {
console.error('Dimensions de vidéo invalides après chargement')
return
}
// Stocker les dimensions si elles ne sont pas déjà définies
if (!this.originalVideoDimensions.width || !this.originalVideoDimensions.height) {
this.originalVideoDimensions = {
width: this.videoElement.videoWidth,
height: this.videoElement.videoHeight
}
}
// Ajouter un log pour indiquer si c'est le proxy ou l'original
const sourceType = this.isUsingProxy ? "proxy" : "originale"
console.log(`Vidéo ${sourceType} chargée. Dimensions d'affichage:`,
this.videoElement.videoWidth, 'x', this.videoElement.videoHeight)
this.initializeView()
// Démarrer l'animation pour le rendu fluide
this.startAnimation()
},
playVideo() {
if (!this.videoElement) {
console.log("Mode test: élément vidéo non disponible")
return
}
this.videoElement.play()
this.startAnimation()
},
pauseVideo() {
if (!this.videoElement) {
console.log("Mode test: élément vidéo non disponible")
return
}
this.videoElement.pause()
},
startAnimation() {
// Arrêter l'animation existante si elle existe
this.stopAnimation()
// Démarrer l'animation
this.animationId = requestAnimationFrame(this.animate)
},
stopAnimation() {
if (this.animationId) {
cancelAnimationFrame(this.animationId)
this.animationId = null
}
},
initializeView() {
this.$nextTick(() => {
this.updateDimensions()
})
},
handleWindowResize() {
if (this.resizeTimeout) {
clearTimeout(this.resizeTimeout)
}
this.resizeTimeout = setTimeout(() => {
this.updateDimensions()
}, 100)
},
updateDimensions() {
const container = this.$refs.container
if (!container) return
const containerWidth = container.clientWidth
const containerHeight = container.clientHeight
// Obtenir les dimensions de la vidéo avec des valeurs par défaut
let videoWidth = 0
let videoHeight = 0
if (this.videoElement && this.videoElement.videoWidth && this.videoElement.videoHeight) {
videoWidth = this.videoElement.videoWidth
videoHeight = this.videoElement.videoHeight
} else if (this.originalVideoDimensions.width && this.originalVideoDimensions.height) {
videoWidth = this.originalVideoDimensions.width
videoHeight = this.originalVideoDimensions.height
} else if (this.imageWidth && this.imageHeight) {
videoWidth = this.imageWidth
videoHeight = this.imageHeight
} else {
// Valeurs par défaut si aucune dimension n'est disponible
videoWidth = 640
videoHeight = 480
}
// Vérifier que les dimensions sont valides
if (!videoWidth || !videoHeight || videoWidth <= 0 || videoHeight <= 0) {
console.warn('Dimensions vidéo invalides, utilisation de valeurs par défaut')
videoWidth = 640
videoHeight = 480
}
const videoRatio = videoWidth / videoHeight
let width = containerWidth
let height = width / videoRatio
if (height > containerHeight) {
height = containerHeight
width = height * videoRatio
}
// S'assurer que les dimensions finales sont valides
if (isNaN(width) || isNaN(height) || width <= 0 || height <= 0) {
console.error('Dimensions calculées invalides, utilisation des dimensions du conteneur')
width = containerWidth || 640
height = containerHeight || 480
}
this.stageConfig.width = containerWidth
this.stageConfig.height = containerHeight
this.imageWidth = width
this.imageHeight = height
this.position = {
x: Math.floor((containerWidth - width) / 2),
y: Math.floor((containerHeight - height) / 2)
}
console.log('Dimensions mises à jour:', { videoWidth, videoHeight, displayWidth: width, displayHeight: height })
// Forcer une mise à jour du canvas
if (this.$refs.layer) {
const layer = this.$refs.layer.getNode();
layer.batchDraw();
}
},
selectTool(tool) {
this.currentTool = tool
},
handleMouseDown(e) {
if (e.evt.button !== 0) return
const stage = this.$refs.stage.getStage()
const pointerPos = stage.getPointerPosition()
if (!this.isInsideImage(pointerPos)) return
if (this.currentTool === 'arrow' && this.selectedId) {
const handles = this.getResizeHandles()
const clickedHandle = handles.find(handle => {
const dx = handle.x - pointerPos.x
const dy = handle.y - pointerPos.y
return Math.sqrt(dx * dx + dy * dy) <= 5
})
if (clickedHandle) {
this.resizing = true
return
}
}
// Sélection des rectangles (fonctionne avec tous les outils)
const clickedRect = this.rectangles.find(rect =>
pointerPos.x >= rect.x &&
pointerPos.x <= rect.x + rect.width &&
pointerPos.y >= rect.y &&
pointerPos.y <= rect.y + rect.height
)
if (clickedRect) {
this.selectedId = clickedRect.id
if (this.currentTool === 'arrow') {
this.isDragging = true
this.dragStartPos = pointerPos
}
console.log('Selected rectangle:', this.selectedId)
return
}
// Sélection des points (fonctionne avec tous les outils)
const clickedPoint = this.points.find(point => {
const dx = point.x - pointerPos.x
const dy = point.y - pointerPos.y
return Math.sqrt(dx * dx + dy * dy) <= 8 // Augmenter la zone de détection
})
if (clickedPoint) {
this.selectedId = clickedPoint.id
if (this.currentTool === 'arrow') {
this.isDragging = true
this.dragStartPos = pointerPos
}
console.log('Selected point:', this.selectedId)
return
}
// Déselectionner si aucun élément n'est cliqué
this.selectedId = null
switch(this.currentTool) {
case 'rectangle':
if (!this.annotationStore.selectedObjectId) {
this.annotationStore.addObject()
}
this.isDrawing = true
this.rectangleStart = {
x: pointerPos.x,
y: pointerPos.y
}
this.rectangleSize = { width: 0, height: 0 }
break
case 'positive':
this.addPoint(pointerPos, 'positive')
break
case 'negative':
this.addPoint(pointerPos, 'negative')
break
}
},
handleMouseMove() {
const stage = this.$refs.stage.getStage();
const pointerPos = stage.getPointerPosition();
this.mousePosition = pointerPos;
if (this.isDragging && this.selectedId && this.currentTool === 'arrow') {
const dx = pointerPos.x - this.dragStartPos.x
const dy = pointerPos.y - this.dragStartPos.y
const selectedRect = this.rectangles.find(r => r.id === this.selectedId)
if (selectedRect) {
selectedRect.x += dx
selectedRect.y += dy
}
const selectedPoint = this.points.find(p => p.id === this.selectedId)
if (selectedPoint) {
selectedPoint.x += dx
selectedPoint.y += dy
}
this.dragStartPos = pointerPos
return
}
if (!this.isDrawing || this.currentTool !== 'rectangle') return;
this.rectangleSize = {
width: pointerPos.x - this.rectangleStart.x,
height: pointerPos.y - this.rectangleStart.y
};
},
async handleMouseUp() {
if (this.resizing) {
this.resizing = false;
return;
}
if (this.isDragging) {
this.isDragging = false;
// Mettre à jour la position dans le store après le drag
if (this.selectedId) {
const selectedRect = this.rectangles.find(r => r.id === this.selectedId)
if (selectedRect) {
// Convertir les coordonnées d'affichage en coordonnées réelles
const realX = Math.round((selectedRect.x - this.position.x) * this.scaleX)
const realY = Math.round((selectedRect.y - this.position.y) * this.scaleY)
const realWidth = Math.round(selectedRect.width * this.scaleX)
const realHeight = Math.round(selectedRect.height * this.scaleY)
// Mettre à jour l'annotation dans le store
this.annotationStore.updateAnnotation(this.currentFrameNumber, this.selectedId, {
x: realX,
y: realY,
width: realWidth,
height: realHeight
})
}
const selectedPoint = this.points.find(p => p.id === this.selectedId)
if (selectedPoint) {
// Convertir les coordonnées d'affichage en coordonnées réelles
const realX = Math.round((selectedPoint.x - this.position.x) * this.scaleX)
const realY = Math.round((selectedPoint.y - this.position.y) * this.scaleY)
// Mettre à jour l'annotation dans le store
this.annotationStore.updateAnnotation(this.currentFrameNumber, this.selectedId, {
x: realX,
y: realY
})
}
}
return;
}
if (!this.isDrawing || this.currentTool !== 'rectangle') return;
// Normaliser les coordonnées du rectangle pour s'assurer que x, y est le coin supérieur gauche
// et que width, height sont positifs
let normalizedRect = this.normalizeRectangle(
this.rectangleStart.x,
this.rectangleStart.y,
this.rectangleSize.width,
this.rectangleSize.height
);
const relativeStart = {
x: normalizedRect.x - this.position.x,
y: normalizedRect.y - this.position.y
};
// Utiliser les dimensions réelles de la vidéo originale, pas du proxy
const originalRect = {
x: Math.round(relativeStart.x * this.scaleX),
y: Math.round(relativeStart.y * this.scaleY),
width: Math.round(normalizedRect.width * this.scaleX),
height: Math.round(normalizedRect.height * this.scaleY)
};
// Vérifier s'il existe déjà des annotations pour cet objet sur cette frame
const existingAnnotations = this.annotationStore.getAnnotationsForFrame(this.currentFrameNumber)
.filter(annotation => annotation.objectId === this.annotationStore.selectedObjectId);
// Si des annotations existent déjà, les supprimer avant d'ajouter la nouvelle
if (existingAnnotations.length > 0) {
console.log(`Suppression de ${existingAnnotations.length} annotations existantes pour l'objet ${this.annotationStore.selectedObjectId}`);
existingAnnotations.forEach(annotation => {
this.annotationStore.removeAnnotation(this.currentFrameNumber, annotation.id);
});
}
// Créer l'annotation avec les coordonnées réelles
const annotation = {
objectId: this.annotationStore.selectedObjectId,
type: 'rectangle',
x: originalRect.x,
y: originalRect.y,
width: originalRect.width,
height: originalRect.height
};
// Ajouter l'annotation au store
const annotationId = this.annotationStore.addAnnotation(this.currentFrameNumber, annotation);
// Log détaillé pour le mode annotation uniquement
console.log('Rectangle ajouté à la frame', this.currentFrameNumber, 'avec ID:', annotationId, ':', annotation);
console.log('État actuel des annotations:', JSON.parse(JSON.stringify(this.annotationStore.frameAnnotations)));
this.isDrawing = false;
this.rectangleSize = { width: 0, height: 0 };
},
// Ajouter cette nouvelle méthode pour normaliser les coordonnées du rectangle
normalizeRectangle(x, y, width, height) {
// Si la largeur est négative, ajuster x et width
let newX = x;
let newWidth = width;
if (width < 0) {
newX = x + width;
newWidth = Math.abs(width);
}
// Si la hauteur est négative, ajuster y et height
let newY = y;
let newHeight = height;
if (height < 0) {
newY = y + height;
newHeight = Math.abs(height);
}
return {
x: newX,
y: newY,
width: newWidth,
height: newHeight
};
},
isInsideImage(point) {
return point.x >= this.position.x &&
point.x <= this.position.x + this.imageWidth &&
point.y >= this.position.y &&
point.y <= this.position.y + this.imageHeight
},
addPoint(pos, type) {
if (!this.annotationStore.selectedObjectId) {
this.annotationStore.addObject()
}
const relativeX = pos.x - this.position.x
const relativeY = pos.y - this.position.y
// Utiliser les dimensions réelles de la vidéo originale, pas du proxy
const imageX = Math.round(relativeX * this.scaleX)
const imageY = Math.round(relativeY * this.scaleY)
// Vérifier s'il existe des rectangles pour cet objet sur cette frame
const existingRectangles = this.annotationStore.getAnnotationsForFrame(this.currentFrameNumber)
.filter(annotation =>
annotation.objectId === this.annotationStore.selectedObjectId &&
annotation.type === 'rectangle'
);
// Si des rectangles existent, les supprimer avant d'ajouter le point
if (existingRectangles.length > 0) {
console.log(`Suppression de ${existingRectangles.length} rectangles existants pour l'objet ${this.annotationStore.selectedObjectId}`);
existingRectangles.forEach(rectangle => {
this.annotationStore.removeAnnotation(this.currentFrameNumber, rectangle.id);
});
// Supprimer également les masques associés à ces rectangles
const associatedMasks = this.annotationStore.getAnnotationsForFrame(this.currentFrameNumber)
.filter(annotation =>
annotation.objectId === this.annotationStore.selectedObjectId &&
annotation.type === 'mask' &&
(!annotation.points || annotation.points.length === 0)
);
associatedMasks.forEach(mask => {
this.annotationStore.removeAnnotation(this.currentFrameNumber, mask.id);
});
}
// Créer directement une annotation pour le point (comme pour les rectangles)
const annotation = {
objectId: this.annotationStore.selectedObjectId,
type: 'point',
x: imageX,
y: imageY,
pointType: type
};
// Ajouter l'annotation au store
const annotationId = this.annotationStore.addAnnotation(this.currentFrameNumber, annotation);
// Log détaillé
console.log('Point ajouté à la frame', this.currentFrameNumber, 'avec ID:', annotationId, ':', annotation);
console.log('État des frameAnnotations après ajout:', JSON.parse(JSON.stringify(this.annotationStore.frameAnnotations)));
},
handleKeyDown(e) {
// Raccourci pour supprimer un élément sélectionné (annotations uniquement)
// Note: Pour supprimer un objet, utiliser Ctrl+Suppr dans la liste des objets
if (e.key === 'Delete' && this.selectedId) {
console.log('Tentative de suppression de l\'élément:', this.selectedId)
// Déterminer le type d'élément sélectionné
const selectedRect = this.rectangles.find(r => r.id === this.selectedId);
const selectedPoint = this.points.find(p => p.id === this.selectedId);
if (selectedRect) {
console.log('Suppression du rectangle:', this.selectedId)
// Supprimer le rectangle
this.annotationStore.removeAnnotation(this.currentFrameNumber, this.selectedId);
// Vérifier s'il reste des annotations pour cet objet sur cette frame
this.checkAndCleanupMasks(selectedRect.objectId);
}
else if (selectedPoint) {
console.log('Suppression du point:', this.selectedId, 'Type:', selectedPoint.isDirect ? 'direct' : 'depuis annotation')
if (selectedPoint.isTemporary) {
// Supprimer un point temporaire
this.annotationStore.removeTemporaryPoint(selectedPoint.id.replace('temp-point-', ''));
} else if (selectedPoint.isDirect) {
// Nouveau système : point direct - supprimer directement l'annotation
this.annotationStore.removeAnnotation(this.currentFrameNumber, this.selectedId);
console.log('Point direct supprimé')
} else {
// Ancien système : point d'une annotation existante
const annotationId = selectedPoint.fromAnnotation;
const annotation = this.annotationStore.getAnnotation(this.currentFrameNumber, annotationId);
if (annotation && annotation.points) {
// Filtrer les points pour retirer celui qui est sélectionné
const pointKey = selectedPoint.id.split('-point-')[1]; // Récupérer les coordonnées du point
const [pointX, pointY] = pointKey.split('-').map(Number);
const updatedPoints = annotation.points.filter(p =>
!(p.x === pointX && p.y === pointY)
);
if (updatedPoints.length > 0) {
// Mettre à jour l'annotation avec les points restants
this.annotationStore.updateAnnotation(this.currentFrameNumber, annotationId, {
points: updatedPoints
});
console.log('Point retiré de l\'annotation, points restants:', updatedPoints.length)
} else {
// Si plus aucun point, supprimer l'annotation complètement
this.annotationStore.removeAnnotation(this.currentFrameNumber, annotationId);
console.log('Annotation complètement supprimée (plus de points)')
}
// Vérifier s'il reste des annotations pour cet objet sur cette frame
this.checkAndCleanupMasks(selectedPoint.objectId);
}
}
} else {
console.log('Aucun élément trouvé avec l\'ID:', this.selectedId)
}
this.selectedId = null;
console.log('Element deleted');
}
// Raccourci "v" supprimé - Les points sont maintenant sauvegardés directement
// Raccourci Escape supprimé - Plus de points temporaires à annuler
// Raccourci pour basculer l'affichage des bounding boxes (touche 'b')
if (e.key === 'b' || e.key === 'B') {
e.preventDefault();
this.toggleBoundingBoxes();
}
// Raccourci pour déboguer les bounding boxes (touche 'd')
if (e.key === 'd' || e.key === 'D') {
e.preventDefault();
this.debugBoundingBoxes();
}
// Navigation frame par frame avec les flèches
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
e.preventDefault() // Empêcher le défilement de la page
// Calculer la nouvelle frame
const frameRate = this.annotationStore.currentSession.frameRate || 30
const currentFrame = this.currentFrameNumber
const newFrame = e.key === 'ArrowLeft' ? Math.max(0, currentFrame - 1) : currentFrame + 1
// Calculer le nouveau temps basé sur la frame
const newTime = newFrame / frameRate
// Mettre à jour le temps dans le store et la vidéo
this.videoStore.setCurrentTime(newTime)
if (this.videoElement) {
this.videoElement.currentTime = newTime
}
// console.log(`Navigation: Frame ${currentFrame} -> ${newFrame}, Temps: ${newTime.toFixed(3)}s`)
}
},
// Nouvelle méthode pour vérifier et nettoyer les masques orphelins
checkAndCleanupMasks(objectId) {
const frameAnnotations = this.annotationStore.getAnnotationsForFrame(this.currentFrameNumber) || [];
// Vérifier s'il reste des annotations (rectangles ou points) pour cet objet sur cette frame
const hasRemainingElements = frameAnnotations.some(annotation =>
annotation.objectId === objectId &&
(annotation.type === 'rectangle' ||
(annotation.type === 'mask' && annotation.points && annotation.points.length > 0))
);
if (!hasRemainingElements) {
// Si aucun élément ne reste, supprimer tous les masques associés à cet objet sur cette frame
const masksToRemove = frameAnnotations
.filter(annotation =>
annotation.objectId === objectId &&
annotation.type === 'mask' &&
(!annotation.points || annotation.points.length === 0)
)
.map(annotation => annotation.id);
masksToRemove.forEach(maskId => {
this.annotationStore.removeAnnotation(this.currentFrameNumber, maskId);
});
if (masksToRemove.length > 0) {
console.log(`Suppression de ${masksToRemove.length} masques orphelins pour l'objet ${objectId}`);
}
}
},
getResizeHandles() {
const rect = this.rectangles.find(r => r.id === this.selectedId)
if (!rect) return []
return [
{ position: 'nw', x: rect.x, y: rect.y },
{ position: 'ne', x: rect.x + rect.width, y: rect.y },
{ position: 'se', x: rect.x + rect.width, y: rect.y + rect.height },
{ position: 'sw', x: rect.x, y: rect.y + rect.height },
{ position: 'n', x: rect.x + rect.width/2, y: rect.y },
{ position: 'e', x: rect.x + rect.width, y: rect.y + rect.height/2 },
{ position: 's', x: rect.x + rect.width/2, y: rect.y + rect.height },
{ position: 'w', x: rect.x, y: rect.y + rect.height/2 }
]
},
handleResize(e, position) {
const rect = this.rectangles.find(r => r.id === this.selectedId)
if (!rect) return
const stage = this.$refs.stage.getStage()
const pos = stage.getPointerPosition()
const originalX = rect.x
const originalY = rect.y
const originalWidth = rect.width
const originalHeight = rect.height
let newWidth, newHeight
// Appliquer le redimensionnement selon la poignée utilisée
switch (position) {
case 'e':
rect.width = Math.max(10, pos.x - rect.x)
break
case 'w':
newWidth = originalWidth + (originalX - pos.x)
if (newWidth >= 10) {
rect.x = pos.x
rect.width = newWidth
}
break
case 'n':
newHeight = originalHeight + (originalY - pos.y)
if (newHeight >= 10) {
rect.y = pos.y
rect.height = newHeight
}
break
case 's':
rect.height = Math.max(10, pos.y - rect.y)
break
case 'nw':
if (originalWidth + (originalX - pos.x) >= 10) {
rect.x = pos.x
rect.width = originalWidth + (originalX - pos.x)
}
if (originalHeight + (originalY - pos.y) >= 10) {
rect.y = pos.y
rect.height = originalHeight + (originalY - pos.y)
}
break
case 'ne':
rect.width = Math.max(10, pos.x - rect.x)
if (originalHeight + (originalY - pos.y) >= 10) {
rect.y = pos.y
rect.height = originalHeight + (originalY - pos.y)
}
break
case 'se':
rect.width = Math.max(10, pos.x - rect.x)
rect.height = Math.max(10, pos.y - rect.y)
break
case 'sw':
if (originalWidth + (originalX - pos.x) >= 10) {
rect.x = pos.x
rect.width = originalWidth + (originalX - pos.x)
}
rect.height = Math.max(10, pos.y - rect.y)
break
}
// Convertir les coordonnées d'affichage en coordonnées réelles
const realX = Math.round((rect.x - this.position.x) * this.scaleX)
const realY = Math.round((rect.y - this.position.y) * this.scaleY)
const realWidth = Math.round(rect.width * this.scaleX)
const realHeight = Math.round(rect.height * this.scaleY)
// Mettre à jour l'annotation dans le store avec les coordonnées réelles
this.annotationStore.updateAnnotation(this.currentFrameNumber, this.selectedId, {
x: realX,
y: realY,
width: realWidth,
height: realHeight
})
},
updateCurrentFrame() {
if (!this.videoElement) return
const frameRate = this.annotationStore.currentSession.frameRate || 30
// Utiliser Math.round au lieu de Math.floor pour une meilleure précision
const newFrameNumber = Math.round(this.videoElement.currentTime * frameRate)
// Ne mettre à jour que si la frame a changé
if (newFrameNumber !== this.currentFrameNumber) {
this.currentFrameNumber = newFrameNumber
// Forcer le rafraîchissement du canvas pour s'assurer que seules les annotations
// de la frame actuelle sont affichées
if (this.$refs.layer) {
const layer = this.$refs.layer.getNode()
layer.batchDraw()
}
// Debug des bounding boxes pour la nouvelle frame
this.$nextTick(() => {
this.debugBoundingBoxes()
})
// Log pour débogage
// console.log(`Temps: ${this.videoElement.currentTime.toFixed(3)}s, Frame: ${this.currentFrameNumber}`)
}
},
selectObject(objectId) {
this.annotationStore.selectObject(objectId)
this.$emit('object-selected', objectId)
},
createNewObject() {
this.annotationStore.addObject()
},
animate() {
// Récupérer les éléments sélectionnés
if (this.$refs.layer && this.annotationStore.selectedObjectId) {
const layer = this.$refs.layer.getNode();
// Trouver tous les éléments de l'objet sélectionné
const selectedRects = layer.find('Rect').filter(rect => {
return rect.attrs.objectId === this.annotationStore.selectedObjectId;
});
const selectedPoints = layer.find('Group').filter(group => {
return group.attrs.objectId === this.annotationStore.selectedObjectId;
});
// Appliquer l'animation
[...selectedRects, ...selectedPoints].forEach(shape => {
// Animation de pulsation
const scale = 1 + Math.sin(Date.now() / 300) * 0.05; // Pulsation subtile
shape.scale({ x: scale, y: scale });
});
layer.batchDraw();
}
// Continuer l'animation
this.animationId = requestAnimationFrame(this.animate);
},
getObjectColor(objectId) {
const object = this.annotationStore.objects[objectId];
return object ? object.color : '#CCCCCC';
},
handleMaskClick(maskId, e) {
// Empêcher la propagation pour éviter que handleMouseDown ne soit aussi appelé
if (e && e.evt) {
e.evt.stopPropagation(); // Remplacer cancelBubble par stopPropagation
}
// Sélectionner le masque
this.selectedId = maskId;
console.log('Selected mask:', maskId);
},
drawMask(context, shape, annotation) {
if (!annotation.mask || !annotation.maskImageSize) {
console.warn('Annotation sans masque ou dimensions:', annotation);
return;
}
// Vérifier si le masque est déjà dans le cache
const cacheKey = `${annotation.id}-${annotation.mask.substring(0, 20)}`;
let maskImage = this.maskCache[cacheKey];
if (!maskImage) {
try {
console.log(`Décodage du masque pour l'annotation ${annotation.id}`);
console.log('Début du masque:', annotation.mask.substring(0, 50) + '...');
// Créer une nouvelle image pour charger le masque base64
maskImage = new Image();
// Attendre que l'image soit chargée avant de continuer
const loadPromise = new Promise((resolve, reject) => {
maskImage.onload = () => resolve();
maskImage.onerror = (e) => reject(new Error(`Erreur de chargement de l'image: ${e}`));
});
// Définir la source de l'image (base64)
if (annotation.mask.startsWith('data:')) {
// Si c'est déjà un data URL
maskImage.src = annotation.mask;
} else {
// Sinon, supposer que c'est un base64 brut et créer un data URL
maskImage.src = `data:image/png;base64,${annotation.mask}`;
}
// Attendre que l'image soit chargée
loadPromise.then(() => {
console.log(`Image du masque chargée: ${maskImage.width}x${maskImage.height}`);
// Créer un canvas temporaire pour traiter l'image
const tempCanvas = document.createElement('canvas');
tempCanvas.width = maskImage.width;
tempCanvas.height = maskImage.height;
const tempCtx = tempCanvas.getContext('2d');
// Dessiner l'image sur le canvas temporaire
tempCtx.drawImage(maskImage, 0, 0);
// Obtenir les données de l'image
const imageData = tempCtx.getImageData(0, 0, maskImage.width, maskImage.height);
const data = imageData.data;
// Obtenir la couleur de l'objet
const objectColor = this.getObjectColor(annotation.objectId);
const r = parseInt(objectColor.slice(1, 3), 16);
const g = parseInt(objectColor.slice(3, 5), 16);
const b = parseInt(objectColor.slice(5, 7), 16);
// Parcourir tous les pixels
for (let i = 0; i < data.length; i += 4) {
// Si le pixel est blanc (ou presque blanc)
if (data[i] > 200 && data[i+1] > 200 && data[i+2] > 200) {
// Remplacer par la couleur de l'objet avec une transparence
data[i] = r;
data[i+1] = g;
data[i+2] = b;
data[i+3] = 180; // Semi-transparent
} else {
// Rendre le pixel complètement transparent
data[i+3] = 0;
}
}
// Remettre les données modifiées dans le canvas
tempCtx.putImageData(imageData, 0, 0);
// Créer une nouvelle image à partir du canvas modifié
const coloredMaskImage = new Image();
coloredMaskImage.src = tempCanvas.toDataURL();
// Mettre en cache l'image colorée
this.maskCache[cacheKey] = coloredMaskImage;
// Forcer un nouveau rendu
this.$nextTick(() => {
if (this.$refs.layer) {
this.$refs.layer.getNode().batchDraw();
}
});
}).catch(error => {
console.error('Erreur lors du traitement de l\'image du masque:', error);
});
// Retourner tôt car l'image n'est pas encore chargée
return;
} catch (error) {
console.error('Erreur lors de la création de l\'image du masque:', error);
return;
}
}
// Si l'image n'est pas encore complètement chargée, retourner
if (!maskImage.complete) {
return;
}
// Calculer l'échelle pour adapter le masque à la taille d'affichage
const scaleX = this.imageWidth / annotation.maskImageSize.width;
const scaleY = this.imageHeight / annotation.maskImageSize.height;
// Dessiner le masque sur le canvas principal
const ctx = context._context;
ctx.save();
// Appliquer la transformation pour positionner correctement le masque
ctx.translate(this.position.x, this.position.y);
ctx.scale(scaleX, scaleY);
// Dessiner l'image du masque coloré
ctx.drawImage(maskImage, 0, 0);
// Restaurer le contexte
ctx.restore();
// Indiquer à Konva que le dessin est terminé
shape.strokeEnabled(false); // Désactiver le contour automatique
},
handleShapeMouseDown(e, shapeId) {
// Empêcher la propagation pour éviter que handleMouseDown ne soit aussi appelé
e.evt.stopPropagation(); // Remplacer cancelBubble par stopPropagation
// Sélectionner la forme
this.selectedId = shapeId;
// Si l'outil actuel est la flèche, activer le mode de déplacement
if (this.currentTool === 'arrow') {
this.isDragging = true;
const stage = this.$refs.stage.getStage();
this.dragStartPos = stage.getPointerPosition();
console.log('Selected shape:', shapeId);
}
},
// Ajouter cette méthode pour gérer l'ajout de points à un masque existant
addPointToExistingMask(pos, type) {
if (!this.annotationStore.selectedObjectId) {
this.annotationStore.addObject();
}
const relativeX = pos.x - this.position.x;
const relativeY = pos.y - this.position.y;
// Utiliser les dimensions réelles de la vidéo originale
const imageX = Math.round(relativeX * this.scaleX);
const imageY = Math.round(relativeY * this.scaleY);
// Ajouter le point à la collection temporaire
this.annotationStore.addTemporaryPoint({
objectId: this.annotationStore.selectedObjectId,
x: imageX,
y: imageY,
pointType: type
});
console.log('Point temporaire ajouté:', { x: imageX, y: imageY, type });
},
// Nouvelle méthode pour basculer l'affichage des bounding boxes
toggleBoundingBoxes() {
this.showAllBoundingBoxes = !this.showAllBoundingBoxes;
console.log('Affichage des bounding boxes:', this.showAllBoundingBoxes ? 'activé' : 'désactivé');
},
// Méthode de débogage pour afficher les informations des bounding boxes
debugBoundingBoxes() {
const boxes = this.allBoundingBoxes;
if (boxes.length > 0) {
console.log(`🔍 Frame ${this.currentFrameNumber}: ${boxes.length} bounding box(es) trouvée(s)`);
const currentBoxes = boxes.filter(b => b.source === 'current');
if (currentBoxes.length > 0) {
console.log(` ✏️ Annotations en cours: ${currentBoxes.length}`);
currentBoxes.forEach(box => {
console.log(` - ${box.name} (${box.type}): x=${Math.round(box.x)}, y=${Math.round(box.y)}, w=${Math.round(box.width)}, h=${Math.round(box.height)}`);
});
}
}
},
// Nouvelle méthode pour gérer les clics sur les points
handlePointClick(pointId, e) {
// Empêcher la propagation pour éviter que handleMouseDown ne soit aussi appelé
e.evt.stopPropagation()
// Sélectionner le point
this.selectedId = pointId
// Si l'outil actuel est la flèche, activer le mode de déplacement
if (this.currentTool === 'arrow') {
this.isDragging = true
const stage = this.$refs.stage.getStage()
this.dragStartPos = stage.getPointerPosition()
}
console.log('Selected point via direct click:', pointId)
},
},
watch: {
'stageConfig.width'() {
this.$nextTick(() => {
this.updateDimensions()
})
},
'stageConfig.height'() {
this.$nextTick(() => {
this.updateDimensions()
})
},
'videoStore.currentTime'() {
this.updateCurrentFrame()
},
'annotationStore.selectedObjectId'(newId) {
console.log('Objet sélectionné changé:', newId)
// Redémarrer l'animation quand l'objet sélectionné change
this.startAnimation()
},
currentFrameNumber() {
// Forcer le rafraîchissement du canvas quand la frame change
this.$nextTick(() => {
if (this.$refs.layer) {
const layer = this.$refs.layer.getNode()
layer.batchDraw()
}
})
}
},
}
</script>
<style scoped>
.video-section {
width: 100%;
height: 100%;
display: flex;
gap: 8px;
}
.video-container {
flex: 1;
position: relative;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
.video-wrapper, .canvas-wrapper {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.video-wrapper {
z-index: 1;
}
.canvas-wrapper {
z-index: 999;
}
.video-element {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: contain;
z-index: 1;
}
.canvas-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10;
background: transparent;
pointer-events: auto;
}
.tool-btn {
width: 34px;
height: 34px;
border: none;
border-radius: 4px;
background: transparent;
color: #fff;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
}
.tool-btn:hover {
background: #4a4a4a;
}
.tool-btn.active {
background: #3a3a3a;
color: white;
}
.tool-btn svg {
width: 20px;
height: 20px;
stroke-width: 2;
}
.tool-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
background: transparent;
}
.tool-btn:not(:disabled):hover {
background: #4a4a4a;
}
.pulse-animation {
animation: pulse 1.5s infinite ease-in-out;
}
.spinner {
width: 20px;
height: 20px;
border: 3px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: white;
animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
</style> 123456789101112131415161718192021222324252627282930<template>
<div class="video-timeline">
<timeline-section />
<objects-timeline-section />
</div>
</template>
<script>
import TimelineSection from './TimelineSection.vue'
import ObjectsTimelineSection from './ObjectsTimelineSection.vue'
export default {
name: 'VideoTimeline',
components: {
TimelineSection,
ObjectsTimelineSection
}
}
</script>
<style scoped>
.video-timeline {
width: 100%;
border-radius: 8px;
padding: 0;
display: flex;
flex-direction: column;
gap: 16px;
}
</style> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198<template>
<div class="zoom-section">
<div class="zoom-header">
<div class="view-navigation">
<button
class="nav-button"
@click="previousView"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
</svg>
</button>
<span class="view-indicator">
{{ currentViewIndex + 1 }} / {{ views.length }}
</span>
<button
class="nav-button"
@click="nextView"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
</svg>
</button>
</div>
</div>
<div class="zoom-content">
<transition :name="transitionName" mode="out-in">
<component
:is="currentView.component"
:key="currentViewIndex"
class="view-content"
/>
</transition>
</div>
</div>
</template>
<script>
import { useAnnotationStore } from '@/stores/annotationStore'
import { computed } from 'vue'
import ZoomView from './ZoomView.vue'
import AnnotationsRawView from './AnnotationsRawView.vue'
export default {
name: 'ZoomSection',
components: {
ZoomView,
AnnotationsRawView
},
setup() {
const annotationStore = useAnnotationStore()
const objectName = computed(() => {
if (!annotationStore.selectedObjectId) return 'Aucun objet sélectionné'
return annotationStore.objects[annotationStore.selectedObjectId]?.name ||
annotationStore.selectedObjectId
})
return {
objectName
}
},
data() {
return {
currentViewIndex: 0,
transitionName: 'slide-right',
views: [
{
name: 'Zoom',
component: 'ZoomView'
},
{
name: 'Raw Annotations',
component: 'AnnotationsRawView'
}
]
}
},
computed: {
currentView() {
return this.views[this.currentViewIndex]
}
},
methods: {
nextView() {
this.transitionName = 'slide-right'
this.currentViewIndex = (this.currentViewIndex + 1) % this.views.length
},
previousView() {
this.transitionName = 'slide-left'
this.currentViewIndex = this.currentViewIndex === 0
? this.views.length - 1
: this.currentViewIndex - 1
}
}
}
</script>
<style scoped>
.zoom-section {
width: 100%;
height: 100%;
background: #2c2c2c;
border-radius: 8px;
display: flex;
flex-direction: column;
overflow: hidden;
}
.zoom-header {
padding: 8px 12px;
background: #3c3c3c;
border-bottom: 1px solid #4a4a4a;
display: flex;
justify-content: center;
align-items: center;
}
.view-navigation {
display: flex;
align-items: center;
gap: 8px;
}
.nav-button {
background: #4a4a4a;
border: none;
border-radius: 4px;
color: white;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s;
}
.nav-button:hover:not(:disabled) {
background: #5a5a5a;
}
.view-indicator {
color: #ccc;
font-size: 0.8rem;
min-width: 40px;
text-align: center;
}
.zoom-content {
flex: 1;
position: relative;
overflow: hidden;
}
.view-content {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
/* Animations de transition */
.slide-right-enter-active, .slide-right-leave-active,
.slide-left-enter-active, .slide-left-leave-active {
transition: transform 0.3s ease;
}
/* Animation vers la droite */
.slide-right-enter-from {
transform: translateX(100%);
}
.slide-right-leave-to {
transform: translateX(-100%);
}
/* Animation vers la gauche */
.slide-left-enter-from {
transform: translateX(-100%);
}
.slide-left-leave-to {
transform: translateX(100%);
}
</style> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354<template>
<div class="zoom-view">
<div v-if="hasAnnotations" class="zoom-image-container">
<canvas
ref="zoomCanvas"
class="zoom-canvas"
:width="zoomWidth"
:height="zoomHeight"
></canvas>
<div class="zoom-info">
<span>Frame {{ currentFrameNumber }}</span>
<span v-if="zoomRegion">{{ Math.round(zoomRegion.width) }}x{{ Math.round(zoomRegion.height) }}px</span>
<span v-if="zoomRegion?.type === 'points' && selectedAnnotations.length > 1">
{{ selectedAnnotations.length }} points
</span>
</div>
</div>
<div v-else class="no-annotations">
<p>Aucune annotation sur cette frame</p>
</div>
</div>
</template>
<script>
import { useAnnotationStore } from '@/stores/annotationStore'
import { useVideoStore } from '@/stores/videoStore'
import { computed, ref, watch, nextTick, onMounted } from 'vue'
export default {
name: 'ZoomView',
mounted() {
// Forcer le rafraîchissement quand le composant est monté
this.$nextTick(() => {
setTimeout(() => {
this.updateZoomImage()
}, 100) // Petit délai pour s'assurer que la vidéo est prête
})
},
setup() {
const annotationStore = useAnnotationStore()
const videoStore = useVideoStore()
const zoomCanvas = ref(null)
// Dimensions du canvas de zoom
const zoomWidth = 200
const zoomHeight = 300
const getCurrentFrameNumber = () => {
const frameRate = annotationStore.currentSession?.frameRate || 30
return Math.round(videoStore.currentTime * frameRate)
}
const currentFrameNumber = computed(() => getCurrentFrameNumber())
const selectedAnnotations = computed(() => {
const currentFrame = getCurrentFrameNumber()
const frameAnnotations = annotationStore.getAnnotationsForFrame(currentFrame) || []
return frameAnnotations.filter(
annotation => annotation && annotation.objectId === annotationStore.selectedObjectId
)
})
const hasAnnotations = computed(() => {
return selectedAnnotations.value.length > 0
})
const zoomRegion = computed(() => {
const annotations = selectedAnnotations.value
if (!annotations.length) return null
// Séparer rectangles et points
const rectangles = annotations.filter(a => a.type === 'rectangle')
const points = annotations.filter(a => a.type === 'point')
if (rectangles.length > 0) {
// Utiliser le premier rectangle trouvé
const rect = rectangles[0]
return {
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
type: 'rectangle'
}
} else if (points.length > 0) {
// Calculer le centre moyen des points
const avgX = points.reduce((sum, p) => sum + p.x, 0) / points.length
const avgY = points.reduce((sum, p) => sum + p.y, 0) / points.length
if (points.length === 1) {
// Pour un seul point, utiliser une taille fixe raisonnable
const fixedSize = 120
return {
x: avgX - fixedSize,
y: avgY - fixedSize,
width: fixedSize * 2,
height: fixedSize * 2,
type: 'points',
centerX: avgX,
centerY: avgY
}
} else {
// Pour plusieurs points, calculer la bounding box englobante
const minX = Math.min(...points.map(p => p.x))
const maxX = Math.max(...points.map(p => p.x))
const minY = Math.min(...points.map(p => p.y))
const maxY = Math.max(...points.map(p => p.y))
// Calculer les dimensions nécessaires
const pointsWidth = maxX - minX
const pointsHeight = maxY - minY
// Ajouter une marge (minimum 60px de chaque côté)
const marginX = Math.max(60, pointsWidth * 0.3)
const marginY = Math.max(60, pointsHeight * 0.3)
// Calculer les dimensions finales
const finalWidth = pointsWidth + marginX * 2
const finalHeight = pointsHeight + marginY * 2
return {
x: minX - marginX,
y: minY - marginY,
width: finalWidth,
height: finalHeight,
type: 'points',
centerX: avgX,
centerY: avgY,
pointsBounds: {
minX, maxX, minY, maxY,
pointsWidth, pointsHeight
}
}
}
}
return null
})
const drawAnnotationsOnZoom = (ctx, sourceX, sourceY, sourceWidth, sourceHeight) => {
const annotations = selectedAnnotations.value
if (!annotations.length) return
// Calculer le facteur d'échelle entre la source et le canvas
const scaleX = zoomWidth / sourceWidth
const scaleY = zoomHeight / sourceHeight
annotations.forEach(annotation => {
if (annotation.type === 'rectangle') {
// Calculer la position du rectangle dans le canvas zoomé
const rectX = (annotation.x - sourceX) * scaleX
const rectY = (annotation.y - sourceY) * scaleY
const rectWidth = annotation.width * scaleX
const rectHeight = annotation.height * scaleY
// Ne dessiner que si le rectangle est visible dans la zone
if (rectX < zoomWidth && rectY < zoomHeight &&
rectX + rectWidth > 0 && rectY + rectHeight > 0) {
// Dessiner le rectangle
ctx.strokeStyle = '#00ff00' // Vert pour les rectangles
ctx.lineWidth = 2
ctx.setLineDash([5, 3]) // Trait pointillé
ctx.strokeRect(rectX, rectY, rectWidth, rectHeight)
ctx.setLineDash([]) // Remettre trait plein
}
} else if (annotation.type === 'point') {
// Calculer la position du point dans le canvas zoomé
const pointX = (annotation.x - sourceX) * scaleX
const pointY = (annotation.y - sourceY) * scaleY
// Ne dessiner que si le point est visible dans la zone
if (pointX >= 0 && pointX <= zoomWidth && pointY >= 0 && pointY <= zoomHeight) {
// Couleur selon le type de point
const pointColor = annotation.pointType === 'positive' ? '#00ff00' : '#ff0000'
// Dessiner le cercle du point
ctx.fillStyle = pointColor
ctx.strokeStyle = '#ffffff'
ctx.lineWidth = 2
ctx.beginPath()
ctx.arc(pointX, pointY, 6, 0, 2 * Math.PI)
ctx.fill()
ctx.stroke()
// Dessiner le symbole + ou -
ctx.strokeStyle = '#ffffff'
ctx.lineWidth = 2
ctx.beginPath()
if (annotation.pointType === 'positive') {
// Dessiner +
ctx.moveTo(pointX - 3, pointY)
ctx.lineTo(pointX + 3, pointY)
ctx.moveTo(pointX, pointY - 3)
ctx.lineTo(pointX, pointY + 3)
} else {
// Dessiner -
ctx.moveTo(pointX - 3, pointY)
ctx.lineTo(pointX + 3, pointY)
}
ctx.stroke()
}
}
})
// Si c'est une vue centrée sur des points, dessiner une croix de repère au centre
if (zoomRegion.value?.type === 'points') {
ctx.strokeStyle = '#ffff00' // Jaune pour le centre
ctx.lineWidth = 1
ctx.setLineDash([3, 3])
ctx.beginPath()
const centerX = zoomWidth / 2
const centerY = zoomHeight / 2
ctx.moveTo(centerX - 15, centerY)
ctx.lineTo(centerX + 15, centerY)
ctx.moveTo(centerX, centerY - 15)
ctx.lineTo(centerX, centerY + 15)
ctx.stroke()
ctx.setLineDash([])
}
}
const updateZoomImage = async () => {
if (!zoomCanvas.value || !zoomRegion.value) return
// Trouver l'élément vidéo
const videoElement = document.querySelector('video')
if (!videoElement) return
const canvas = zoomCanvas.value
const ctx = canvas.getContext('2d')
// Effacer le canvas
ctx.clearRect(0, 0, zoomWidth, zoomHeight)
try {
// Calculer les coordonnées source dans la vidéo
const sourceX = Math.max(0, zoomRegion.value.x)
const sourceY = Math.max(0, zoomRegion.value.y)
const sourceWidth = Math.min(zoomRegion.value.width, videoElement.videoWidth - sourceX)
const sourceHeight = Math.min(zoomRegion.value.height, videoElement.videoHeight - sourceY)
// S'assurer que les dimensions sont valides
if (sourceWidth <= 0 || sourceHeight <= 0) return
// Dessiner la région zoomée sur le canvas
ctx.drawImage(
videoElement,
sourceX, sourceY, sourceWidth, sourceHeight, // Source (région de la vidéo)
0, 0, zoomWidth, zoomHeight // Destination (canvas)
)
// Dessiner les annotations sur l'image zoomée
drawAnnotationsOnZoom(ctx, sourceX, sourceY, sourceWidth, sourceHeight)
} catch (error) {
console.error('Erreur lors de la capture du zoom:', error)
// Afficher un message d'erreur sur le canvas
ctx.fillStyle = '#666'
ctx.fillRect(0, 0, zoomWidth, zoomHeight)
ctx.fillStyle = '#fff'
ctx.font = '14px Arial'
ctx.textAlign = 'center'
ctx.fillText('Erreur de capture', zoomWidth / 2, zoomHeight / 2)
}
}
// Watcher pour mettre à jour l'image quand les annotations changent
watch([selectedAnnotations, currentFrameNumber], () => {
nextTick(() => {
updateZoomImage()
})
}, { deep: true })
// Watcher pour mettre à jour quand le temps de la vidéo change
watch(() => videoStore.currentTime, () => {
nextTick(() => {
updateZoomImage()
})
})
// Hook onMounted pour forcer le rafraîchissement au montage
onMounted(() => {
nextTick(() => {
setTimeout(() => {
updateZoomImage()
}, 200) // Délai plus long pour s'assurer que tout est prêt
})
})
return {
selectedAnnotations,
hasAnnotations,
zoomRegion,
currentFrameNumber,
zoomCanvas,
zoomWidth,
zoomHeight,
updateZoomImage
}
}
}
</script>
<style scoped>
.zoom-view {
height: 100%;
padding: 10px;
color: white;
overflow: auto;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.zoom-image-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
}
.zoom-canvas {
border: 1px solid #555;
border-radius: 4px;
background: #000;
}
.zoom-info {
display: flex;
gap: 12px;
font-size: 0.8rem;
color: #ccc;
}
.no-annotations {
text-align: center;
color: #888;
font-style: italic;
display: flex;
align-items: center;
justify-content: center;
height: 100%;
}
.no-annotations p {
margin: 0;
}
</style> 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586<template>
<div class="video-tools">
<tool-button
:is-active="currentTool === 'arrow'"
@click="selectTool('arrow')"
title="Selection Tool"
>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path d="M3 3l7 19 2.051-7.179L19 13 3 3z"/>
</svg>
</tool-button>
<tool-button
:is-active="currentTool === 'rectangle'"
@click="selectTool('rectangle')"
title="Rectangle Tool"
>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
</svg>
</tool-button>
<tool-button
:is-active="currentTool === 'positive'"
@click="selectTool('positive')"
title="Positive Point"
>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="white" stroke="currentColor">
<circle cx="12" cy="12" r="10" fill="#4CAF50"/>
<line x1="7" y1="12" x2="17" y2="12" stroke="white" stroke-width="2"/>
<line x1="12" y1="7" x2="12" y2="17" stroke="white" stroke-width="2"/>
</svg>
</tool-button>
<tool-button
:is-active="currentTool === 'negative'"
@click="selectTool('negative')"
title="Negative Point"
>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="white" stroke="currentColor">
<circle cx="12" cy="12" r="10" fill="#f44336"/>
<line x1="7" y1="12" x2="17" y2="12" stroke="white" stroke-width="2"/>
</svg>
</tool-button>
</div>
</template>
<script>
import ToolButton from './ToolButton.vue'
export default {
name: 'ToolBar',
components: {
ToolButton
},
props: {
currentTool: {
type: String,
required: true
}
},
emits: ['tool-selected'],
methods: {
selectTool(tool) {
this.$emit('tool-selected', tool)
}
}
}
</script>
<style scoped>
.video-tools {
width: 50px;
height: 100%;
padding: 8px;
display: flex;
flex-direction: column;
gap: 8px;
justify-content: center;
align-items: center;
}
</style> 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970<template>
<button
class="tool-btn"
:class="{ active: isActive }"
@click="$emit('click')"
:title="title"
>
<slot></slot>
</button>
</template>
<script>
export default {
name: 'ToolButton',
props: {
isActive: {
type: Boolean,
default: false
},
title: {
type: String,
default: ''
}
},
emits: ['click']
}
</script>
<style scoped>
.tool-btn {
width: 34px;
height: 34px;
border: none;
border-radius: 4px;
background: transparent;
color: #fff;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
}
.tool-btn:hover {
background: #4a4a4a;
}
.tool-btn.active {
background: #3a3a3a;
color: white;
}
.tool-btn svg {
width: 20px;
height: 20px;
stroke-width: 2;
}
.tool-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
background: transparent;
}
.tool-btn:not(:disabled):hover {
background: #4a4a4a;
}
</style> 1234567891011import { createApp } from 'vue'import { createPinia } from 'pinia'import App from './App.vue'import router from './router'import VueKonva from 'vue-konva'
const app = createApp(App)app.use(router)app.use(VueKonva)app.use(createPinia())app.mount('#app')123456789101112131415161718192021import { createRouter, createWebHashHistory } from 'vue-router'
import SegmentationView from '../views/SegmentationView.vue'
const routes = [
{
path: '/',
redirect: '/segmentation'
},
{
path: '/segmentation',
name: 'segmentation',
component: SegmentationView
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285// Dans un store Pinia (stores/annotationStore.js)
import { defineStore } from 'pinia'
import { v4 as uuidv4 } from 'uuid'
export const useAnnotationStore = defineStore('annotations', {
state: () => ({
// Session courante avec métadonnées vidéo
currentSession: {
id: 'session-1',
name: 'Session d\'annotation',
videoId: null,
video: null, // Nom du fichier vidéo
metadata: {
duration: 0,
width: 0,
height: 0,
fps: 30,
date: new Date().toISOString()
}
},
// Dictionnaire des objets
objects: {
// Format: "1": { id: "1", name: "Objet 1", color: "#4f056f" }
},
// Compteur pour les IDs d'objets
objectIdCounter: 1,
// Annotations par frame
frameAnnotations: {}, // Format: {
// "0": [
// {
// id: "uuid",
// objectId: "1",
// type: "mask",
// mask: "base64...",
// maskScore: 0.91,
// maskImageSize: { width: 1920, height: 1080 },
// points: [{ x: 1270, y: 405, type: "positive" }]
// },
// {
// id: "uuid",
// objectId: "2",
// type: "rectangle",
// x: 100,
// y: 100,
// width: 200,
// height: 150
// }
// ]
// }
selectedObjectId: null,
temporaryPoints: []
}),
getters: {
getTemporaryPointsForObject: (state) => (objectId) => {
return state.temporaryPoints.filter(point => point.objectId === objectId)
}
},
actions: {
// Sélectionner un objet
selectObject(objectId) {
this.selectedObjectId = objectId
console.log(`Objet sélectionné: ${objectId}`)
},
// Désélectionner l'objet actuel
deselectObject() {
this.selectedObjectId = null
},
// Mettre à jour les métadonnées de la vidéo
updateVideoMetadata(metadata) {
this.currentSession.metadata = {
...this.currentSession.metadata,
...metadata
}
},
// Ajouter une annotation pour l'objet sélectionné à la frame actuelle
addAnnotation(frameNumber, annotation) {
const id = uuidv4()
let newAnnotation
if (annotation.type === 'mask') {
newAnnotation = {
id,
objectId: this.selectedObjectId,
type: 'mask',
mask: annotation.mask || '',
maskScore: annotation.maskScore || 0,
maskImageSize: annotation.maskImageSize || {
width: this.currentSession.metadata.width,
height: this.currentSession.metadata.height
},
points: annotation.points || []
}
} else if (annotation.type === 'rectangle') {
newAnnotation = {
id,
objectId: this.selectedObjectId,
type: 'rectangle',
x: annotation.x,
y: annotation.y,
width: annotation.width,
height: annotation.height
}
} else if (annotation.type === 'point') {
newAnnotation = {
id,
objectId: this.selectedObjectId,
type: 'point',
x: annotation.x,
y: annotation.y,
pointType: annotation.pointType // 'positive' ou 'negative'
}
} else {
// Gestion par défaut pour les autres types
newAnnotation = {
id,
objectId: this.selectedObjectId,
...annotation
}
}
// Vérifier que newAnnotation a été créée
if (!newAnnotation) {
console.error('Erreur: impossible de créer l\'annotation', annotation)
return null
}
if (!this.frameAnnotations[frameNumber]) {
this.frameAnnotations[frameNumber] = []
}
this.frameAnnotations[frameNumber].push(newAnnotation)
console.log('Annotation ajoutée:', newAnnotation)
return id
},
updateAnnotation(frameNumber, annotationId, updates) {
if (!this.frameAnnotations[frameNumber]) return
const annotationIndex = this.frameAnnotations[frameNumber].findIndex(
a => a.id === annotationId
)
if (annotationIndex === -1) return
// Mettre à jour l'annotation avec les nouvelles propriétés
this.frameAnnotations[frameNumber][annotationIndex] = {
...this.frameAnnotations[frameNumber][annotationIndex],
...updates
}
},
// Ajouter un nouvel objet
addObject(objectData = {}) {
const objectId = `${this.objectIdCounter++}`
this.objects[objectId] = {
id: objectId,
name: objectData.name || `Objet ${this.objectIdCounter - 1}`,
color: objectData.color || this.getRandomColor(),
// Autres propriétés selon vos besoins
}
// Sélectionner automatiquement le nouvel objet
this.selectObject(objectId)
return objectId
},
// Récupérer les annotations pour une frame
getAnnotationsForFrame(frameNumber) {
return this.frameAnnotations[frameNumber.toString()] || []
},
// Supprimer une annotation
removeAnnotation(frameNumber, annotationId) {
const frameKey = frameNumber.toString()
if (this.frameAnnotations[frameKey]) {
this.frameAnnotations[frameKey] = this.frameAnnotations[frameKey]
.filter(a => a.id !== annotationId)
}
},
// Nouvelle méthode pour supprimer tous les masques d'un objet sur une frame
removeMasksForObject(frameNumber, objectId) {
const frameKey = frameNumber.toString()
if (this.frameAnnotations[frameKey]) {
this.frameAnnotations[frameKey] = this.frameAnnotations[frameKey]
.filter(a => !(a.objectId === objectId && a.type === 'mask'))
}
},
// Vérifier si un objet a encore des annotations sur une frame
hasAnnotationsForObject(frameNumber, objectId) {
const frameKey = frameNumber.toString()
if (!this.frameAnnotations[frameKey]) return false
return this.frameAnnotations[frameKey]
.some(a => a.objectId === objectId)
},
// Générer une couleur aléatoire
getRandomColor() {
return '#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0')
},
// Sauvegarder les annotations dans le format demandé
saveAnnotations() {
const data = {
video: this.currentSession.video,
metadata: this.currentSession.metadata,
objects: this.objects,
annotations: this.frameAnnotations
}
localStorage.setItem('annotations', JSON.stringify(data))
},
// Charger les annotations depuis le format demandé
loadAnnotations() {
const saved = localStorage.getItem('annotations')
if (saved) {
const data = JSON.parse(saved)
this.currentSession.video = data.video
this.currentSession.metadata = data.metadata
this.objects = data.objects
this.frameAnnotations = data.annotations
}
},
getAnnotation(frameNumber, annotationId) {
if (!this.frameAnnotations[frameNumber]) return null
return this.frameAnnotations[frameNumber].find(a => a.id === annotationId) || null
},
addTemporaryPoint(point) {
// Ajouter un ID unique au point
const pointWithId = {
...point,
id: uuidv4()
}
this.temporaryPoints.push(pointWithId)
return pointWithId.id
},
removeTemporaryPoint(pointId) {
const index = this.temporaryPoints.findIndex(p => p.id === pointId)
if (index !== -1) {
this.temporaryPoints.splice(index, 1)
}
},
clearTemporaryPoints() {
this.temporaryPoints = []
},
// Supprimer un objet et toutes ses annotations
deleteObject(objectId) {
// Supprimer l'objet du dictionnaire
delete this.objects[objectId]
// Supprimer toutes les annotations associées à cet objet
Object.keys(this.frameAnnotations).forEach(frameKey => {
this.frameAnnotations[frameKey] = this.frameAnnotations[frameKey]
.filter(annotation => annotation.objectId !== objectId)
})
// Si l'objet supprimé était sélectionné, désélectionner
if (this.selectedObjectId === objectId) {
this.selectedObjectId = null
}
// Supprimer les points temporaires associés à cet objet
this.temporaryPoints = this.temporaryPoints.filter(point => point.objectId !== objectId)
}
}
})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import { defineStore } from 'pinia'
export const useVideoStore = defineStore('video', {
state: () => ({
videos: [],
selectedVideo: null,
defaultPath: 'C:\\Users\\antoi\\Documents\\Work_Learn\\Stage-Rennes\\RepositoryFootballVision\\SportDETR\\data\\football\\raw',
// defaultPath: '\\\\10.35.51.152\\Biomeca\\Projets\\25_EVA2PERF_M2_AntoineVerdon\\RepositoryFootballVision\\SportDETR\\data\\football\\raw',
currentTime: 0,
isPlaying: false,
duration: 0,
// Vidéo par défaut depuis les assets
defaultVideo: null,
isInitialized: false
}),
actions: {
// Initialiser avec une vidéo par défaut si aucune n'est sélectionnée
async initialize() {
if (!this.isInitialized && !this.selectedVideo) {
// Essayer de charger une vidéo par défaut depuis les assets
try {
const defaultVideoPath = require('@/assets/football.mp4')
this.defaultVideo = {
name: 'football',
path: defaultVideoPath,
type: 'video/mp4',
isDefault: true
}
// Ne pas définir automatiquement comme selectedVideo, laisser l'utilisateur choisir
} catch (error) {
console.log('Aucune vidéo par défaut disponible dans les assets')
}
this.isInitialized = true
}
},
setVideos(videos) {
this.videos = videos
},
async setSelectedVideo(video) {
this.selectedVideo = video
},
setCurrentTime(time) {
this.currentTime = time
},
setIsPlaying(isPlaying) {
this.isPlaying = isPlaying
},
setDuration(duration) {
this.duration = duration
},
async loadVideosFromFolder() {
// DÉSACTIVÉ - pas de chargement de dossier externe
this.videos = []
return []
},
async loadVideoMetadata(videoPath) {
return new Promise((resolve, reject) => {
const tempVideo = document.createElement('video')
tempVideo.src = videoPath
tempVideo.crossOrigin = 'anonymous'
tempVideo.addEventListener('loadedmetadata', () => {
this.duration = tempVideo.duration
resolve({
duration: tempVideo.duration,
videoElement: tempVideo
})
})
tempVideo.addEventListener('error', (error) => {
console.error('Erreur lors du chargement de la vidéo:', error)
reject(error)
})
})
},
updateProgressBar(time) {
this.currentTime = time
this.emitTimeUpdate(time)
},
emitTimeUpdate(time) {
this.currentTime = time
}
}
}) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132<template>
<div class="segmentation-view">
<!-- Sidebar de segmentation -->
<SegmentationSidebar
class="sidebar"
@video-selected="selectVideo"
/>
<div class="main-content">
<!-- Grille 2x2 avec les 4 sections -->
<div class="grid-container">
<!-- Ligne du haut -->
<VideoSection class="video-section grid-item" />
<ZoomSection class="zoom-section grid-item" />
<!-- Ligne du bas -->
<VideoTimeline class="video-timeline grid-item" />
<EnrichedSection class="enriched-section grid-item" />
</div>
</div>
</div>
</template>
<script>
import SegmentationSidebar from '@/components/SegmentationSidebar.vue'
import VideoSection from '@/components/VideoSection.vue'
import VideoTimeline from '@/components/VideoTimeline.vue'
import ZoomSection from '@/components/ZoomSection.vue'
import EnrichedSection from '@/components/EnrichedSection.vue'
import { useVideoStore } from '@/stores/videoStore'
export default {
name: 'SegmentationView',
components: {
SegmentationSidebar,
VideoSection,
VideoTimeline,
ZoomSection,
EnrichedSection
},
setup() {
const videoStore = useVideoStore()
return {
videoStore
}
},
async mounted() {
// Charger une vidéo par défaut si aucune n'est sélectionnée
if (!this.videoStore.selectedVideo) {
await this.loadDefaultVideo()
}
},
methods: {
async selectVideo(video) {
await this.videoStore.setSelectedVideo(video)
},
async loadDefaultVideo() {
// Créer une vidéo par défaut avec la vidéo de football
try {
const defaultVideo = {
name: 'football.mp4',
path: require('@/assets/football.mp4'),
type: 'video/mp4',
isDefault: true,
size: 0
}
await this.videoStore.setSelectedVideo(defaultVideo)
console.log('Vidéo par défaut chargée:', defaultVideo.name)
} catch (error) {
console.error('Erreur lors du chargement de la vidéo par défaut:', error)
}
}
}
}
</script>
<style scoped>
.segmentation-view {
display: flex;
height: 100vh;
background: #1a1a1a;
}
.sidebar {
width: 200px;
border-right: 1px solid #333;
}
.main-content {
flex: 1;
display: flex;
flex-direction: column;
padding: 8px;
background: #2A2A2A;
}
.grid-container {
flex: 1;
display: grid;
grid-template-columns: 3fr 1fr;
grid-template-rows: 1fr 1fr;
gap: 8px;
min-height: 0;
}
.grid-item {
background: #2a2a2a;
border-radius: 8px;
overflow: hidden;
}
.video-section {
/* Section vidéo principale - haut gauche */
}
.zoom-section {
/* Section zoom - haut droite */
}
.enriched-section {
/* Section enriched - bas droite */
}
.video-timeline {
/* Timeline vidéo - bas gauche */
}
</style>12345const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true
}).dockerignoreAdded+12
.gitattributes+2
.gitignoreAdded+43
DockerfileAdded+34
README.md+16-6
babel.config.jsAdded+5
index.htmlAdded+14
jsconfig.jsonAdded+19
package-lock.jsonAdded
package.jsonAdded+48
public/favicon.icoAdded
public/index.htmlAdded+17
src/App.vueAdded+31
src/assets/football.mp4Added+3
src/assets/imgFoot.jpgAdded

Large File Pointer Details
- SHA256: a681562c393f5fcd34f36f21adf6614a9fb993dd9fedfd0b267cb1877d2da250
- Pointer size: 131 Bytes
- Size of remote file: 773 kB
src/assets/logo.jpgAdded

src/components/AnnotationsRawView.vueAdded+288
src/components/EmptyView.vueAdded+277
src/components/EnrichedSection.vueAdded+186
src/components/LabelingView.vueAdded+255
src/components/ObjectItem.vueAdded+357
src/components/ObjectTimeline.vueAdded+70
src/components/ObjectsTimelineSection.vueAdded+166
src/components/SegmentationSidebar.vueAdded+217
src/components/ShortcutsView.vueAdded+137
src/components/TimelineSection.vueAdded+481
src/components/VideoProgressTimeline.vueAdded+82
src/components/VideoSection.vueAdded+1852
src/components/VideoTimeline.vueAdded+30
src/components/ZoomSection.vueAdded+198
src/components/ZoomView.vueAdded+354
src/components/tools/ToolBar.vueAdded+86
src/components/tools/ToolButton.vueAdded+70
src/main.jsAdded+11
src/router/index.jsAdded+21
src/stores/annotationStore.jsAdded+285
src/stores/videoStore.jsAdded+96
src/views/SegmentationView.vueAdded+132
vue.config.jsAdded+5