Skip to main content

edgefirst_client/coco/
studio.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright © 2025 Au-Zone Technologies. All Rights Reserved.
3
4//! COCO import/export for EdgeFirst Studio.
5//!
6//! Provides high-level workflows for importing COCO datasets into Studio
7//! and exporting Studio datasets to COCO format.
8//!
9//! **Note:** COCO datasets must be extracted before import. ZIP archives
10//! are not supported directly - extract images to `train2017/`, `val2017/`,
11//! etc. subdirectories first.
12
13use super::{
14    convert::{
15        box2d_to_coco_bbox, coco_bbox_to_box2d, coco_segmentation_to_polygon,
16        polygon_to_coco_polygon,
17    },
18    reader::{CocoReadOptions, CocoReader, read_coco_directory},
19    types::{CocoDataset, CocoImage, CocoIndex, CocoInfo, CocoSegmentation},
20    writer::{CocoDatasetBuilder, CocoWriteOptions, CocoWriter},
21};
22use crate::{
23    Annotation, AnnotationSetID, Client, DatasetID, Error, FileType, Progress, Sample, SampleFile,
24};
25use std::{
26    collections::HashSet,
27    path::{Path, PathBuf},
28};
29use tokio::sync::mpsc::Sender;
30
31/// Result of a COCO import operation.
32#[derive(Debug, Clone)]
33pub struct CocoImportResult {
34    /// Total number of images in the COCO dataset.
35    pub total_images: usize,
36    /// Number of images that were already imported (skipped).
37    pub skipped: usize,
38    /// Number of images newly imported.
39    pub imported: usize,
40}
41
42/// Options for importing COCO to Studio.
43#[derive(Debug, Clone)]
44pub struct CocoImportOptions {
45    /// Include segmentation masks.
46    pub include_masks: bool,
47    /// Include images (upload them to Studio).
48    pub include_images: bool,
49    /// Group name for all samples (e.g., "train", "val").
50    pub group: Option<String>,
51    /// Batch size for API calls.
52    pub batch_size: usize,
53    /// Maximum concurrent uploads (default: 64).
54    pub concurrency: usize,
55    /// Resume import by skipping already-imported samples.
56    /// When true (default), checks existing samples and skips duplicates.
57    pub resume: bool,
58}
59
60impl Default for CocoImportOptions {
61    fn default() -> Self {
62        Self {
63            include_masks: true,
64            include_images: true,
65            group: None,
66            batch_size: 100,
67            concurrency: 64,
68            resume: true,
69        }
70    }
71}
72
73/// Options for exporting Studio to COCO.
74#[derive(Debug, Clone)]
75pub struct CocoExportOptions {
76    /// Filter by group names (empty = all).
77    pub groups: Vec<String>,
78    /// Include segmentation masks in output.
79    pub include_masks: bool,
80    /// Include images in output (download and add to ZIP).
81    pub include_images: bool,
82    /// Output as ZIP archive (if false, output JSON only).
83    pub output_zip: bool,
84    /// Pretty-print JSON.
85    pub pretty_json: bool,
86    /// COCO info section.
87    pub info: Option<CocoInfo>,
88}
89
90impl Default for CocoExportOptions {
91    fn default() -> Self {
92        Self {
93            groups: vec![],
94            include_masks: true,
95            include_images: false,
96            output_zip: false,
97            pretty_json: false,
98            info: None,
99        }
100    }
101}
102
103/// Import COCO dataset into EdgeFirst Studio.
104///
105/// Reads COCO annotations and images from an extracted directory,
106/// converts to EdgeFirst format, and uploads to Studio using the bulk API.
107///
108/// # Arguments
109/// * `client` - Authenticated Studio client
110/// * `coco_path` - Path to COCO annotation JSON file (images must be extracted
111///   in sibling directories like `train2017/`, `val2017/`)
112/// * `dataset_id` - Target dataset in Studio
113/// * `annotation_set_id` - Target annotation set
114/// * `options` - Import options
115/// * `progress` - Optional progress channel
116///
117/// # Returns
118/// Import result with counts of total, skipped, and imported samples
119///
120/// # Errors
121/// Returns an error if:
122/// - No annotation file is found
123/// - Images are not extracted (ZIP archives not supported)
124/// - Upload to Studio fails
125///
126/// # Resume Behavior
127/// When `options.resume` is true (default), the function checks which samples
128/// already exist in the target dataset and skips them. This allows resuming
129/// interrupted imports without re-uploading data.
130///
131/// # Example
132/// ```bash
133/// # First extract COCO dataset:
134/// cd ~/Datasets/COCO
135/// unzip annotations_trainval2017.zip
136/// unzip val2017.zip
137///
138/// # Then import:
139/// edgefirst import-coco annotations/instances_val2017.json DS_ID AS_ID --group val
140///
141/// # If interrupted, simply run again - it will resume from where it left off
142/// ```
143pub async fn import_coco_to_studio(
144    client: &Client,
145    coco_path: impl AsRef<Path>,
146    dataset_id: DatasetID,
147    annotation_set_id: AnnotationSetID,
148    options: &CocoImportOptions,
149    progress: Option<Sender<Progress>>,
150) -> Result<CocoImportResult, Error> {
151    let coco_path = coco_path.as_ref();
152
153    // Read COCO dataset
154    let (dataset, images_dir) = read_coco_from_path(coco_path)?;
155
156    let total_images = dataset.images.len();
157    if total_images == 0 {
158        return Err(Error::MissingAnnotations(
159            "No images found in COCO dataset".to_string(),
160        ));
161    }
162
163    // Validate that images are extracted
164    if options.include_images {
165        validate_images_extracted(&dataset, &images_dir)?;
166    }
167
168    // Check for existing samples if resume is enabled
169    let existing_names = fetch_existing_sample_names(client, &dataset_id, options.resume).await?;
170
171    // Filter images for import
172    let group_filter = options.group.as_deref();
173    let (images_to_import, skipped, filtered_by_group) =
174        filter_images_for_import(&dataset.images, group_filter, &existing_names);
175
176    // Log filtering info
177    log_import_filter_info(group_filter, filtered_by_group, total_images);
178
179    let to_import = images_to_import.len();
180
181    // If nothing to import, return early
182    if to_import == 0 {
183        log_nothing_to_import(skipped);
184        return Ok(CocoImportResult {
185            total_images,
186            skipped,
187            imported: 0,
188        });
189    }
190
191    if skipped > 0 {
192        log::info!(
193            "Resuming import: {} of {} images already imported, {} remaining",
194            skipped,
195            total_images,
196            to_import
197        );
198    }
199
200    // Build index and upload
201    let index = CocoIndex::from_dataset(&dataset);
202    send_progress(&progress, 0, to_import).await;
203
204    let upload_ctx = UploadContext {
205        client,
206        dataset_id: &dataset_id,
207        annotation_set_id: &annotation_set_id,
208        options,
209        progress: &progress,
210    };
211    let imported =
212        upload_images_in_batches(&upload_ctx, &images_to_import, &index, &images_dir).await?;
213
214    Ok(CocoImportResult {
215        total_images,
216        skipped,
217        imported,
218    })
219}
220
221/// Fetch existing sample names from the server if resume is enabled.
222async fn fetch_existing_sample_names(
223    client: &Client,
224    dataset_id: &DatasetID,
225    resume: bool,
226) -> Result<HashSet<String>, Error> {
227    if !resume {
228        return Ok(HashSet::new());
229    }
230
231    log::info!("Checking for existing samples in dataset {}...", dataset_id);
232    let names = client.sample_names(*dataset_id, &[], None, None).await?;
233    log::info!("Found {} existing samples in dataset", names.len());
234
235    if !names.is_empty() {
236        let samples: Vec<_> = names.iter().take(3).collect();
237        log::debug!("Sample names from server: {:?}", samples);
238    }
239
240    Ok(names)
241}
242
243/// Log filtering information.
244fn log_import_filter_info(group_filter: Option<&str>, filtered_by_group: usize, total: usize) {
245    if filtered_by_group > 0 {
246        log::info!(
247            "Group filter '{}': {} images excluded, {} matching",
248            group_filter.unwrap_or(""),
249            filtered_by_group,
250            total - filtered_by_group
251        );
252    }
253}
254
255/// Log when there's nothing to import.
256fn log_nothing_to_import(skipped: usize) {
257    if skipped > 0 {
258        log::info!(
259            "All {} matching images already imported, nothing to do",
260            skipped
261        );
262    } else {
263        log::info!("No images to import");
264    }
265}
266
267/// Send progress update.
268async fn send_progress(progress: &Option<Sender<Progress>>, current: usize, total: usize) {
269    if let Some(p) = progress {
270        let _ = p
271            .send(Progress {
272                current,
273                total,
274                status: None,
275            })
276            .await;
277    }
278}
279
280/// Context for batch upload operations.
281struct UploadContext<'a> {
282    client: &'a Client,
283    dataset_id: &'a DatasetID,
284    annotation_set_id: &'a AnnotationSetID,
285    options: &'a CocoImportOptions,
286    progress: &'a Option<Sender<Progress>>,
287}
288
289/// Upload images in batches with high concurrency.
290async fn upload_images_in_batches<'a>(
291    ctx: &UploadContext<'a>,
292    images: &[&CocoImage],
293    index: &CocoIndex,
294    images_dir: &Path,
295) -> Result<usize, Error> {
296    let mut imported = 0;
297    let to_import = images.len();
298
299    for batch in images.chunks(ctx.options.batch_size) {
300        let samples = convert_batch_to_samples(batch, index, images_dir, ctx.options)?;
301
302        ctx.client
303            .populate_samples_with_concurrency(
304                *ctx.dataset_id,
305                Some(*ctx.annotation_set_id),
306                samples,
307                None,
308                Some(ctx.options.concurrency),
309            )
310            .await?;
311
312        imported += batch.len();
313        send_progress(ctx.progress, imported, to_import).await;
314    }
315
316    Ok(imported)
317}
318
319/// Convert a batch of COCO images to EdgeFirst samples.
320fn convert_batch_to_samples(
321    batch: &[&CocoImage],
322    index: &CocoIndex,
323    images_dir: &Path,
324    options: &CocoImportOptions,
325) -> Result<Vec<Sample>, Error> {
326    let mut samples = Vec::with_capacity(batch.len());
327
328    for image in batch {
329        let image_group = super::reader::infer_group_from_folder(&image.file_name);
330        let sample = convert_coco_image_to_sample(
331            image,
332            index,
333            images_dir,
334            options.include_masks,
335            options.include_images,
336            image_group.as_deref(),
337        )?;
338        samples.push(sample);
339    }
340
341    Ok(samples)
342}
343
344/// Validate that images are extracted and accessible.
345fn validate_images_extracted(dataset: &CocoDataset, images_dir: &Path) -> Result<(), Error> {
346    // Sample a few images to verify they exist
347    let sample_size = std::cmp::min(5, dataset.images.len());
348    let mut missing = Vec::new();
349
350    for image in dataset.images.iter().take(sample_size) {
351        if find_image_file(images_dir, &image.file_name).is_none() {
352            missing.push(image.file_name.clone());
353        }
354    }
355
356    if !missing.is_empty() {
357        let examples: Vec<_> = missing.iter().take(3).cloned().collect();
358        return Err(Error::MissingImages(format!(
359            "Images must be extracted before import.\n\
360             Cannot find: {}\n\n\
361             Searched in: {}\n\
362             Expected subdirectories: train2017/, val2017/, images/\n\n\
363             Please extract your COCO image archives first:\n\
364             $ cd {} && unzip train2017.zip && unzip val2017.zip",
365            examples.join(", "),
366            images_dir.display(),
367            images_dir.display()
368        )));
369    }
370
371    Ok(())
372}
373
374/// Find an image file in standard COCO directory locations.
375fn find_image_file(base_dir: &Path, file_name: &str) -> Option<PathBuf> {
376    let candidates = [
377        base_dir.join(file_name),
378        base_dir.join("images").join(file_name),
379        base_dir.join("train2017").join(file_name),
380        base_dir.join("val2017").join(file_name),
381        base_dir.join("test2017").join(file_name),
382        base_dir.join("train2014").join(file_name),
383        base_dir.join("val2014").join(file_name),
384    ];
385    candidates.into_iter().find(|p| p.exists())
386}
387
388/// Infer group name from COCO annotation filename.
389///
390/// Examples:
391/// - `instances_train2017.json` -> Some("train")
392/// - `instances_val2017.json` -> Some("val")
393/// - `instances_test2017.json` -> Some("test")
394/// - `custom.json` -> None
395fn infer_group_from_filename(path: &Path) -> Option<String> {
396    let stem = path.file_stem()?.to_str()?;
397
398    // Look for patterns like "instances_train2017" or "instances_val2014"
399    if let Some(rest) = stem.strip_prefix("instances_") {
400        // Remove trailing year digits: "train2017" -> "train"
401        let group = rest.trim_end_matches(char::is_numeric);
402        if !group.is_empty() {
403            return Some(group.to_string());
404        }
405    }
406
407    // Also handle patterns like "train_instances" or just "train"
408    for prefix in ["train", "val", "test", "validation"] {
409        if stem.starts_with(prefix) {
410            return Some(prefix.to_string());
411        }
412    }
413
414    None
415}
416
417/// Read COCO dataset from a path (directory or JSON file).
418///
419/// Returns the dataset and the base directory for images.
420fn read_coco_from_path(coco_path: &Path) -> Result<(CocoDataset, PathBuf), Error> {
421    if coco_path.is_dir() {
422        // Read all annotation files and merge into one dataset
423        let datasets = read_coco_directory(coco_path, &CocoReadOptions::default())?;
424        log::info!("Found {} annotation files in directory", datasets.len());
425
426        // Merge all datasets, preserving group info by prefixing file_name
427        let mut merged = CocoDataset::default();
428        for (mut ds, group) in datasets {
429            log::info!(
430                "  - {} group: {} images, {} annotations",
431                group,
432                ds.images.len(),
433                ds.annotations.len()
434            );
435            // Prefix file_name with group folder so infer_group_from_folder can extract it
436            // e.g., "000000123.jpg" -> "train2017/000000123.jpg"
437            for image in &mut ds.images {
438                if !image.file_name.contains('/') {
439                    image.file_name = format!("{}2017/{}", group, image.file_name);
440                }
441            }
442            merge_coco_datasets(&mut merged, ds);
443        }
444        Ok((merged, coco_path.to_path_buf()))
445    } else if coco_path.extension().is_some_and(|e| e == "json") {
446        // JSON file directly
447        let reader = CocoReader::new();
448        let dataset = reader.read_json(coco_path)?;
449        let parent = coco_path
450            .parent()
451            .and_then(|p| p.parent()) // Go up from annotations/ to COCO root
452            .unwrap_or(Path::new("."));
453        Ok((dataset, parent.to_path_buf()))
454    } else {
455        Err(Error::InvalidParameters(
456            "COCO import requires a JSON annotation file or directory. \
457             ZIP archives must be extracted first."
458                .to_string(),
459        ))
460    }
461}
462
463/// Filter images for import based on group filter and existing samples.
464///
465/// Returns a vector of images to import, the count of skipped images,
466/// and the count of images filtered by group.
467fn filter_images_for_import<'a>(
468    images: &'a [CocoImage],
469    group_filter: Option<&str>,
470    existing_names: &HashSet<String>,
471) -> (Vec<&'a CocoImage>, usize, usize) {
472    let total = images.len();
473
474    // Filter images that match group filter and aren't already imported
475    let images_to_import: Vec<_> = images
476        .iter()
477        .filter(|img| {
478            // Check group filter
479            if let Some(filter) = group_filter {
480                let inferred = super::reader::infer_group_from_folder(&img.file_name);
481                if inferred.as_deref() != Some(filter) {
482                    return false;
483                }
484            }
485            // Check if already imported
486            let sample_name = extract_sample_name(&img.file_name);
487            !existing_names.contains(&sample_name)
488        })
489        .collect();
490
491    // Count images filtered by group
492    let filtered_by_group = if group_filter.is_some() {
493        images
494            .iter()
495            .filter(|img| {
496                let inferred = super::reader::infer_group_from_folder(&img.file_name);
497                inferred.as_deref() != group_filter
498            })
499            .count()
500    } else {
501        0
502    };
503
504    let skipped = total - filtered_by_group - images_to_import.len();
505    (images_to_import, skipped, filtered_by_group)
506}
507
508/// Extract sample name from a file name.
509fn extract_sample_name(file_name: &str) -> String {
510    Path::new(file_name)
511        .file_stem()
512        .and_then(|s| s.to_str())
513        .map(String::from)
514        .unwrap_or_else(|| file_name.to_string())
515}
516
517/// Merge two COCO datasets, avoiding duplicates.
518///
519/// Images and categories are deduplicated by ID. Annotations are always
520/// appended (assuming globally unique IDs across annotation files).
521fn merge_coco_datasets(target: &mut CocoDataset, source: CocoDataset) {
522    // Merge images (deduplicate by id)
523    let existing_image_ids: HashSet<_> = target.images.iter().map(|i| i.id).collect();
524    for image in source.images {
525        if !existing_image_ids.contains(&image.id) {
526            target.images.push(image);
527        }
528    }
529
530    // Merge categories (deduplicate by id)
531    let existing_cat_ids: HashSet<_> = target.categories.iter().map(|c| c.id).collect();
532    for cat in source.categories {
533        if !existing_cat_ids.contains(&cat.id) {
534            target.categories.push(cat);
535        }
536    }
537
538    // Merge annotations (always append - IDs should be globally unique)
539    target.annotations.extend(source.annotations);
540
541    // Merge licenses (deduplicate by id)
542    let existing_license_ids: HashSet<_> = target.licenses.iter().map(|l| l.id).collect();
543    for license in source.licenses {
544        if !existing_license_ids.contains(&license.id) {
545            target.licenses.push(license);
546        }
547    }
548
549    // Take info from source if target has none
550    if target.info.description.is_none() && source.info.description.is_some() {
551        target.info = source.info;
552    }
553}
554
555/// Convert a COCO image and its annotations to an EdgeFirst Sample for Studio upload.
556///
557/// LVIS extension fields (`iscrowd`, `category_frequency`, `neg_label_indices`,
558/// `not_exhaustive_label_indices`) are set on the returned Sample/Annotations when
559/// present in the source data. However, Studio's backend currently drops these fields
560/// during import because it re-marshals annotations through typed Go structs (see
561/// DE-2509). These fields will round-trip correctly once the backend adds JSONB
562/// pass-through support. Until then, they are harmlessly omitted from the stored data
563/// via `skip_serializing_if = "Option::is_none"`.
564fn convert_coco_image_to_sample(
565    image: &CocoImage,
566    index: &CocoIndex,
567    images_dir: &Path,
568    include_masks: bool,
569    include_images: bool,
570    group: Option<&str>,
571) -> Result<Sample, Error> {
572    let sample_name = Path::new(&image.file_name)
573        .file_stem()
574        .and_then(|s| s.to_str())
575        .map(String::from)
576        .unwrap_or_else(|| image.file_name.clone());
577
578    // Create annotations
579    let annotations = index
580        .annotations_for_image(image.id)
581        .iter()
582        .filter_map(|coco_ann| {
583            let label = index.label_name(coco_ann.category_id)?;
584            let label_index = index.label_index(coco_ann.category_id);
585
586            let box2d = coco_bbox_to_box2d(&coco_ann.bbox, image.width, image.height);
587
588            let polygon = if include_masks {
589                coco_ann.segmentation.as_ref().and_then(|seg| {
590                    coco_segmentation_to_polygon(seg, image.width, image.height).ok()
591                })
592            } else {
593                None
594            };
595
596            {
597                let mut ann = Annotation::new();
598                ann.set_name(Some(sample_name.clone()));
599                ann.set_label(Some(label.to_string()));
600                ann.set_label_index(label_index);
601                ann.set_box2d(Some(box2d));
602                ann.set_polygon(polygon);
603                ann.set_group(group.map(String::from));
604                ann.set_iscrowd(Some(coco_ann.iscrowd != 0));
605                ann.set_category_frequency(index.frequency(coco_ann.category_id).map(String::from));
606                Some(ann)
607            }
608        })
609        .collect();
610
611    // Translate LVIS image-level fields to label_index lists
612    let neg_label_indices = image.neg_category_ids.as_ref().map(|ids| {
613        ids.iter()
614            .filter_map(|&id| index.label_index(id).map(|idx| idx as u32))
615            .collect::<Vec<u32>>()
616    });
617    let not_exhaustive_label_indices = image.not_exhaustive_category_ids.as_ref().map(|ids| {
618        ids.iter()
619            .filter_map(|&id| index.label_index(id).map(|idx| idx as u32))
620            .collect::<Vec<u32>>()
621    });
622
623    // Create sample files
624    let mut files = Vec::new();
625    if include_images && let Some(image_path) = find_image_file(images_dir, &image.file_name) {
626        files.push(SampleFile::with_filename(
627            FileType::Image.to_string(),
628            image_path.to_string_lossy().to_string(),
629        ));
630    }
631
632    Ok(Sample {
633        image_name: Some(sample_name),
634        width: Some(image.width),
635        height: Some(image.height),
636        group: group.map(String::from),
637        neg_label_indices,
638        not_exhaustive_label_indices,
639        files,
640        annotations,
641        ..Default::default()
642    })
643}
644
645/// Export Studio dataset to COCO format.
646///
647/// Downloads samples and annotations from Studio and converts to COCO format.
648///
649/// # Arguments
650/// * `client` - Authenticated Studio client
651/// * `dataset_id` - Source dataset in Studio
652/// * `annotation_set_id` - Source annotation set
653/// * `output_path` - Output file path (JSON or ZIP)
654/// * `options` - Export options
655/// * `progress` - Optional progress channel
656///
657/// # Returns
658/// Number of annotations exported
659pub async fn export_studio_to_coco(
660    client: &Client,
661    dataset_id: DatasetID,
662    annotation_set_id: AnnotationSetID,
663    output_path: impl AsRef<Path>,
664    options: &CocoExportOptions,
665    progress: Option<Sender<Progress>>,
666) -> Result<usize, Error> {
667    let output_path = output_path.as_ref();
668
669    // Fetch samples from Studio with annotations
670    let groups: Vec<String> = options.groups.clone();
671    let annotation_types = [crate::AnnotationType::Box2d, crate::AnnotationType::Polygon];
672
673    // Fetch all samples
674    let all_samples = client
675        .samples(
676            dataset_id,
677            Some(annotation_set_id),
678            &annotation_types,
679            &groups,
680            &[],
681            progress.clone(),
682            None,
683        )
684        .await?;
685
686    // Convert to COCO format
687    let mut builder = CocoDatasetBuilder::new();
688
689    if let Some(info) = &options.info {
690        builder = builder.info(info.clone());
691    }
692
693    for sample in &all_samples {
694        let image_name = sample.image_name.as_deref().unwrap_or("unknown");
695        let width = sample.width.unwrap_or(0);
696        let height = sample.height.unwrap_or(0);
697
698        // Use the image_name directly if it has an extension, otherwise add .jpg
699        let file_name = if image_name.contains('.') {
700            image_name.to_string()
701        } else {
702            format!("{}.jpg", image_name)
703        };
704        let image_id = builder.add_image(&file_name, width, height);
705
706        for ann in &sample.annotations {
707            // Get bbox from box2d if present, otherwise compute from polygon
708            let bbox = if let Some(box2d) = ann.box2d() {
709                Some(box2d_to_coco_bbox(box2d, width, height))
710            } else if let Some(polygon) = ann.polygon() {
711                compute_bbox_from_polygon(polygon, width, height)
712            } else {
713                None
714            };
715
716            if let Some(bbox) = bbox {
717                let label = ann.label().map(|s| s.as_str()).unwrap_or("unknown");
718                let category_id = builder.add_category(label, None);
719
720                let segmentation = if options.include_masks {
721                    ann.polygon().map(|polygon| {
722                        let coco_poly = polygon_to_coco_polygon(polygon, width, height);
723                        CocoSegmentation::Polygon(coco_poly)
724                    })
725                } else {
726                    None
727                };
728
729                builder.add_annotation(image_id, category_id, bbox, segmentation);
730            }
731        }
732    }
733
734    let dataset = builder.build();
735    let annotation_count = dataset.annotations.len();
736
737    // Write output
738    let writer = CocoWriter::with_options(CocoWriteOptions {
739        compress: true,
740        pretty: options.pretty_json,
741    });
742
743    if options.output_zip {
744        // Download images and create ZIP
745        let images = if options.include_images {
746            download_images(client, &all_samples, progress.clone()).await?
747        } else {
748            vec![]
749        };
750
751        writer.write_zip(&dataset, images.into_iter(), output_path)?;
752    } else {
753        writer.write_json(&dataset, output_path)?;
754    }
755
756    Ok(annotation_count)
757}
758
759/// Download images for samples from their presigned URLs.
760///
761/// Returns a vector of (archive_path, image_data) pairs suitable for ZIP
762/// creation.
763async fn download_images(
764    client: &Client,
765    samples: &[Sample],
766    progress: Option<Sender<Progress>>,
767) -> Result<Vec<(String, Vec<u8>)>, Error> {
768    let mut result = Vec::with_capacity(samples.len());
769    let total = samples.len();
770
771    for (i, sample) in samples.iter().enumerate() {
772        // Find image file URL
773        let image_url = sample.files.iter().find_map(|f| {
774            if f.file_type() == "image" {
775                f.url()
776            } else {
777                None
778            }
779        });
780
781        if let Some(url) = image_url {
782            // Download the image
783            match client.download(url).await {
784                Ok(data) => {
785                    // Build archive path from sample name
786                    let name = sample.image_name.as_deref().unwrap_or("unknown");
787                    let filename = if name.contains('.') {
788                        format!("images/{}", name)
789                    } else {
790                        format!("images/{}.jpg", name)
791                    };
792                    result.push((filename, data));
793                }
794                Err(e) => {
795                    // Log warning but continue with other images
796                    log::warn!(
797                        "Failed to download image for sample {:?}: {}",
798                        sample.image_name,
799                        e
800                    );
801                }
802            }
803        }
804
805        // Update progress
806        if let Some(ref p) = progress {
807            let _ = p
808                .send(Progress {
809                    current: i + 1,
810                    total,
811                    status: None,
812                })
813                .await;
814        }
815    }
816
817    Ok(result)
818}
819
820/// Options for verifying a COCO import.
821#[derive(Debug, Clone)]
822pub struct CocoVerifyOptions {
823    /// Include segmentation mask verification.
824    pub verify_masks: bool,
825    /// Group to verify (None = all groups).
826    pub group: Option<String>,
827}
828
829impl Default for CocoVerifyOptions {
830    fn default() -> Self {
831        Self {
832            verify_masks: true,
833            group: None,
834        }
835    }
836}
837
838/// Result of a COCO annotation update operation.
839#[derive(Debug, Clone)]
840pub struct CocoUpdateResult {
841    /// Total number of images in the COCO dataset.
842    pub total_images: usize,
843    /// Number of samples that were updated with new annotations.
844    pub updated: usize,
845    /// Number of COCO images not found in Studio (not updated).
846    pub not_found: usize,
847}
848
849/// Options for updating annotations on existing samples.
850#[derive(Debug, Clone)]
851pub struct CocoUpdateOptions {
852    /// Include segmentation masks in the update.
853    pub include_masks: bool,
854    /// Group name filter (None = match any group).
855    pub group: Option<String>,
856    /// Batch size for API calls.
857    pub batch_size: usize,
858    /// Maximum concurrent operations.
859    pub concurrency: usize,
860}
861
862impl Default for CocoUpdateOptions {
863    fn default() -> Self {
864        Self {
865            include_masks: true,
866            group: None,
867            batch_size: 100,
868            concurrency: 64,
869        }
870    }
871}
872
873/// Read COCO dataset from a path, handling both files and directories.
874fn read_coco_dataset_for_update(coco_path: &Path) -> Result<CocoDataset, Error> {
875    if coco_path.is_dir() {
876        // Read all annotation files and merge into one dataset
877        let datasets = read_coco_directory(coco_path, &CocoReadOptions::default())?;
878        log::info!("Found {} annotation files in directory", datasets.len());
879
880        // Merge all datasets, preserving group info by prefixing file_name
881        let mut merged = CocoDataset::default();
882        for (mut ds, group) in datasets {
883            log::info!(
884                "  - {} group: {} images, {} annotations",
885                group,
886                ds.images.len(),
887                ds.annotations.len()
888            );
889            // Prefix file_name with group folder so infer_group_from_folder can extract it
890            for image in &mut ds.images {
891                if !image.file_name.contains('/') {
892                    image.file_name = format!("{}2017/{}", group, image.file_name);
893                }
894            }
895            merge_coco_datasets(&mut merged, ds);
896        }
897        Ok(merged)
898    } else if coco_path.extension().is_some_and(|e| e == "json") {
899        let reader = CocoReader::new();
900        reader.read_json(coco_path)
901    } else {
902        Err(Error::InvalidParameters(
903            "COCO update requires a JSON annotation file or directory.".to_string(),
904        ))
905    }
906}
907
908/// Build a map of sample name -> (sample_id, width, height, group) from
909/// samples.
910fn build_sample_info_map(
911    samples: &[Sample],
912) -> std::collections::HashMap<String, (crate::SampleID, u32, u32, Option<String>)> {
913    use std::collections::HashMap;
914    let mut sample_info = HashMap::new();
915    for sample in samples {
916        if let (Some(name), Some(id), Some(w), Some(h)) =
917            (sample.name(), sample.id(), sample.width, sample.height)
918        {
919            sample_info.insert(name, (id, w, h, sample.group.clone()));
920        }
921    }
922    sample_info
923}
924
925/// Ensure all COCO category labels exist in Studio.
926async fn ensure_labels_exist(
927    client: &Client,
928    dataset_id: &DatasetID,
929    categories: &[crate::coco::CocoCategory],
930) -> Result<std::collections::HashMap<String, u64>, Error> {
931    use std::collections::{HashMap, HashSet};
932
933    // Get existing labels
934    let existing_labels = client.labels(*dataset_id, None).await?;
935    let existing_label_names: HashSet<String> = existing_labels
936        .iter()
937        .map(|l| l.name().to_string())
938        .collect();
939
940    // Find COCO categories that don't exist as labels in Studio
941    let missing_labels: Vec<String> = categories
942        .iter()
943        .filter(|c| !existing_label_names.contains(&c.name))
944        .map(|c| c.name.clone())
945        .collect();
946
947    // Create missing labels
948    if !missing_labels.is_empty() {
949        log::info!(
950            "Creating {} missing labels in Studio...",
951            missing_labels.len()
952        );
953        for label_name in &missing_labels {
954            client.add_label(*dataset_id, label_name).await?;
955        }
956    }
957
958    // Re-query labels to get their IDs after creation
959    let labels = client.labels(*dataset_id, None).await?;
960    let label_map: HashMap<String, u64> = labels
961        .iter()
962        .map(|l| (l.name().to_string(), l.id()))
963        .collect();
964
965    log::info!(
966        "Label map has {} entries for {} COCO categories",
967        label_map.len(),
968        categories.len()
969    );
970
971    Ok(label_map)
972}
973
974/// Convert a single COCO annotation to a ServerAnnotation.
975///
976/// This is a pure transformation function that can be easily tested.
977fn convert_coco_annotation_to_server(
978    coco_ann: &super::types::CocoAnnotation,
979    coco_index: &CocoIndex,
980    label_map: &std::collections::HashMap<String, u64>,
981    image_id: u64,
982    annotation_set_id: u64,
983    dims: (u32, u32),
984    include_masks: bool,
985) -> (crate::api::ServerAnnotation, bool) {
986    let (width, height) = dims;
987
988    // Get category name and label_id
989    let category_name = coco_index
990        .categories
991        .get(&coco_ann.category_id)
992        .map(|c| c.name.as_str())
993        .unwrap_or("unknown");
994
995    let label_id = label_map.get(category_name).copied();
996    let missing_label = label_id.is_none();
997
998    // Convert bounding box to server format
999    let box2d = coco_bbox_to_box2d(&coco_ann.bbox, width, height);
1000
1001    // Convert polygon to string if enabled
1002    let polygon = if include_masks {
1003        coco_ann
1004            .segmentation
1005            .as_ref()
1006            .and_then(|seg| coco_segmentation_to_polygon(seg, width, height).ok())
1007            .map(|p| polygon_to_polygon_string(&p))
1008            .unwrap_or_default()
1009    } else {
1010        String::new()
1011    };
1012
1013    let annotation_type = if polygon.is_empty() { "box" } else { "seg" }.to_string();
1014
1015    let server_ann = crate::api::ServerAnnotation {
1016        label_id,
1017        label_index: None,
1018        label_name: Some(category_name.to_string()),
1019        annotation_type,
1020        x: box2d.left() as f64,
1021        y: box2d.top() as f64,
1022        w: box2d.width() as f64,
1023        h: box2d.height() as f64,
1024        score: 1.0,
1025        polygon,
1026        image_id,
1027        annotation_set_id,
1028        object_reference: None,
1029    };
1030
1031    (server_ann, missing_label)
1032}
1033
1034/// Process a single COCO image for update, returning annotations and group
1035/// update info.
1036fn process_image_for_update(
1037    coco_image: &CocoImage,
1038    sample_info: &std::collections::HashMap<String, (crate::SampleID, u32, u32, Option<String>)>,
1039    coco_index: &CocoIndex,
1040    label_map: &std::collections::HashMap<String, u64>,
1041    annotation_set_id: u64,
1042    include_masks: bool,
1043) -> Option<(
1044    crate::SampleID,
1045    Vec<crate::api::ServerAnnotation>,
1046    Option<String>,
1047    usize,
1048)> {
1049    let sample_name = extract_sample_name(&coco_image.file_name);
1050    let expected_group = super::reader::infer_group_from_folder(&coco_image.file_name);
1051
1052    let (sample_id, width, height, current_group) = sample_info.get(&sample_name)?;
1053    let (sample_id, width, height) = (*sample_id, *width, *height);
1054    let image_id: u64 = sample_id.into();
1055
1056    // Check if group needs updating
1057    let group_update = expected_group.as_ref().and_then(|expected| {
1058        if Some(expected) != current_group.as_ref() {
1059            Some(expected.clone())
1060        } else {
1061            None
1062        }
1063    });
1064
1065    // Convert all annotations for this image
1066    let mut annotations = Vec::new();
1067    let mut missing_label_count = 0;
1068
1069    for coco_ann in coco_index.annotations_for_image(coco_image.id) {
1070        let (server_ann, missing) = convert_coco_annotation_to_server(
1071            coco_ann,
1072            coco_index,
1073            label_map,
1074            image_id,
1075            annotation_set_id,
1076            (width, height),
1077            include_masks,
1078        );
1079        if missing {
1080            missing_label_count += 1;
1081        }
1082        annotations.push(server_ann);
1083    }
1084
1085    Some((sample_id, annotations, group_update, missing_label_count))
1086}
1087
1088/// Update sample groups in bulk.
1089async fn update_sample_groups(
1090    client: &Client,
1091    dataset_id: &DatasetID,
1092    samples_needing_group_update: &[(crate::SampleID, String)],
1093) -> usize {
1094    use std::collections::{HashMap, HashSet};
1095
1096    if samples_needing_group_update.is_empty() {
1097        return 0;
1098    }
1099
1100    log::info!(
1101        "Updating groups for {} samples...",
1102        samples_needing_group_update.len()
1103    );
1104
1105    // Collect unique group names and get/create their IDs
1106    let unique_groups: HashSet<String> = samples_needing_group_update
1107        .iter()
1108        .map(|(_, group)| group.clone())
1109        .collect();
1110
1111    let mut group_id_map: HashMap<String, u64> = HashMap::new();
1112    for group_name in unique_groups {
1113        match client.get_or_create_group(*dataset_id, &group_name).await {
1114            Ok(group_id) => {
1115                group_id_map.insert(group_name, group_id);
1116            }
1117            Err(e) => {
1118                log::warn!("Failed to get/create group '{}': {}", group_name, e);
1119            }
1120        }
1121    }
1122
1123    // Update each sample's group
1124    let mut updated_count = 0;
1125    let mut failed_count = 0;
1126    for (sample_id, group_name) in samples_needing_group_update {
1127        if let Some(&group_id) = group_id_map.get(group_name) {
1128            match client.set_sample_group_id(*sample_id, group_id).await {
1129                Ok(_) => {
1130                    updated_count += 1;
1131                    if updated_count % 1000 == 0 {
1132                        log::debug!("Updated groups for {} samples so far", updated_count);
1133                    }
1134                }
1135                Err(e) => {
1136                    failed_count += 1;
1137                    if failed_count <= 5 {
1138                        log::warn!("Failed to update group for sample {:?}: {}", sample_id, e);
1139                    }
1140                }
1141            }
1142        }
1143    }
1144
1145    if failed_count > 5 {
1146        log::warn!("... and {} more group update failures", failed_count - 5);
1147    }
1148    log::info!(
1149        "Updated groups for {} samples ({} failed)",
1150        updated_count,
1151        failed_count
1152    );
1153
1154    updated_count
1155}
1156
1157/// Update annotations on existing samples without re-uploading images.
1158///
1159/// This function reads COCO annotations and updates the annotations on samples
1160/// that already exist in Studio. It's useful for:
1161/// - Adding masks to samples that were imported without them
1162/// - Syncing updated annotations to Studio
1163///
1164/// **Note:** This does NOT upload images. Samples must already exist in Studio.
1165///
1166/// # Arguments
1167/// * `client` - Authenticated Studio client
1168/// * `coco_path` - Path to COCO annotation JSON file
1169/// * `dataset_id` - Target dataset in Studio
1170/// * `annotation_set_id` - Target annotation set
1171/// * `options` - Update options
1172/// * `progress` - Optional progress channel
1173///
1174/// # Returns
1175/// Update result with counts of updated and not-found samples.
1176pub async fn update_coco_annotations(
1177    client: &Client,
1178    coco_path: impl AsRef<Path>,
1179    dataset_id: DatasetID,
1180    annotation_set_id: AnnotationSetID,
1181    options: &CocoUpdateOptions,
1182    progress: Option<Sender<Progress>>,
1183) -> Result<CocoUpdateResult, Error> {
1184    use crate::{SampleID, api::ServerAnnotation};
1185
1186    let coco_path = coco_path.as_ref();
1187
1188    // Read COCO annotations
1189    let dataset = read_coco_dataset_for_update(coco_path)?;
1190    let total_images = dataset.images.len();
1191
1192    if total_images == 0 {
1193        return Err(Error::MissingAnnotations(
1194            "No images found in COCO dataset".to_string(),
1195        ));
1196    }
1197
1198    log::info!(
1199        "COCO dataset: {} images, {} annotations, {} categories",
1200        total_images,
1201        dataset.annotations.len(),
1202        dataset.categories.len()
1203    );
1204
1205    // Query ALL existing samples from Studio
1206    log::info!("Fetching existing samples from Studio...");
1207    let existing_samples = client
1208        .samples(
1209            dataset_id,
1210            Some(annotation_set_id),
1211            &[],
1212            &[],
1213            &[],
1214            progress.clone(),
1215            None,
1216        )
1217        .await?;
1218
1219    let sample_info = build_sample_info_map(&existing_samples);
1220    log::info!(
1221        "Found {} existing samples in Studio with IDs and dimensions",
1222        sample_info.len()
1223    );
1224
1225    // Build COCO index for efficient annotation lookup
1226    let coco_index = CocoIndex::from_dataset(&dataset);
1227
1228    // Ensure all labels exist
1229    let label_map = ensure_labels_exist(client, &dataset_id, &dataset.categories).await?;
1230
1231    // Process all images and collect results
1232    let annotation_set_id_u64: u64 = annotation_set_id.into();
1233    let mut sample_ids_to_update: Vec<SampleID> = Vec::new();
1234    let mut server_annotations: Vec<ServerAnnotation> = Vec::new();
1235    let mut samples_needing_group_update: Vec<(SampleID, String)> = Vec::new();
1236    let mut not_found = 0;
1237    let mut missing_label_count = 0;
1238
1239    for coco_image in &dataset.images {
1240        match process_image_for_update(
1241            coco_image,
1242            &sample_info,
1243            &coco_index,
1244            &label_map,
1245            annotation_set_id_u64,
1246            options.include_masks,
1247        ) {
1248            Some((sample_id, annotations, group_update, missing_labels)) => {
1249                sample_ids_to_update.push(sample_id);
1250                server_annotations.extend(annotations);
1251                missing_label_count += missing_labels;
1252                if let Some(group) = group_update {
1253                    samples_needing_group_update.push((sample_id, group));
1254                }
1255            }
1256            None => {
1257                not_found += 1;
1258                log::debug!(
1259                    "Sample not found in Studio: {}",
1260                    extract_sample_name(&coco_image.file_name)
1261                );
1262            }
1263        }
1264    }
1265
1266    let to_update = sample_ids_to_update.len();
1267    log::info!(
1268        "Updating {} samples ({} not found in Studio), {} annotations",
1269        to_update,
1270        not_found,
1271        server_annotations.len()
1272    );
1273
1274    if missing_label_count > 0 {
1275        log::warn!(
1276            "{} annotations have missing label_id (category not found in label map)",
1277            missing_label_count
1278        );
1279    }
1280
1281    if to_update == 0 {
1282        return Ok(CocoUpdateResult {
1283            total_images,
1284            updated: 0,
1285            not_found,
1286        });
1287    }
1288
1289    // Send initial progress
1290    if let Some(ref tx) = progress {
1291        let _ = tx
1292            .send(Progress {
1293                current: 0,
1294                total: to_update,
1295                status: None,
1296            })
1297            .await;
1298    }
1299
1300    // Step 1: Delete existing annotations for these samples
1301    log::info!(
1302        "Deleting existing annotations for {} samples...",
1303        sample_ids_to_update.len()
1304    );
1305    let annotation_types = if options.include_masks {
1306        vec!["box".to_string(), "seg".to_string()]
1307    } else {
1308        vec!["box".to_string()]
1309    };
1310
1311    // Delete in batches to avoid overwhelming the server
1312    for batch in sample_ids_to_update.chunks(options.batch_size) {
1313        client
1314            .delete_annotations_bulk(annotation_set_id, &annotation_types, batch)
1315            .await?;
1316    }
1317
1318    // Send progress after delete
1319    if let Some(ref tx) = progress {
1320        let _ = tx
1321            .send(Progress {
1322                current: to_update / 2,
1323                total: to_update,
1324                status: None,
1325            })
1326            .await;
1327    }
1328
1329    // Step 2: Add new annotations in batches
1330    log::info!("Adding {} new annotations...", server_annotations.len());
1331    let mut added = 0;
1332    for batch in server_annotations.chunks(options.batch_size) {
1333        client
1334            .add_annotations_bulk(annotation_set_id, batch.to_vec())
1335            .await?;
1336        added += batch.len();
1337        log::debug!("Added {} annotations so far", added);
1338    }
1339
1340    // Final progress update
1341    if let Some(ref tx) = progress {
1342        let _ = tx
1343            .send(Progress {
1344                current: to_update,
1345                total: to_update,
1346                status: None,
1347            })
1348            .await;
1349    }
1350
1351    // Step 3: Update sample groups if needed
1352    let groups_updated =
1353        update_sample_groups(client, &dataset_id, &samples_needing_group_update).await;
1354
1355    log::info!(
1356        "Update complete: {} samples updated, {} not found, {} annotations added, {} groups updated",
1357        to_update,
1358        not_found,
1359        added,
1360        groups_updated
1361    );
1362
1363    Ok(CocoUpdateResult {
1364        total_images,
1365        updated: to_update,
1366        not_found,
1367    })
1368}
1369
1370/// Convert a Polygon to a polygon string for the server API.
1371///
1372/// The server expects a 3D array format: `[[[x1,y1],[x2,y2],...], ...]`
1373/// where each point is an `[x, y]` pair. This matches how the server
1374/// parses polygons in `annotations_handler.go`:
1375/// ```go
1376/// var polygons [][][]float64
1377/// json.Unmarshal([]byte(ann.Polygon), &polygons)
1378/// ```
1379///
1380/// **Note:** This function filters out NaN and Infinity values which would
1381/// serialize as `null` in JSON and cause parsing failures on the server.
1382fn polygon_to_polygon_string(polygon: &crate::Polygon) -> String {
1383    // Convert Vec<Vec<(f32, f32)>> to Vec<Vec<[f32; 2]>> for proper JSON
1384    // serialization Filter out any NaN or Infinity values which would become
1385    // "null" in JSON
1386    let rings: Vec<Vec<[f32; 2]>> = polygon
1387        .rings
1388        .iter()
1389        .map(|ring| {
1390            ring.iter()
1391                .filter(|(x, y)| x.is_finite() && y.is_finite())
1392                .map(|&(x, y)| [x, y])
1393                .collect()
1394        })
1395        .filter(|ring: &Vec<[f32; 2]>| ring.len() >= 3) // Need at least 3 points for a valid polygon
1396        .collect();
1397
1398    serde_json::to_string(&rings).unwrap_or_default()
1399}
1400
1401/// Compute COCO bounding box from polygon contours.
1402///
1403/// When the server doesn't return bounding box coordinates for segmentation
1404/// annotations, we compute them from the polygon bounds.
1405fn compute_bbox_from_polygon(
1406    polygon: &crate::Polygon,
1407    width: u32,
1408    height: u32,
1409) -> Option<[f64; 4]> {
1410    if polygon.rings.is_empty() {
1411        return None;
1412    }
1413
1414    let mut min_x = f32::MAX;
1415    let mut min_y = f32::MAX;
1416    let mut max_x = f32::MIN;
1417    let mut max_y = f32::MIN;
1418
1419    for ring in &polygon.rings {
1420        for &(x, y) in ring {
1421            if x.is_finite() && y.is_finite() {
1422                min_x = min_x.min(x);
1423                min_y = min_y.min(y);
1424                max_x = max_x.max(x);
1425                max_y = max_y.max(y);
1426            }
1427        }
1428    }
1429
1430    if min_x == f32::MAX || min_y == f32::MAX {
1431        return None;
1432    }
1433
1434    // Convert normalized coordinates to COCO pixel coordinates [x, y, w, h]
1435    let x = (min_x * width as f32) as f64;
1436    let y = (min_y * height as f32) as f64;
1437    let w = ((max_x - min_x) * width as f32) as f64;
1438    let h = ((max_y - min_y) * height as f32) as f64;
1439
1440    if w > 0.0 && h > 0.0 {
1441        Some([x, y, w, h])
1442    } else {
1443        None
1444    }
1445}
1446
1447/// Verify a COCO dataset import against Studio data.
1448///
1449/// Compares the local COCO dataset against what's stored in Studio to verify:
1450/// - All images are present (no missing, no extras)
1451/// - All annotations are correct (using Hungarian matching)
1452/// - Bounding boxes match within tolerance
1453/// - Segmentation masks match (if enabled)
1454///
1455/// This does NOT download images - it only compares metadata and annotations.
1456///
1457/// # Arguments
1458/// * `client` - Authenticated Studio client
1459/// * `coco_path` - Path to local COCO annotation JSON file
1460/// * `dataset_id` - Dataset in Studio to verify against
1461/// * `annotation_set_id` - Annotation set in Studio to verify against
1462/// * `options` - Verification options
1463/// * `progress` - Optional progress channel
1464///
1465/// # Returns
1466/// Verification result with detailed comparison metrics.
1467pub async fn verify_coco_import(
1468    client: &Client,
1469    coco_path: impl AsRef<Path>,
1470    dataset_id: DatasetID,
1471    annotation_set_id: AnnotationSetID,
1472    options: &CocoVerifyOptions,
1473    progress: Option<Sender<Progress>>,
1474) -> Result<super::verify::VerificationResult, Error> {
1475    use super::{
1476        verify::{
1477            MaskValidationResult, VerificationResult, validate_bboxes, validate_categories,
1478            validate_masks,
1479        },
1480        writer::CocoDatasetBuilder,
1481    };
1482
1483    let coco_path = coco_path.as_ref();
1484
1485    // Read local COCO dataset
1486    log::info!("Reading local COCO dataset from {:?}", coco_path);
1487    let (coco_dataset, inferred_group) = if coco_path.is_dir() {
1488        // Read all annotation files and merge into one dataset
1489        let datasets = read_coco_directory(coco_path, &CocoReadOptions::default())?;
1490        log::info!("Found {} annotation files in directory", datasets.len());
1491
1492        let mut merged = CocoDataset::default();
1493        for (ds, group) in datasets {
1494            log::info!(
1495                "  - {} group: {} images, {} annotations",
1496                group,
1497                ds.images.len(),
1498                ds.annotations.len()
1499            );
1500            merge_coco_datasets(&mut merged, ds);
1501        }
1502        // When verifying entire directory, don't filter by group
1503        (merged, None)
1504    } else if coco_path.extension().is_some_and(|e| e == "json") {
1505        let reader = CocoReader::new();
1506        let dataset = reader.read_json(coco_path)?;
1507        let group = infer_group_from_filename(coco_path);
1508        (dataset, group)
1509    } else {
1510        return Err(Error::InvalidParameters(
1511            "COCO verification requires a JSON annotation file or directory.".to_string(),
1512        ));
1513    };
1514
1515    // Determine group filter (only when verifying a single JSON file)
1516    let effective_group = options.group.clone().or(inferred_group);
1517    let groups: Vec<String> = effective_group
1518        .as_ref()
1519        .map(|g| vec![g.clone()])
1520        .unwrap_or_default();
1521
1522    log::info!(
1523        "Local COCO: {} images, {} annotations",
1524        coco_dataset.images.len(),
1525        coco_dataset.annotations.len()
1526    );
1527
1528    // Fetch samples from Studio with annotations
1529    log::info!("Fetching samples from Studio dataset {}...", dataset_id);
1530    let annotation_types = [crate::AnnotationType::Box2d, crate::AnnotationType::Polygon];
1531
1532    let studio_samples = client
1533        .samples(
1534            dataset_id,
1535            Some(annotation_set_id),
1536            &annotation_types,
1537            &groups,
1538            &[],
1539            progress.clone(),
1540            None,
1541        )
1542        .await?;
1543
1544    let total_annotations: usize = studio_samples.iter().map(|s| s.annotations.len()).sum();
1545    log::info!(
1546        "Studio: {} samples, {} total annotations",
1547        studio_samples.len(),
1548        total_annotations
1549    );
1550
1551    // Convert Studio samples to COCO format for comparison
1552    let mut builder = CocoDatasetBuilder::new();
1553
1554    for sample in &studio_samples {
1555        let image_name = sample.image_name.as_deref().unwrap_or("unknown");
1556        let width = sample.width.unwrap_or(0);
1557        let height = sample.height.unwrap_or(0);
1558
1559        // Use the image_name directly if it has an extension, otherwise add .jpg
1560        let file_name = if image_name.contains('.') {
1561            image_name.to_string()
1562        } else {
1563            format!("{}.jpg", image_name)
1564        };
1565        let image_id = builder.add_image(&file_name, width, height);
1566
1567        for ann in &sample.annotations {
1568            // Get bbox from box2d if present, otherwise compute from polygon
1569            let bbox = if let Some(box2d) = ann.box2d() {
1570                Some(box2d_to_coco_bbox(box2d, width, height))
1571            } else if let Some(polygon) = ann.polygon() {
1572                // Compute bbox from polygon bounds
1573                compute_bbox_from_polygon(polygon, width, height)
1574            } else {
1575                None
1576            };
1577
1578            if let Some(bbox) = bbox {
1579                let label = ann.label().map(|s| s.as_str()).unwrap_or("unknown");
1580                let category_id = builder.add_category(label, None);
1581
1582                let segmentation = if options.verify_masks {
1583                    ann.polygon().map(|polygon| {
1584                        let coco_poly = polygon_to_coco_polygon(polygon, width, height);
1585                        CocoSegmentation::Polygon(coco_poly)
1586                    })
1587                } else {
1588                    None
1589                };
1590
1591                builder.add_annotation(image_id, category_id, bbox, segmentation);
1592            }
1593        }
1594    }
1595
1596    let studio_dataset = builder.build();
1597
1598    // Build sample name sets for comparison
1599    let coco_names: HashSet<String> = coco_dataset
1600        .images
1601        .iter()
1602        .map(|img| {
1603            Path::new(&img.file_name)
1604                .file_stem()
1605                .and_then(|s| s.to_str())
1606                .map(String::from)
1607                .unwrap_or_else(|| img.file_name.clone())
1608        })
1609        .collect();
1610
1611    let studio_names: HashSet<String> = studio_samples.iter().filter_map(|s| s.name()).collect();
1612
1613    let missing_images: Vec<String> = coco_names.difference(&studio_names).cloned().collect();
1614    let extra_images: Vec<String> = studio_names.difference(&coco_names).cloned().collect();
1615
1616    // Validate bounding boxes
1617    log::info!("Validating bounding boxes...");
1618    let bbox_validation = validate_bboxes(&coco_dataset, &studio_dataset);
1619
1620    // Validate masks if enabled
1621    log::info!("Validating segmentation masks...");
1622    let mask_validation = if options.verify_masks {
1623        validate_masks(&coco_dataset, &studio_dataset)
1624    } else {
1625        MaskValidationResult::new()
1626    };
1627
1628    // Validate categories
1629    let category_validation = validate_categories(&coco_dataset, &studio_dataset);
1630
1631    Ok(VerificationResult {
1632        coco_image_count: coco_dataset.images.len(),
1633        studio_image_count: studio_samples.len(),
1634        missing_images,
1635        extra_images,
1636        coco_annotation_count: coco_dataset.annotations.len(),
1637        studio_annotation_count: studio_dataset.annotations.len(),
1638        bbox_validation,
1639        mask_validation,
1640        category_validation,
1641    })
1642}
1643
1644#[cfg(test)]
1645mod tests {
1646    use super::*;
1647    use crate::coco::{CocoAnnotation, CocoCategory};
1648
1649    // =========================================================================
1650    // Options default tests
1651    // =========================================================================
1652
1653    #[test]
1654    fn test_coco_import_options_default() {
1655        let options = CocoImportOptions::default();
1656        assert!(options.include_masks);
1657        assert!(options.include_images);
1658        assert!(options.group.is_none());
1659        assert_eq!(options.batch_size, 100);
1660        assert_eq!(options.concurrency, 64);
1661        assert!(options.resume);
1662    }
1663
1664    #[test]
1665    fn test_coco_export_options_default() {
1666        let options = CocoExportOptions::default();
1667        assert!(options.groups.is_empty());
1668        assert!(options.include_masks);
1669        assert!(!options.include_images);
1670        assert!(!options.output_zip);
1671        assert!(!options.pretty_json);
1672        assert!(options.info.is_none());
1673    }
1674
1675    #[test]
1676    fn test_coco_update_options_default() {
1677        let options = CocoUpdateOptions::default();
1678        assert!(options.include_masks);
1679        assert!(options.group.is_none());
1680        assert_eq!(options.batch_size, 100);
1681        assert_eq!(options.concurrency, 64);
1682    }
1683
1684    #[test]
1685    fn test_coco_verify_options_default() {
1686        let options = CocoVerifyOptions::default();
1687        assert!(options.verify_masks);
1688        assert!(options.group.is_none());
1689    }
1690
1691    // =========================================================================
1692    // find_image_file tests
1693    // =========================================================================
1694
1695    #[test]
1696    fn test_find_image_file_nonexistent() {
1697        let result = find_image_file(Path::new("/nonexistent"), "test.jpg");
1698        assert!(result.is_none());
1699    }
1700
1701    #[test]
1702    fn test_find_image_file_with_subdirectory_in_name() {
1703        // Tests that file_name like "train2017/000001.jpg" is handled
1704        let result = find_image_file(Path::new("/nonexistent"), "train2017/image.jpg");
1705        assert!(result.is_none()); // Non-existent, but exercises the path logic
1706    }
1707
1708    // =========================================================================
1709    // infer_group_from_filename tests
1710    // =========================================================================
1711
1712    #[test]
1713    fn test_infer_group_from_filename_instances_train() {
1714        let path = Path::new("annotations/instances_train2017.json");
1715        assert_eq!(infer_group_from_filename(path), Some("train".to_string()));
1716    }
1717
1718    #[test]
1719    fn test_infer_group_from_filename_instances_val() {
1720        let path = Path::new("annotations/instances_val2017.json");
1721        assert_eq!(infer_group_from_filename(path), Some("val".to_string()));
1722    }
1723
1724    #[test]
1725    fn test_infer_group_from_filename_instances_test() {
1726        let path = Path::new("instances_test2017.json");
1727        assert_eq!(infer_group_from_filename(path), Some("test".to_string()));
1728    }
1729
1730    #[test]
1731    fn test_infer_group_from_filename_train_prefix() {
1732        let path = Path::new("train_annotations.json");
1733        assert_eq!(infer_group_from_filename(path), Some("train".to_string()));
1734    }
1735
1736    #[test]
1737    fn test_infer_group_from_filename_val_prefix() {
1738        let path = Path::new("val_data.json");
1739        assert_eq!(infer_group_from_filename(path), Some("val".to_string()));
1740    }
1741
1742    #[test]
1743    fn test_infer_group_from_filename_validation_prefix() {
1744        // The function checks "val" before "validation", so "validation_set" matches
1745        // "val"
1746        let path = Path::new("validation_set.json");
1747        assert_eq!(infer_group_from_filename(path), Some("val".to_string()));
1748    }
1749
1750    #[test]
1751    fn test_infer_group_from_filename_custom() {
1752        let path = Path::new("my_custom_annotations.json");
1753        assert_eq!(infer_group_from_filename(path), None);
1754    }
1755
1756    #[test]
1757    fn test_infer_group_from_filename_instances_2014() {
1758        let path = Path::new("instances_val2014.json");
1759        assert_eq!(infer_group_from_filename(path), Some("val".to_string()));
1760    }
1761
1762    // =========================================================================
1763    // merge_coco_datasets tests
1764    // =========================================================================
1765
1766    #[test]
1767    fn test_merge_coco_datasets_empty() {
1768        let mut target = CocoDataset::default();
1769        let source = CocoDataset::default();
1770        merge_coco_datasets(&mut target, source);
1771        assert!(target.images.is_empty());
1772        assert!(target.annotations.is_empty());
1773        assert!(target.categories.is_empty());
1774    }
1775
1776    #[test]
1777    fn test_merge_coco_datasets_basic() {
1778        let mut target = CocoDataset {
1779            images: vec![CocoImage {
1780                id: 1,
1781                file_name: "img1.jpg".to_string(),
1782                ..Default::default()
1783            }],
1784            categories: vec![CocoCategory {
1785                id: 1,
1786                name: "cat".to_string(),
1787                supercategory: None,
1788                ..Default::default()
1789            }],
1790            annotations: vec![CocoAnnotation {
1791                id: 1,
1792                image_id: 1,
1793                category_id: 1,
1794                ..Default::default()
1795            }],
1796            ..Default::default()
1797        };
1798
1799        let source = CocoDataset {
1800            images: vec![CocoImage {
1801                id: 2,
1802                file_name: "img2.jpg".to_string(),
1803                ..Default::default()
1804            }],
1805            categories: vec![CocoCategory {
1806                id: 2,
1807                name: "dog".to_string(),
1808                supercategory: None,
1809                ..Default::default()
1810            }],
1811            annotations: vec![CocoAnnotation {
1812                id: 2,
1813                image_id: 2,
1814                category_id: 2,
1815                ..Default::default()
1816            }],
1817            ..Default::default()
1818        };
1819
1820        merge_coco_datasets(&mut target, source);
1821
1822        assert_eq!(target.images.len(), 2);
1823        assert_eq!(target.categories.len(), 2);
1824        assert_eq!(target.annotations.len(), 2);
1825    }
1826
1827    #[test]
1828    fn test_merge_coco_datasets_deduplicates_images() {
1829        let mut target = CocoDataset {
1830            images: vec![CocoImage {
1831                id: 1,
1832                file_name: "img1.jpg".to_string(),
1833                ..Default::default()
1834            }],
1835            ..Default::default()
1836        };
1837
1838        let source = CocoDataset {
1839            images: vec![
1840                CocoImage {
1841                    id: 1, // Duplicate
1842                    file_name: "img1_dup.jpg".to_string(),
1843                    ..Default::default()
1844                },
1845                CocoImage {
1846                    id: 2,
1847                    file_name: "img2.jpg".to_string(),
1848                    ..Default::default()
1849                },
1850            ],
1851            ..Default::default()
1852        };
1853
1854        merge_coco_datasets(&mut target, source);
1855
1856        assert_eq!(target.images.len(), 2); // Only 2, not 3
1857        assert_eq!(target.images[0].file_name, "img1.jpg"); // Original preserved
1858    }
1859
1860    #[test]
1861    fn test_merge_coco_datasets_deduplicates_categories() {
1862        let mut target = CocoDataset {
1863            categories: vec![CocoCategory {
1864                id: 1,
1865                name: "person".to_string(),
1866                supercategory: None,
1867                ..Default::default()
1868            }],
1869            ..Default::default()
1870        };
1871
1872        let source = CocoDataset {
1873            categories: vec![
1874                CocoCategory {
1875                    id: 1, // Duplicate
1876                    name: "person_dup".to_string(),
1877                    supercategory: None,
1878                    ..Default::default()
1879                },
1880                CocoCategory {
1881                    id: 2,
1882                    name: "car".to_string(),
1883                    supercategory: None,
1884                    ..Default::default()
1885                },
1886            ],
1887            ..Default::default()
1888        };
1889
1890        merge_coco_datasets(&mut target, source);
1891
1892        assert_eq!(target.categories.len(), 2);
1893        assert_eq!(target.categories[0].name, "person"); // Original preserved
1894    }
1895
1896    #[test]
1897    fn test_merge_coco_datasets_info_preserved() {
1898        let mut target = CocoDataset::default();
1899
1900        let source = CocoDataset {
1901            info: CocoInfo {
1902                description: Some("Test dataset".to_string()),
1903                ..Default::default()
1904            },
1905            ..Default::default()
1906        };
1907
1908        merge_coco_datasets(&mut target, source);
1909
1910        assert_eq!(target.info.description, Some("Test dataset".to_string()));
1911    }
1912
1913    // =========================================================================
1914    // convert_coco_image_to_sample tests
1915    // =========================================================================
1916
1917    #[test]
1918    fn test_convert_coco_image_to_sample() {
1919        let image = CocoImage {
1920            id: 1,
1921            width: 640,
1922            height: 480,
1923            file_name: "test.jpg".to_string(),
1924            ..Default::default()
1925        };
1926
1927        let dataset = CocoDataset {
1928            images: vec![image.clone()],
1929            categories: vec![CocoCategory {
1930                id: 1,
1931                name: "person".to_string(),
1932                supercategory: None,
1933                ..Default::default()
1934            }],
1935            annotations: vec![CocoAnnotation {
1936                id: 1,
1937                image_id: 1,
1938                category_id: 1,
1939                bbox: [100.0, 50.0, 200.0, 150.0],
1940                area: 30000.0,
1941                iscrowd: 0,
1942                segmentation: None,
1943                score: None,
1944            }],
1945            ..Default::default()
1946        };
1947
1948        let index = CocoIndex::from_dataset(&dataset);
1949
1950        let sample = convert_coco_image_to_sample(
1951            &image,
1952            &index,
1953            Path::new("/tmp"),
1954            true,
1955            false, // Don't try to include images
1956            Some("train"),
1957        )
1958        .unwrap();
1959
1960        assert_eq!(sample.image_name, Some("test".to_string()));
1961        assert_eq!(sample.width, Some(640));
1962        assert_eq!(sample.height, Some(480));
1963        assert_eq!(sample.group, Some("train".to_string()));
1964        assert_eq!(sample.annotations.len(), 1);
1965        assert_eq!(sample.annotations[0].label(), Some(&"person".to_string()));
1966    }
1967
1968    #[test]
1969    fn test_convert_coco_image_to_sample_no_annotations() {
1970        let image = CocoImage {
1971            id: 1,
1972            width: 640,
1973            height: 480,
1974            file_name: "empty.jpg".to_string(),
1975            ..Default::default()
1976        };
1977
1978        let dataset = CocoDataset {
1979            images: vec![image.clone()],
1980            categories: vec![],
1981            annotations: vec![],
1982            ..Default::default()
1983        };
1984
1985        let index = CocoIndex::from_dataset(&dataset);
1986
1987        let sample =
1988            convert_coco_image_to_sample(&image, &index, Path::new("/tmp"), true, false, None)
1989                .unwrap();
1990
1991        assert_eq!(sample.image_name, Some("empty".to_string()));
1992        assert!(sample.annotations.is_empty());
1993    }
1994
1995    #[test]
1996    fn test_convert_coco_image_to_sample_with_mask() {
1997        let image = CocoImage {
1998            id: 1,
1999            width: 100,
2000            height: 100,
2001            file_name: "masked.jpg".to_string(),
2002            ..Default::default()
2003        };
2004
2005        let dataset = CocoDataset {
2006            images: vec![image.clone()],
2007            categories: vec![CocoCategory {
2008                id: 1,
2009                name: "object".to_string(),
2010                supercategory: None,
2011                ..Default::default()
2012            }],
2013            annotations: vec![CocoAnnotation {
2014                id: 1,
2015                image_id: 1,
2016                category_id: 1,
2017                bbox: [10.0, 10.0, 50.0, 50.0],
2018                area: 2500.0,
2019                iscrowd: 0,
2020                segmentation: Some(CocoSegmentation::Polygon(vec![vec![
2021                    10.0, 10.0, 60.0, 10.0, 60.0, 60.0, 10.0, 60.0,
2022                ]])),
2023                score: None,
2024            }],
2025            ..Default::default()
2026        };
2027
2028        let index = CocoIndex::from_dataset(&dataset);
2029
2030        // With masks
2031        let sample_with =
2032            convert_coco_image_to_sample(&image, &index, Path::new("/tmp"), true, false, None)
2033                .unwrap();
2034        assert!(sample_with.annotations[0].polygon().is_some());
2035
2036        // Without masks
2037        let sample_without =
2038            convert_coco_image_to_sample(&image, &index, Path::new("/tmp"), false, false, None)
2039                .unwrap();
2040        assert!(sample_without.annotations[0].polygon().is_none());
2041    }
2042
2043    // =========================================================================
2044    // compute_bbox_from_polygon tests
2045    // =========================================================================
2046
2047    #[test]
2048    fn test_compute_bbox_from_polygon_simple() {
2049        let mask = crate::Polygon::new(vec![vec![(0.1, 0.1), (0.5, 0.1), (0.5, 0.5), (0.1, 0.5)]]);
2050
2051        let bbox = compute_bbox_from_polygon(&mask, 100, 100);
2052
2053        assert!(bbox.is_some());
2054        let [x, y, w, h] = bbox.unwrap();
2055        assert!((x - 10.0).abs() < 1.0);
2056        assert!((y - 10.0).abs() < 1.0);
2057        assert!((w - 40.0).abs() < 1.0);
2058        assert!((h - 40.0).abs() < 1.0);
2059    }
2060
2061    #[test]
2062    fn test_compute_bbox_from_polygon_empty() {
2063        let mask = crate::Polygon::new(vec![]);
2064        let bbox = compute_bbox_from_polygon(&mask, 100, 100);
2065        assert!(bbox.is_none());
2066    }
2067
2068    #[test]
2069    fn test_compute_bbox_from_polygon_with_nan() {
2070        let mask = crate::Polygon::new(vec![vec![(f32::NAN, f32::NAN), (f32::NAN, f32::NAN)]]);
2071        let bbox = compute_bbox_from_polygon(&mask, 100, 100);
2072        assert!(bbox.is_none());
2073    }
2074
2075    #[test]
2076    fn test_compute_bbox_from_polygon_multiple_rings() {
2077        // Two disjoint regions
2078        let mask = crate::Polygon::new(vec![
2079            vec![(0.1, 0.1), (0.2, 0.1), (0.2, 0.2), (0.1, 0.2)],
2080            vec![(0.8, 0.8), (0.9, 0.8), (0.9, 0.9), (0.8, 0.9)],
2081        ]);
2082
2083        let bbox = compute_bbox_from_polygon(&mask, 100, 100);
2084
2085        assert!(bbox.is_some());
2086        let [x, y, w, h] = bbox.unwrap();
2087        // Should encompass both regions: 0.1 to 0.9
2088        assert!((x - 10.0).abs() < 1.0);
2089        assert!((y - 10.0).abs() < 1.0);
2090        assert!((w - 80.0).abs() < 1.0);
2091        assert!((h - 80.0).abs() < 1.0);
2092    }
2093
2094    // =========================================================================
2095    // polygon_to_polygon_string tests
2096    // =========================================================================
2097
2098    #[test]
2099    fn test_polygon_to_polygon_string() {
2100        // Create a simple triangle mask
2101        let mask = crate::Polygon::new(vec![vec![(0.1, 0.2), (0.3, 0.4), (0.5, 0.6)]]);
2102
2103        let result = polygon_to_polygon_string(&mask);
2104
2105        // Server expects 3D array format: [[[x1,y1],[x2,y2],...]]
2106        // NOT COCO format: [[x1,y1,x2,y2,...]]
2107        assert_eq!(result, "[[[0.1,0.2],[0.3,0.4],[0.5,0.6]]]");
2108    }
2109
2110    #[test]
2111    fn test_polygon_to_polygon_string_multiple_rings() {
2112        // Create a mask with two polygons (e.g., disjoint regions)
2113        // Each polygon needs at least 3 points to be valid
2114        let mask = crate::Polygon::new(vec![
2115            vec![(0.1, 0.1), (0.2, 0.1), (0.15, 0.2)], // Triangle 1
2116            vec![(0.5, 0.5), (0.6, 0.5), (0.55, 0.6)], // Triangle 2
2117        ]);
2118
2119        let result = polygon_to_polygon_string(&mask);
2120
2121        // Should produce two separate polygon rings
2122        assert_eq!(
2123            result,
2124            "[[[0.1,0.1],[0.2,0.1],[0.15,0.2]],[[0.5,0.5],[0.6,0.5],[0.55,0.6]]]"
2125        );
2126    }
2127
2128    #[test]
2129    fn test_polygon_to_polygon_string_filters_nan_values() {
2130        // Test that NaN values are filtered out
2131        let mask = crate::Polygon::new(vec![vec![
2132            (0.1, 0.2),
2133            (f32::NAN, 0.4), // NaN value - should be filtered
2134            (0.3, 0.4),
2135            (0.5, 0.6),
2136        ]]);
2137
2138        let result = polygon_to_polygon_string(&mask);
2139
2140        // NaN values should be filtered out, not serialized as "null"
2141        assert!(
2142            !result.contains("null"),
2143            "NaN values should be filtered out, got: {}",
2144            result
2145        );
2146        // Should have 3 valid points remaining
2147        assert_eq!(result, "[[[0.1,0.2],[0.3,0.4],[0.5,0.6]]]");
2148    }
2149
2150    #[test]
2151    fn test_polygon_to_polygon_string_filters_infinity() {
2152        // Test that Infinity values are filtered out
2153        let mask = crate::Polygon::new(vec![vec![
2154            (0.1, 0.2),
2155            (f32::INFINITY, 0.4), // Infinity - should be filtered
2156            (0.3, 0.4),
2157            (0.5, 0.6),
2158        ]]);
2159
2160        let result = polygon_to_polygon_string(&mask);
2161
2162        assert!(
2163            !result.contains("null"),
2164            "Infinity values should be filtered out"
2165        );
2166        assert_eq!(result, "[[[0.1,0.2],[0.3,0.4],[0.5,0.6]]]");
2167    }
2168
2169    #[test]
2170    fn test_polygon_to_polygon_string_too_few_points_after_filter() {
2171        // If filtering leaves fewer than 3 points, the ring should be dropped
2172        let mask = crate::Polygon::new(vec![vec![
2173            (0.1, 0.2),
2174            (f32::NAN, 0.4),      // filtered
2175            (f32::NAN, f32::NAN), // filtered
2176        ]]);
2177
2178        let result = polygon_to_polygon_string(&mask);
2179
2180        // Only 1 point remains, so the ring should be dropped
2181        assert_eq!(result, "[]");
2182    }
2183
2184    #[test]
2185    fn test_polygon_to_polygon_string_negative_infinity() {
2186        let mask = crate::Polygon::new(vec![vec![
2187            (0.1, 0.2),
2188            (f32::NEG_INFINITY, 0.4), // -Infinity - should be filtered
2189            (0.3, 0.4),
2190            (0.5, 0.6),
2191        ]]);
2192
2193        let result = polygon_to_polygon_string(&mask);
2194        assert_eq!(result, "[[[0.1,0.2],[0.3,0.4],[0.5,0.6]]]");
2195    }
2196
2197    // =========================================================================
2198    // CocoImportResult tests
2199    // =========================================================================
2200
2201    #[test]
2202    fn test_coco_import_result() {
2203        let result = CocoImportResult {
2204            total_images: 100,
2205            skipped: 30,
2206            imported: 70,
2207        };
2208
2209        assert_eq!(result.total_images, 100);
2210        assert_eq!(result.skipped, 30);
2211        assert_eq!(result.imported, 70);
2212    }
2213
2214    // =========================================================================
2215    // CocoUpdateResult tests
2216    // =========================================================================
2217
2218    #[test]
2219    fn test_coco_update_result() {
2220        let result = CocoUpdateResult {
2221            total_images: 500,
2222            updated: 450,
2223            not_found: 50,
2224        };
2225
2226        assert_eq!(result.total_images, 500);
2227        assert_eq!(result.updated, 450);
2228        assert_eq!(result.not_found, 50);
2229    }
2230
2231    // =========================================================================
2232    // read_coco_dataset_for_update tests
2233    // =========================================================================
2234
2235    #[test]
2236    fn test_read_coco_dataset_for_update_invalid_extension() {
2237        let result = read_coco_dataset_for_update(Path::new("/tmp/file.txt"));
2238        assert!(result.is_err());
2239        let err = result.unwrap_err();
2240        assert!(
2241            err.to_string()
2242                .contains("COCO update requires a JSON annotation file")
2243        );
2244    }
2245
2246    #[test]
2247    fn test_read_coco_dataset_for_update_nonexistent_json() {
2248        let result = read_coco_dataset_for_update(Path::new("/nonexistent/file.json"));
2249        assert!(result.is_err());
2250    }
2251
2252    #[test]
2253    fn test_read_coco_dataset_for_update_nonexistent_directory() {
2254        let result = read_coco_dataset_for_update(Path::new("/nonexistent_dir"));
2255        // Directory doesn't exist, so is_dir() returns false, and it's not .json
2256        assert!(result.is_err());
2257    }
2258
2259    // =========================================================================
2260    // build_sample_info_map tests
2261    // =========================================================================
2262
2263    #[test]
2264    fn test_build_sample_info_map_empty() {
2265        let samples: Vec<crate::Sample> = vec![];
2266        let map = build_sample_info_map(&samples);
2267        assert!(map.is_empty());
2268    }
2269
2270    #[test]
2271    fn test_build_sample_info_map_with_samples() {
2272        use crate::{Sample, SampleID};
2273
2274        let sample1 = Sample {
2275            image_name: Some("sample1".to_string()),
2276            id: Some(SampleID::from(1)),
2277            width: Some(640),
2278            height: Some(480),
2279            group: Some("train".to_string()),
2280            ..Default::default()
2281        };
2282
2283        let sample2 = Sample {
2284            image_name: Some("sample2".to_string()),
2285            id: Some(SampleID::from(2)),
2286            width: Some(1280),
2287            height: Some(720),
2288            group: None,
2289            ..Default::default()
2290        };
2291
2292        let samples = vec![sample1, sample2];
2293        let map = build_sample_info_map(&samples);
2294
2295        assert_eq!(map.len(), 2);
2296        assert!(map.contains_key("sample1"));
2297        assert!(map.contains_key("sample2"));
2298
2299        let (id1, w1, h1, g1) = map.get("sample1").unwrap();
2300        assert_eq!(*id1, SampleID::from(1));
2301        assert_eq!(*w1, 640);
2302        assert_eq!(*h1, 480);
2303        assert_eq!(g1.as_deref(), Some("train"));
2304
2305        let (id2, w2, h2, g2) = map.get("sample2").unwrap();
2306        assert_eq!(*id2, SampleID::from(2));
2307        assert_eq!(*w2, 1280);
2308        assert_eq!(*h2, 720);
2309        assert!(g2.is_none());
2310    }
2311
2312    #[test]
2313    fn test_build_sample_info_map_skips_incomplete_samples() {
2314        use crate::Sample;
2315
2316        // Sample missing id
2317        let sample_no_id = Sample {
2318            image_name: Some("no_id".to_string()),
2319            width: Some(640),
2320            height: Some(480),
2321            ..Default::default()
2322        };
2323
2324        // Sample missing name
2325        let sample_no_name = Sample {
2326            id: Some(crate::SampleID::from(1)),
2327            width: Some(640),
2328            height: Some(480),
2329            ..Default::default()
2330        };
2331
2332        // Sample missing dimensions
2333        let sample_no_dims = Sample {
2334            image_name: Some("no_dims".to_string()),
2335            id: Some(crate::SampleID::from(2)),
2336            ..Default::default()
2337        };
2338
2339        let samples = vec![sample_no_id, sample_no_name, sample_no_dims];
2340        let map = build_sample_info_map(&samples);
2341
2342        // All samples should be skipped because they're incomplete
2343        assert!(map.is_empty());
2344    }
2345
2346    // =========================================================================
2347    // UploadContext tests
2348    // =========================================================================
2349
2350    #[test]
2351    fn test_coco_import_options_clone() {
2352        // Test that options can be cloned (used in async contexts)
2353        let options = CocoImportOptions::default();
2354        let cloned = options.clone();
2355
2356        assert_eq!(options.batch_size, cloned.batch_size);
2357        assert_eq!(options.concurrency, cloned.concurrency);
2358        assert_eq!(options.include_masks, cloned.include_masks);
2359    }
2360
2361    // =========================================================================
2362    // CocoImportOptions custom values tests
2363    // =========================================================================
2364
2365    #[test]
2366    fn test_coco_import_options_custom() {
2367        let options = CocoImportOptions {
2368            include_masks: false,
2369            include_images: false,
2370            group: Some("test".to_string()),
2371            batch_size: 50,
2372            concurrency: 32,
2373            resume: false,
2374        };
2375
2376        assert!(!options.include_masks);
2377        assert!(!options.include_images);
2378        assert_eq!(options.group.as_deref(), Some("test"));
2379        assert_eq!(options.batch_size, 50);
2380        assert_eq!(options.concurrency, 32);
2381        assert!(!options.resume);
2382    }
2383
2384    #[test]
2385    fn test_coco_update_options_custom() {
2386        let options = CocoUpdateOptions {
2387            include_masks: false,
2388            group: Some("val".to_string()),
2389            batch_size: 25,
2390            concurrency: 16,
2391        };
2392
2393        assert!(!options.include_masks);
2394        assert_eq!(options.group.as_deref(), Some("val"));
2395        assert_eq!(options.batch_size, 25);
2396        assert_eq!(options.concurrency, 16);
2397    }
2398
2399    // =========================================================================
2400    // extract_sample_name tests
2401    // =========================================================================
2402
2403    #[test]
2404    fn test_extract_sample_name_simple() {
2405        assert_eq!(extract_sample_name("image.jpg"), "image");
2406    }
2407
2408    #[test]
2409    fn test_extract_sample_name_with_path() {
2410        assert_eq!(extract_sample_name("train2017/000001.jpg"), "000001");
2411    }
2412
2413    #[test]
2414    fn test_extract_sample_name_no_extension() {
2415        assert_eq!(extract_sample_name("image"), "image");
2416    }
2417
2418    #[test]
2419    fn test_extract_sample_name_multiple_dots() {
2420        assert_eq!(extract_sample_name("image.v2.final.jpg"), "image.v2.final");
2421    }
2422}