simplexsigil2 commited on
Commit
072fa45
·
verified ·
1 Parent(s): ffed66a

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +340 -0
README.md CHANGED
@@ -229,6 +229,346 @@ for video_path in train_df['path'][:5]:
229
  f"label {seg['label']}")
230
  ```
231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  ## Technical Properties
233
 
234
  ### Video Specifications
 
229
  f"label {seg['label']}")
230
  ```
231
 
232
+ ### PyTorch Dataset Integration
233
+
234
+ ```python
235
+ from datasets import load_dataset
236
+ import pandas as pd
237
+ import torch
238
+ from torch.utils.data import Dataset, DataLoader
239
+ from pathlib import Path
240
+ import cv2
241
+ import numpy as np
242
+
243
+
244
+ class WanFallDataset(Dataset):
245
+ """
246
+ PyTorch Dataset for WanFall activity recognition.
247
+
248
+ This dataset provides both temporal segments and video paths for loading.
249
+ """
250
+
251
+ def __init__(
252
+ self,
253
+ split='train',
254
+ video_root=None,
255
+ transform=None,
256
+ target_transform=None,
257
+ return_segments=True,
258
+ fps=16,
259
+ num_frames=81
260
+ ):
261
+ """
262
+ Args:
263
+ split: One of 'train', 'validation', 'test'
264
+ video_root: Root directory containing video files (e.g., /path/to/wanfall/videos)
265
+ transform: Optional transform to apply to video frames
266
+ target_transform: Optional transform to apply to labels
267
+ return_segments: If True, returns all temporal segments. If False, returns one sample per video.
268
+ fps: Frame rate of videos (default: 16)
269
+ num_frames: Number of frames per video (default: 81)
270
+ """
271
+ super().__init__()
272
+
273
+ # Load labels (all temporal segments)
274
+ labels_ds = load_dataset("simplexsigil2/wanfall")
275
+ self.labels_df = pd.DataFrame(labels_ds["train"])
276
+
277
+ # Load split
278
+ split_ds = load_dataset("simplexsigil2/wanfall", "random")
279
+ split_df = pd.DataFrame(split_ds[split])
280
+
281
+ # Merge to get labeled segments for this split
282
+ self.data = pd.merge(split_df, self.labels_df, on="path", how="left")
283
+
284
+ # If not returning segments, keep only one row per video
285
+ if not return_segments:
286
+ self.data = self.data.groupby('path').first().reset_index()
287
+
288
+ self.video_root = Path(video_root) if video_root else None
289
+ self.transform = transform
290
+ self.target_transform = target_transform
291
+ self.return_segments = return_segments
292
+ self.fps = fps
293
+ self.num_frames = num_frames
294
+
295
+ def __len__(self):
296
+ return len(self.data)
297
+
298
+ def __getitem__(self, idx):
299
+ row = self.data.iloc[idx]
300
+
301
+ # Get video path
302
+ video_path = row['path']
303
+ if self.video_root is not None:
304
+ video_path = self.video_root / f"{video_path}.mp4"
305
+
306
+ # Load video frames (if video_root is provided)
307
+ frames = None
308
+ if self.video_root is not None and Path(video_path).exists():
309
+ frames = self._load_video(video_path)
310
+ if self.transform is not None:
311
+ frames = self.transform(frames)
312
+
313
+ # Get label information
314
+ label = int(row['label'])
315
+ start_time = float(row['start'])
316
+ end_time = float(row['end'])
317
+
318
+ # Convert timestamps to frame indices
319
+ start_frame = int(start_time * self.fps)
320
+ end_frame = int(end_time * self.fps)
321
+
322
+ if self.target_transform is not None:
323
+ label = self.target_transform(label)
324
+
325
+ # Return data
326
+ sample = {
327
+ 'video_path': row['path'],
328
+ 'label': label,
329
+ 'start_time': start_time,
330
+ 'end_time': end_time,
331
+ 'start_frame': start_frame,
332
+ 'end_frame': end_frame,
333
+ }
334
+
335
+ if frames is not None:
336
+ sample['frames'] = frames
337
+
338
+ return sample
339
+
340
+ def _load_video(self, video_path):
341
+ """Load video frames using OpenCV."""
342
+ cap = cv2.VideoCapture(str(video_path))
343
+ frames = []
344
+
345
+ while True:
346
+ ret, frame = cap.read()
347
+ if not ret:
348
+ break
349
+ # Convert BGR to RGB
350
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
351
+ frames.append(frame)
352
+
353
+ cap.release()
354
+
355
+ # Convert to numpy array (T, H, W, C)
356
+ frames = np.array(frames)
357
+
358
+ return frames
359
+
360
+
361
+ # Example usage
362
+ def get_dataloaders(video_root, batch_size=32, num_workers=4):
363
+ """Create PyTorch DataLoaders for train/val/test splits."""
364
+
365
+ # Optional: Define transforms
366
+ from torchvision import transforms
367
+
368
+ transform = transforms.Compose([
369
+ transforms.Lambda(lambda x: torch.from_numpy(x).float()),
370
+ transforms.Lambda(lambda x: x.permute(0, 3, 1, 2)), # (T, H, W, C) -> (T, C, H, W)
371
+ transforms.Lambda(lambda x: x / 255.0), # Normalize to [0, 1]
372
+ ])
373
+
374
+ # Create datasets
375
+ train_dataset = WanFallDataset(
376
+ split='train',
377
+ video_root=video_root,
378
+ transform=transform,
379
+ return_segments=True
380
+ )
381
+
382
+ val_dataset = WanFallDataset(
383
+ split='validation',
384
+ video_root=video_root,
385
+ transform=transform,
386
+ return_segments=True
387
+ )
388
+
389
+ test_dataset = WanFallDataset(
390
+ split='test',
391
+ video_root=video_root,
392
+ transform=transform,
393
+ return_segments=True
394
+ )
395
+
396
+ # Create dataloaders
397
+ train_loader = DataLoader(
398
+ train_dataset,
399
+ batch_size=batch_size,
400
+ shuffle=True,
401
+ num_workers=num_workers,
402
+ pin_memory=True
403
+ )
404
+
405
+ val_loader = DataLoader(
406
+ val_dataset,
407
+ batch_size=batch_size,
408
+ shuffle=False,
409
+ num_workers=num_workers,
410
+ pin_memory=True
411
+ )
412
+
413
+ test_loader = DataLoader(
414
+ test_dataset,
415
+ batch_size=batch_size,
416
+ shuffle=False,
417
+ num_workers=num_workers,
418
+ pin_memory=True
419
+ )
420
+
421
+ return train_loader, val_loader, test_loader
422
+
423
+
424
+ # Example training loop snippet
425
+ if __name__ == "__main__":
426
+ video_root = Path("/path/to/wanfall/videos")
427
+
428
+ train_loader, val_loader, test_loader = get_dataloaders(
429
+ video_root=video_root,
430
+ batch_size=16,
431
+ num_workers=4
432
+ )
433
+
434
+ print(f"Train batches: {len(train_loader)}")
435
+ print(f"Val batches: {len(val_loader)}")
436
+ print(f"Test batches: {len(test_loader)}")
437
+
438
+ # Inspect first batch
439
+ for batch in train_loader:
440
+ print("\nBatch keys:", batch.keys())
441
+ if 'frames' in batch:
442
+ print(f"Frames shape: {batch['frames'].shape}")
443
+ print(f"Labels shape: {batch['label'].shape}")
444
+ print(f"Label range: [{batch['label'].min()}, {batch['label'].max()}]")
445
+ break
446
+ ```
447
+
448
+ ### Converting Temporal Segments to Frame-Level Labels
449
+
450
+ If you need frame-level labels for dense prediction tasks:
451
+
452
+ ```python
453
+ import numpy as np
454
+
455
+
456
+ def temporal_segments_to_frames(segments_df, fps=16, num_frames=81):
457
+ """
458
+ Convert temporal segments to frame-level labels.
459
+
460
+ Args:
461
+ segments_df: DataFrame with 'start', 'end', 'label' columns for one video
462
+ fps: Frame rate (default: 16)
463
+ num_frames: Number of frames per video (default: 81)
464
+
465
+ Returns:
466
+ Array of shape (num_frames,) with label for each frame
467
+ """
468
+ # Initialize with -1 (unlabeled)
469
+ frame_labels = np.full(num_frames, -1, dtype=np.int32)
470
+
471
+ # Sort segments by start time
472
+ segments_df = segments_df.sort_values('start')
473
+
474
+ for _, seg in segments_df.iterrows():
475
+ start_frame = int(seg['start'] * fps)
476
+ end_frame = min(int(seg['end'] * fps), num_frames - 1)
477
+
478
+ # Assign label to frames
479
+ frame_labels[start_frame:end_frame + 1] = seg['label']
480
+
481
+ return frame_labels
482
+
483
+
484
+ # Example usage with PyTorch Dataset
485
+ class WanFallFrameLevelDataset(Dataset):
486
+ """PyTorch Dataset with frame-level labels."""
487
+
488
+ def __init__(self, split='train', video_root=None, transform=None):
489
+ super().__init__()
490
+
491
+ # Load labels and split
492
+ labels_ds = load_dataset("simplexsigil2/wanfall")
493
+ self.labels_df = pd.DataFrame(labels_ds["train"])
494
+
495
+ split_ds = load_dataset("simplexsigil2/wanfall", "random")
496
+ split_df = pd.DataFrame(split_ds[split])
497
+
498
+ # Get unique videos in this split
499
+ self.video_paths = split_df['path'].tolist()
500
+ self.video_root = Path(video_root) if video_root else None
501
+ self.transform = transform
502
+
503
+ def __len__(self):
504
+ return len(self.video_paths)
505
+
506
+ def __getitem__(self, idx):
507
+ video_path = self.video_paths[idx]
508
+
509
+ # Load video frames
510
+ frames = None
511
+ if self.video_root is not None:
512
+ full_path = self.video_root / f"{video_path}.mp4"
513
+ if full_path.exists():
514
+ frames = self._load_video(full_path)
515
+ if self.transform is not None:
516
+ frames = self.transform(frames)
517
+
518
+ # Get all segments for this video and convert to frame labels
519
+ video_segments = self.labels_df[self.labels_df['path'] == video_path]
520
+ frame_labels = temporal_segments_to_frames(video_segments)
521
+
522
+ return {
523
+ 'video_path': video_path,
524
+ 'frames': frames,
525
+ 'labels': torch.from_numpy(frame_labels), # Shape: (81,)
526
+ }
527
+
528
+ def _load_video(self, video_path):
529
+ """Load video frames."""
530
+ cap = cv2.VideoCapture(str(video_path))
531
+ frames = []
532
+ while True:
533
+ ret, frame = cap.read()
534
+ if not ret:
535
+ break
536
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
537
+ frames.append(frame)
538
+ cap.release()
539
+ return np.array(frames)
540
+ ```
541
+
542
+ ### Best Practices
543
+
544
+ **1. Temporal Segment vs Frame-Level:**
545
+ - Use temporal segments directly for action localization and detection tasks
546
+ - Convert temporal segments to frame-level labels for dense prediction tasks (see example above)
547
+ - The dataset provides temporal segments; use the conversion function for frame-level labels
548
+
549
+ **2. Handling Multiple Segments per Video:**
550
+ - Set `return_segments=True` to get all temporal segments (one sample per segment)
551
+ - Set `return_segments=False` to get one sample per video (useful for video-level classification)
552
+
553
+ **3. Data Loading:**
554
+ - Videos are stored separately and not included in this HuggingFace dataset
555
+ - Provide `video_root` path where videos are stored with structure: `{video_root}/{path}.mp4`
556
+ - Example: `{video_root}/fall/fall_ch_001.mp4`
557
+
558
+ **4. Memory Efficiency:**
559
+ - Load videos on-demand in `__getitem__` rather than pre-loading
560
+ - Use `num_workers > 0` in DataLoader for parallel loading
561
+ - Consider using video decoding libraries like `decord` or `torchvision.io` for faster loading
562
+
563
+ **5. Temporal Sampling:**
564
+ - For long videos or limited memory, sample frames instead of loading all 81 frames
565
+ - Use uniform sampling, random sampling, or segment-focused sampling based on task
566
+
567
+ **6. Label Handling:**
568
+ - Labels are integers 0-15 for the 16 activity classes
569
+ - `-1` indicates unlabeled frames (when converting to frame-level labels)
570
+ - Consider class balancing or weighted sampling for imbalanced classes
571
+
572
  ## Technical Properties
573
 
574
  ### Video Specifications