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::{verify::*, writer::CocoDatasetBuilder};
1476
1477    let coco_path = coco_path.as_ref();
1478
1479    // Read local COCO dataset
1480    log::info!("Reading local COCO dataset from {:?}", coco_path);
1481    let (coco_dataset, inferred_group) = if coco_path.is_dir() {
1482        // Read all annotation files and merge into one dataset
1483        let datasets = read_coco_directory(coco_path, &CocoReadOptions::default())?;
1484        log::info!("Found {} annotation files in directory", datasets.len());
1485
1486        let mut merged = CocoDataset::default();
1487        for (ds, group) in datasets {
1488            log::info!(
1489                "  - {} group: {} images, {} annotations",
1490                group,
1491                ds.images.len(),
1492                ds.annotations.len()
1493            );
1494            merge_coco_datasets(&mut merged, ds);
1495        }
1496        // When verifying entire directory, don't filter by group
1497        (merged, None)
1498    } else if coco_path.extension().is_some_and(|e| e == "json") {
1499        let reader = CocoReader::new();
1500        let dataset = reader.read_json(coco_path)?;
1501        let group = infer_group_from_filename(coco_path);
1502        (dataset, group)
1503    } else {
1504        return Err(Error::InvalidParameters(
1505            "COCO verification requires a JSON annotation file or directory.".to_string(),
1506        ));
1507    };
1508
1509    // Determine group filter (only when verifying a single JSON file)
1510    let effective_group = options.group.clone().or(inferred_group);
1511    let groups: Vec<String> = effective_group
1512        .as_ref()
1513        .map(|g| vec![g.clone()])
1514        .unwrap_or_default();
1515
1516    log::info!(
1517        "Local COCO: {} images, {} annotations",
1518        coco_dataset.images.len(),
1519        coco_dataset.annotations.len()
1520    );
1521
1522    // Fetch samples from Studio with annotations
1523    log::info!("Fetching samples from Studio dataset {}...", dataset_id);
1524    let annotation_types = [crate::AnnotationType::Box2d, crate::AnnotationType::Polygon];
1525
1526    let studio_samples = client
1527        .samples(
1528            dataset_id,
1529            Some(annotation_set_id),
1530            &annotation_types,
1531            &groups,
1532            &[],
1533            progress.clone(),
1534            None,
1535        )
1536        .await?;
1537
1538    let total_annotations: usize = studio_samples.iter().map(|s| s.annotations.len()).sum();
1539    log::info!(
1540        "Studio: {} samples, {} total annotations",
1541        studio_samples.len(),
1542        total_annotations
1543    );
1544
1545    // Convert Studio samples to COCO format for comparison
1546    let mut builder = CocoDatasetBuilder::new();
1547
1548    for sample in &studio_samples {
1549        let image_name = sample.image_name.as_deref().unwrap_or("unknown");
1550        let width = sample.width.unwrap_or(0);
1551        let height = sample.height.unwrap_or(0);
1552
1553        // Use the image_name directly if it has an extension, otherwise add .jpg
1554        let file_name = if image_name.contains('.') {
1555            image_name.to_string()
1556        } else {
1557            format!("{}.jpg", image_name)
1558        };
1559        let image_id = builder.add_image(&file_name, width, height);
1560
1561        for ann in &sample.annotations {
1562            // Get bbox from box2d if present, otherwise compute from polygon
1563            let bbox = if let Some(box2d) = ann.box2d() {
1564                Some(box2d_to_coco_bbox(box2d, width, height))
1565            } else if let Some(polygon) = ann.polygon() {
1566                // Compute bbox from polygon bounds
1567                compute_bbox_from_polygon(polygon, width, height)
1568            } else {
1569                None
1570            };
1571
1572            if let Some(bbox) = bbox {
1573                let label = ann.label().map(|s| s.as_str()).unwrap_or("unknown");
1574                let category_id = builder.add_category(label, None);
1575
1576                let segmentation = if options.verify_masks {
1577                    ann.polygon().map(|polygon| {
1578                        let coco_poly = polygon_to_coco_polygon(polygon, width, height);
1579                        CocoSegmentation::Polygon(coco_poly)
1580                    })
1581                } else {
1582                    None
1583                };
1584
1585                builder.add_annotation(image_id, category_id, bbox, segmentation);
1586            }
1587        }
1588    }
1589
1590    let studio_dataset = builder.build();
1591
1592    // Build sample name sets for comparison
1593    let coco_names: HashSet<String> = coco_dataset
1594        .images
1595        .iter()
1596        .map(|img| {
1597            Path::new(&img.file_name)
1598                .file_stem()
1599                .and_then(|s| s.to_str())
1600                .map(String::from)
1601                .unwrap_or_else(|| img.file_name.clone())
1602        })
1603        .collect();
1604
1605    let studio_names: HashSet<String> = studio_samples.iter().filter_map(|s| s.name()).collect();
1606
1607    let missing_images: Vec<String> = coco_names.difference(&studio_names).cloned().collect();
1608    let extra_images: Vec<String> = studio_names.difference(&coco_names).cloned().collect();
1609
1610    // Validate bounding boxes
1611    log::info!("Validating bounding boxes...");
1612    let bbox_validation = validate_bboxes(&coco_dataset, &studio_dataset);
1613
1614    // Validate masks if enabled
1615    log::info!("Validating segmentation masks...");
1616    let mask_validation = if options.verify_masks {
1617        validate_masks(&coco_dataset, &studio_dataset)
1618    } else {
1619        MaskValidationResult::new()
1620    };
1621
1622    // Validate categories
1623    let category_validation = validate_categories(&coco_dataset, &studio_dataset);
1624
1625    Ok(VerificationResult {
1626        coco_image_count: coco_dataset.images.len(),
1627        studio_image_count: studio_samples.len(),
1628        missing_images,
1629        extra_images,
1630        coco_annotation_count: coco_dataset.annotations.len(),
1631        studio_annotation_count: studio_dataset.annotations.len(),
1632        bbox_validation,
1633        mask_validation,
1634        category_validation,
1635    })
1636}
1637
1638#[cfg(test)]
1639mod tests {
1640    use super::*;
1641    use crate::coco::{CocoAnnotation, CocoCategory};
1642
1643    // =========================================================================
1644    // Options default tests
1645    // =========================================================================
1646
1647    #[test]
1648    fn test_coco_import_options_default() {
1649        let options = CocoImportOptions::default();
1650        assert!(options.include_masks);
1651        assert!(options.include_images);
1652        assert!(options.group.is_none());
1653        assert_eq!(options.batch_size, 100);
1654        assert_eq!(options.concurrency, 64);
1655        assert!(options.resume);
1656    }
1657
1658    #[test]
1659    fn test_coco_export_options_default() {
1660        let options = CocoExportOptions::default();
1661        assert!(options.groups.is_empty());
1662        assert!(options.include_masks);
1663        assert!(!options.include_images);
1664        assert!(!options.output_zip);
1665        assert!(!options.pretty_json);
1666        assert!(options.info.is_none());
1667    }
1668
1669    #[test]
1670    fn test_coco_update_options_default() {
1671        let options = CocoUpdateOptions::default();
1672        assert!(options.include_masks);
1673        assert!(options.group.is_none());
1674        assert_eq!(options.batch_size, 100);
1675        assert_eq!(options.concurrency, 64);
1676    }
1677
1678    #[test]
1679    fn test_coco_verify_options_default() {
1680        let options = CocoVerifyOptions::default();
1681        assert!(options.verify_masks);
1682        assert!(options.group.is_none());
1683    }
1684
1685    // =========================================================================
1686    // find_image_file tests
1687    // =========================================================================
1688
1689    #[test]
1690    fn test_find_image_file_nonexistent() {
1691        let result = find_image_file(Path::new("/nonexistent"), "test.jpg");
1692        assert!(result.is_none());
1693    }
1694
1695    #[test]
1696    fn test_find_image_file_with_subdirectory_in_name() {
1697        // Tests that file_name like "train2017/000001.jpg" is handled
1698        let result = find_image_file(Path::new("/nonexistent"), "train2017/image.jpg");
1699        assert!(result.is_none()); // Non-existent, but exercises the path logic
1700    }
1701
1702    // =========================================================================
1703    // infer_group_from_filename tests
1704    // =========================================================================
1705
1706    #[test]
1707    fn test_infer_group_from_filename_instances_train() {
1708        let path = Path::new("annotations/instances_train2017.json");
1709        assert_eq!(infer_group_from_filename(path), Some("train".to_string()));
1710    }
1711
1712    #[test]
1713    fn test_infer_group_from_filename_instances_val() {
1714        let path = Path::new("annotations/instances_val2017.json");
1715        assert_eq!(infer_group_from_filename(path), Some("val".to_string()));
1716    }
1717
1718    #[test]
1719    fn test_infer_group_from_filename_instances_test() {
1720        let path = Path::new("instances_test2017.json");
1721        assert_eq!(infer_group_from_filename(path), Some("test".to_string()));
1722    }
1723
1724    #[test]
1725    fn test_infer_group_from_filename_train_prefix() {
1726        let path = Path::new("train_annotations.json");
1727        assert_eq!(infer_group_from_filename(path), Some("train".to_string()));
1728    }
1729
1730    #[test]
1731    fn test_infer_group_from_filename_val_prefix() {
1732        let path = Path::new("val_data.json");
1733        assert_eq!(infer_group_from_filename(path), Some("val".to_string()));
1734    }
1735
1736    #[test]
1737    fn test_infer_group_from_filename_validation_prefix() {
1738        // The function checks "val" before "validation", so "validation_set" matches
1739        // "val"
1740        let path = Path::new("validation_set.json");
1741        assert_eq!(infer_group_from_filename(path), Some("val".to_string()));
1742    }
1743
1744    #[test]
1745    fn test_infer_group_from_filename_custom() {
1746        let path = Path::new("my_custom_annotations.json");
1747        assert_eq!(infer_group_from_filename(path), None);
1748    }
1749
1750    #[test]
1751    fn test_infer_group_from_filename_instances_2014() {
1752        let path = Path::new("instances_val2014.json");
1753        assert_eq!(infer_group_from_filename(path), Some("val".to_string()));
1754    }
1755
1756    // =========================================================================
1757    // merge_coco_datasets tests
1758    // =========================================================================
1759
1760    #[test]
1761    fn test_merge_coco_datasets_empty() {
1762        let mut target = CocoDataset::default();
1763        let source = CocoDataset::default();
1764        merge_coco_datasets(&mut target, source);
1765        assert!(target.images.is_empty());
1766        assert!(target.annotations.is_empty());
1767        assert!(target.categories.is_empty());
1768    }
1769
1770    #[test]
1771    fn test_merge_coco_datasets_basic() {
1772        let mut target = CocoDataset {
1773            images: vec![CocoImage {
1774                id: 1,
1775                file_name: "img1.jpg".to_string(),
1776                ..Default::default()
1777            }],
1778            categories: vec![CocoCategory {
1779                id: 1,
1780                name: "cat".to_string(),
1781                supercategory: None,
1782                ..Default::default()
1783            }],
1784            annotations: vec![CocoAnnotation {
1785                id: 1,
1786                image_id: 1,
1787                category_id: 1,
1788                ..Default::default()
1789            }],
1790            ..Default::default()
1791        };
1792
1793        let source = CocoDataset {
1794            images: vec![CocoImage {
1795                id: 2,
1796                file_name: "img2.jpg".to_string(),
1797                ..Default::default()
1798            }],
1799            categories: vec![CocoCategory {
1800                id: 2,
1801                name: "dog".to_string(),
1802                supercategory: None,
1803                ..Default::default()
1804            }],
1805            annotations: vec![CocoAnnotation {
1806                id: 2,
1807                image_id: 2,
1808                category_id: 2,
1809                ..Default::default()
1810            }],
1811            ..Default::default()
1812        };
1813
1814        merge_coco_datasets(&mut target, source);
1815
1816        assert_eq!(target.images.len(), 2);
1817        assert_eq!(target.categories.len(), 2);
1818        assert_eq!(target.annotations.len(), 2);
1819    }
1820
1821    #[test]
1822    fn test_merge_coco_datasets_deduplicates_images() {
1823        let mut target = CocoDataset {
1824            images: vec![CocoImage {
1825                id: 1,
1826                file_name: "img1.jpg".to_string(),
1827                ..Default::default()
1828            }],
1829            ..Default::default()
1830        };
1831
1832        let source = CocoDataset {
1833            images: vec![
1834                CocoImage {
1835                    id: 1, // Duplicate
1836                    file_name: "img1_dup.jpg".to_string(),
1837                    ..Default::default()
1838                },
1839                CocoImage {
1840                    id: 2,
1841                    file_name: "img2.jpg".to_string(),
1842                    ..Default::default()
1843                },
1844            ],
1845            ..Default::default()
1846        };
1847
1848        merge_coco_datasets(&mut target, source);
1849
1850        assert_eq!(target.images.len(), 2); // Only 2, not 3
1851        assert_eq!(target.images[0].file_name, "img1.jpg"); // Original preserved
1852    }
1853
1854    #[test]
1855    fn test_merge_coco_datasets_deduplicates_categories() {
1856        let mut target = CocoDataset {
1857            categories: vec![CocoCategory {
1858                id: 1,
1859                name: "person".to_string(),
1860                supercategory: None,
1861                ..Default::default()
1862            }],
1863            ..Default::default()
1864        };
1865
1866        let source = CocoDataset {
1867            categories: vec![
1868                CocoCategory {
1869                    id: 1, // Duplicate
1870                    name: "person_dup".to_string(),
1871                    supercategory: None,
1872                    ..Default::default()
1873                },
1874                CocoCategory {
1875                    id: 2,
1876                    name: "car".to_string(),
1877                    supercategory: None,
1878                    ..Default::default()
1879                },
1880            ],
1881            ..Default::default()
1882        };
1883
1884        merge_coco_datasets(&mut target, source);
1885
1886        assert_eq!(target.categories.len(), 2);
1887        assert_eq!(target.categories[0].name, "person"); // Original preserved
1888    }
1889
1890    #[test]
1891    fn test_merge_coco_datasets_info_preserved() {
1892        let mut target = CocoDataset::default();
1893
1894        let source = CocoDataset {
1895            info: CocoInfo {
1896                description: Some("Test dataset".to_string()),
1897                ..Default::default()
1898            },
1899            ..Default::default()
1900        };
1901
1902        merge_coco_datasets(&mut target, source);
1903
1904        assert_eq!(target.info.description, Some("Test dataset".to_string()));
1905    }
1906
1907    // =========================================================================
1908    // convert_coco_image_to_sample tests
1909    // =========================================================================
1910
1911    #[test]
1912    fn test_convert_coco_image_to_sample() {
1913        let image = CocoImage {
1914            id: 1,
1915            width: 640,
1916            height: 480,
1917            file_name: "test.jpg".to_string(),
1918            ..Default::default()
1919        };
1920
1921        let dataset = CocoDataset {
1922            images: vec![image.clone()],
1923            categories: vec![CocoCategory {
1924                id: 1,
1925                name: "person".to_string(),
1926                supercategory: None,
1927                ..Default::default()
1928            }],
1929            annotations: vec![CocoAnnotation {
1930                id: 1,
1931                image_id: 1,
1932                category_id: 1,
1933                bbox: [100.0, 50.0, 200.0, 150.0],
1934                area: 30000.0,
1935                iscrowd: 0,
1936                segmentation: None,
1937                score: None,
1938            }],
1939            ..Default::default()
1940        };
1941
1942        let index = CocoIndex::from_dataset(&dataset);
1943
1944        let sample = convert_coco_image_to_sample(
1945            &image,
1946            &index,
1947            Path::new("/tmp"),
1948            true,
1949            false, // Don't try to include images
1950            Some("train"),
1951        )
1952        .unwrap();
1953
1954        assert_eq!(sample.image_name, Some("test".to_string()));
1955        assert_eq!(sample.width, Some(640));
1956        assert_eq!(sample.height, Some(480));
1957        assert_eq!(sample.group, Some("train".to_string()));
1958        assert_eq!(sample.annotations.len(), 1);
1959        assert_eq!(sample.annotations[0].label(), Some(&"person".to_string()));
1960    }
1961
1962    #[test]
1963    fn test_convert_coco_image_to_sample_no_annotations() {
1964        let image = CocoImage {
1965            id: 1,
1966            width: 640,
1967            height: 480,
1968            file_name: "empty.jpg".to_string(),
1969            ..Default::default()
1970        };
1971
1972        let dataset = CocoDataset {
1973            images: vec![image.clone()],
1974            categories: vec![],
1975            annotations: vec![],
1976            ..Default::default()
1977        };
1978
1979        let index = CocoIndex::from_dataset(&dataset);
1980
1981        let sample =
1982            convert_coco_image_to_sample(&image, &index, Path::new("/tmp"), true, false, None)
1983                .unwrap();
1984
1985        assert_eq!(sample.image_name, Some("empty".to_string()));
1986        assert!(sample.annotations.is_empty());
1987    }
1988
1989    #[test]
1990    fn test_convert_coco_image_to_sample_with_mask() {
1991        let image = CocoImage {
1992            id: 1,
1993            width: 100,
1994            height: 100,
1995            file_name: "masked.jpg".to_string(),
1996            ..Default::default()
1997        };
1998
1999        let dataset = CocoDataset {
2000            images: vec![image.clone()],
2001            categories: vec![CocoCategory {
2002                id: 1,
2003                name: "object".to_string(),
2004                supercategory: None,
2005                ..Default::default()
2006            }],
2007            annotations: vec![CocoAnnotation {
2008                id: 1,
2009                image_id: 1,
2010                category_id: 1,
2011                bbox: [10.0, 10.0, 50.0, 50.0],
2012                area: 2500.0,
2013                iscrowd: 0,
2014                segmentation: Some(CocoSegmentation::Polygon(vec![vec![
2015                    10.0, 10.0, 60.0, 10.0, 60.0, 60.0, 10.0, 60.0,
2016                ]])),
2017                score: None,
2018            }],
2019            ..Default::default()
2020        };
2021
2022        let index = CocoIndex::from_dataset(&dataset);
2023
2024        // With masks
2025        let sample_with =
2026            convert_coco_image_to_sample(&image, &index, Path::new("/tmp"), true, false, None)
2027                .unwrap();
2028        assert!(sample_with.annotations[0].polygon().is_some());
2029
2030        // Without masks
2031        let sample_without =
2032            convert_coco_image_to_sample(&image, &index, Path::new("/tmp"), false, false, None)
2033                .unwrap();
2034        assert!(sample_without.annotations[0].polygon().is_none());
2035    }
2036
2037    // =========================================================================
2038    // compute_bbox_from_polygon tests
2039    // =========================================================================
2040
2041    #[test]
2042    fn test_compute_bbox_from_polygon_simple() {
2043        let mask = crate::Polygon::new(vec![vec![(0.1, 0.1), (0.5, 0.1), (0.5, 0.5), (0.1, 0.5)]]);
2044
2045        let bbox = compute_bbox_from_polygon(&mask, 100, 100);
2046
2047        assert!(bbox.is_some());
2048        let [x, y, w, h] = bbox.unwrap();
2049        assert!((x - 10.0).abs() < 1.0);
2050        assert!((y - 10.0).abs() < 1.0);
2051        assert!((w - 40.0).abs() < 1.0);
2052        assert!((h - 40.0).abs() < 1.0);
2053    }
2054
2055    #[test]
2056    fn test_compute_bbox_from_polygon_empty() {
2057        let mask = crate::Polygon::new(vec![]);
2058        let bbox = compute_bbox_from_polygon(&mask, 100, 100);
2059        assert!(bbox.is_none());
2060    }
2061
2062    #[test]
2063    fn test_compute_bbox_from_polygon_with_nan() {
2064        let mask = crate::Polygon::new(vec![vec![(f32::NAN, f32::NAN), (f32::NAN, f32::NAN)]]);
2065        let bbox = compute_bbox_from_polygon(&mask, 100, 100);
2066        assert!(bbox.is_none());
2067    }
2068
2069    #[test]
2070    fn test_compute_bbox_from_polygon_multiple_rings() {
2071        // Two disjoint regions
2072        let mask = crate::Polygon::new(vec![
2073            vec![(0.1, 0.1), (0.2, 0.1), (0.2, 0.2), (0.1, 0.2)],
2074            vec![(0.8, 0.8), (0.9, 0.8), (0.9, 0.9), (0.8, 0.9)],
2075        ]);
2076
2077        let bbox = compute_bbox_from_polygon(&mask, 100, 100);
2078
2079        assert!(bbox.is_some());
2080        let [x, y, w, h] = bbox.unwrap();
2081        // Should encompass both regions: 0.1 to 0.9
2082        assert!((x - 10.0).abs() < 1.0);
2083        assert!((y - 10.0).abs() < 1.0);
2084        assert!((w - 80.0).abs() < 1.0);
2085        assert!((h - 80.0).abs() < 1.0);
2086    }
2087
2088    // =========================================================================
2089    // polygon_to_polygon_string tests
2090    // =========================================================================
2091
2092    #[test]
2093    fn test_polygon_to_polygon_string() {
2094        // Create a simple triangle mask
2095        let mask = crate::Polygon::new(vec![vec![(0.1, 0.2), (0.3, 0.4), (0.5, 0.6)]]);
2096
2097        let result = polygon_to_polygon_string(&mask);
2098
2099        // Server expects 3D array format: [[[x1,y1],[x2,y2],...]]
2100        // NOT COCO format: [[x1,y1,x2,y2,...]]
2101        assert_eq!(result, "[[[0.1,0.2],[0.3,0.4],[0.5,0.6]]]");
2102    }
2103
2104    #[test]
2105    fn test_polygon_to_polygon_string_multiple_rings() {
2106        // Create a mask with two polygons (e.g., disjoint regions)
2107        // Each polygon needs at least 3 points to be valid
2108        let mask = crate::Polygon::new(vec![
2109            vec![(0.1, 0.1), (0.2, 0.1), (0.15, 0.2)], // Triangle 1
2110            vec![(0.5, 0.5), (0.6, 0.5), (0.55, 0.6)], // Triangle 2
2111        ]);
2112
2113        let result = polygon_to_polygon_string(&mask);
2114
2115        // Should produce two separate polygon rings
2116        assert_eq!(
2117            result,
2118            "[[[0.1,0.1],[0.2,0.1],[0.15,0.2]],[[0.5,0.5],[0.6,0.5],[0.55,0.6]]]"
2119        );
2120    }
2121
2122    #[test]
2123    fn test_polygon_to_polygon_string_filters_nan_values() {
2124        // Test that NaN values are filtered out
2125        let mask = crate::Polygon::new(vec![vec![
2126            (0.1, 0.2),
2127            (f32::NAN, 0.4), // NaN value - should be filtered
2128            (0.3, 0.4),
2129            (0.5, 0.6),
2130        ]]);
2131
2132        let result = polygon_to_polygon_string(&mask);
2133
2134        // NaN values should be filtered out, not serialized as "null"
2135        assert!(
2136            !result.contains("null"),
2137            "NaN values should be filtered out, got: {}",
2138            result
2139        );
2140        // Should have 3 valid points remaining
2141        assert_eq!(result, "[[[0.1,0.2],[0.3,0.4],[0.5,0.6]]]");
2142    }
2143
2144    #[test]
2145    fn test_polygon_to_polygon_string_filters_infinity() {
2146        // Test that Infinity values are filtered out
2147        let mask = crate::Polygon::new(vec![vec![
2148            (0.1, 0.2),
2149            (f32::INFINITY, 0.4), // Infinity - should be filtered
2150            (0.3, 0.4),
2151            (0.5, 0.6),
2152        ]]);
2153
2154        let result = polygon_to_polygon_string(&mask);
2155
2156        assert!(
2157            !result.contains("null"),
2158            "Infinity values should be filtered out"
2159        );
2160        assert_eq!(result, "[[[0.1,0.2],[0.3,0.4],[0.5,0.6]]]");
2161    }
2162
2163    #[test]
2164    fn test_polygon_to_polygon_string_too_few_points_after_filter() {
2165        // If filtering leaves fewer than 3 points, the ring should be dropped
2166        let mask = crate::Polygon::new(vec![vec![
2167            (0.1, 0.2),
2168            (f32::NAN, 0.4),      // filtered
2169            (f32::NAN, f32::NAN), // filtered
2170        ]]);
2171
2172        let result = polygon_to_polygon_string(&mask);
2173
2174        // Only 1 point remains, so the ring should be dropped
2175        assert_eq!(result, "[]");
2176    }
2177
2178    #[test]
2179    fn test_polygon_to_polygon_string_negative_infinity() {
2180        let mask = crate::Polygon::new(vec![vec![
2181            (0.1, 0.2),
2182            (f32::NEG_INFINITY, 0.4), // -Infinity - should be filtered
2183            (0.3, 0.4),
2184            (0.5, 0.6),
2185        ]]);
2186
2187        let result = polygon_to_polygon_string(&mask);
2188        assert_eq!(result, "[[[0.1,0.2],[0.3,0.4],[0.5,0.6]]]");
2189    }
2190
2191    // =========================================================================
2192    // CocoImportResult tests
2193    // =========================================================================
2194
2195    #[test]
2196    fn test_coco_import_result() {
2197        let result = CocoImportResult {
2198            total_images: 100,
2199            skipped: 30,
2200            imported: 70,
2201        };
2202
2203        assert_eq!(result.total_images, 100);
2204        assert_eq!(result.skipped, 30);
2205        assert_eq!(result.imported, 70);
2206    }
2207
2208    // =========================================================================
2209    // CocoUpdateResult tests
2210    // =========================================================================
2211
2212    #[test]
2213    fn test_coco_update_result() {
2214        let result = CocoUpdateResult {
2215            total_images: 500,
2216            updated: 450,
2217            not_found: 50,
2218        };
2219
2220        assert_eq!(result.total_images, 500);
2221        assert_eq!(result.updated, 450);
2222        assert_eq!(result.not_found, 50);
2223    }
2224
2225    // =========================================================================
2226    // read_coco_dataset_for_update tests
2227    // =========================================================================
2228
2229    #[test]
2230    fn test_read_coco_dataset_for_update_invalid_extension() {
2231        let result = read_coco_dataset_for_update(Path::new("/tmp/file.txt"));
2232        assert!(result.is_err());
2233        let err = result.unwrap_err();
2234        assert!(
2235            err.to_string()
2236                .contains("COCO update requires a JSON annotation file")
2237        );
2238    }
2239
2240    #[test]
2241    fn test_read_coco_dataset_for_update_nonexistent_json() {
2242        let result = read_coco_dataset_for_update(Path::new("/nonexistent/file.json"));
2243        assert!(result.is_err());
2244    }
2245
2246    #[test]
2247    fn test_read_coco_dataset_for_update_nonexistent_directory() {
2248        let result = read_coco_dataset_for_update(Path::new("/nonexistent_dir"));
2249        // Directory doesn't exist, so is_dir() returns false, and it's not .json
2250        assert!(result.is_err());
2251    }
2252
2253    // =========================================================================
2254    // build_sample_info_map tests
2255    // =========================================================================
2256
2257    #[test]
2258    fn test_build_sample_info_map_empty() {
2259        let samples: Vec<crate::Sample> = vec![];
2260        let map = build_sample_info_map(&samples);
2261        assert!(map.is_empty());
2262    }
2263
2264    #[test]
2265    fn test_build_sample_info_map_with_samples() {
2266        use crate::{Sample, SampleID};
2267
2268        let sample1 = Sample {
2269            image_name: Some("sample1".to_string()),
2270            id: Some(SampleID::from(1)),
2271            width: Some(640),
2272            height: Some(480),
2273            group: Some("train".to_string()),
2274            ..Default::default()
2275        };
2276
2277        let sample2 = Sample {
2278            image_name: Some("sample2".to_string()),
2279            id: Some(SampleID::from(2)),
2280            width: Some(1280),
2281            height: Some(720),
2282            group: None,
2283            ..Default::default()
2284        };
2285
2286        let samples = vec![sample1, sample2];
2287        let map = build_sample_info_map(&samples);
2288
2289        assert_eq!(map.len(), 2);
2290        assert!(map.contains_key("sample1"));
2291        assert!(map.contains_key("sample2"));
2292
2293        let (id1, w1, h1, g1) = map.get("sample1").unwrap();
2294        assert_eq!(*id1, SampleID::from(1));
2295        assert_eq!(*w1, 640);
2296        assert_eq!(*h1, 480);
2297        assert_eq!(g1.as_deref(), Some("train"));
2298
2299        let (id2, w2, h2, g2) = map.get("sample2").unwrap();
2300        assert_eq!(*id2, SampleID::from(2));
2301        assert_eq!(*w2, 1280);
2302        assert_eq!(*h2, 720);
2303        assert!(g2.is_none());
2304    }
2305
2306    #[test]
2307    fn test_build_sample_info_map_skips_incomplete_samples() {
2308        use crate::Sample;
2309
2310        // Sample missing id
2311        let sample_no_id = Sample {
2312            image_name: Some("no_id".to_string()),
2313            width: Some(640),
2314            height: Some(480),
2315            ..Default::default()
2316        };
2317
2318        // Sample missing name
2319        let sample_no_name = Sample {
2320            id: Some(crate::SampleID::from(1)),
2321            width: Some(640),
2322            height: Some(480),
2323            ..Default::default()
2324        };
2325
2326        // Sample missing dimensions
2327        let sample_no_dims = Sample {
2328            image_name: Some("no_dims".to_string()),
2329            id: Some(crate::SampleID::from(2)),
2330            ..Default::default()
2331        };
2332
2333        let samples = vec![sample_no_id, sample_no_name, sample_no_dims];
2334        let map = build_sample_info_map(&samples);
2335
2336        // All samples should be skipped because they're incomplete
2337        assert!(map.is_empty());
2338    }
2339
2340    // =========================================================================
2341    // UploadContext tests
2342    // =========================================================================
2343
2344    #[test]
2345    fn test_coco_import_options_clone() {
2346        // Test that options can be cloned (used in async contexts)
2347        let options = CocoImportOptions::default();
2348        let cloned = options.clone();
2349
2350        assert_eq!(options.batch_size, cloned.batch_size);
2351        assert_eq!(options.concurrency, cloned.concurrency);
2352        assert_eq!(options.include_masks, cloned.include_masks);
2353    }
2354
2355    // =========================================================================
2356    // CocoImportOptions custom values tests
2357    // =========================================================================
2358
2359    #[test]
2360    fn test_coco_import_options_custom() {
2361        let options = CocoImportOptions {
2362            include_masks: false,
2363            include_images: false,
2364            group: Some("test".to_string()),
2365            batch_size: 50,
2366            concurrency: 32,
2367            resume: false,
2368        };
2369
2370        assert!(!options.include_masks);
2371        assert!(!options.include_images);
2372        assert_eq!(options.group.as_deref(), Some("test"));
2373        assert_eq!(options.batch_size, 50);
2374        assert_eq!(options.concurrency, 32);
2375        assert!(!options.resume);
2376    }
2377
2378    #[test]
2379    fn test_coco_update_options_custom() {
2380        let options = CocoUpdateOptions {
2381            include_masks: false,
2382            group: Some("val".to_string()),
2383            batch_size: 25,
2384            concurrency: 16,
2385        };
2386
2387        assert!(!options.include_masks);
2388        assert_eq!(options.group.as_deref(), Some("val"));
2389        assert_eq!(options.batch_size, 25);
2390        assert_eq!(options.concurrency, 16);
2391    }
2392
2393    // =========================================================================
2394    // extract_sample_name tests
2395    // =========================================================================
2396
2397    #[test]
2398    fn test_extract_sample_name_simple() {
2399        assert_eq!(extract_sample_name("image.jpg"), "image");
2400    }
2401
2402    #[test]
2403    fn test_extract_sample_name_with_path() {
2404        assert_eq!(extract_sample_name("train2017/000001.jpg"), "000001");
2405    }
2406
2407    #[test]
2408    fn test_extract_sample_name_no_extension() {
2409        assert_eq!(extract_sample_name("image"), "image");
2410    }
2411
2412    #[test]
2413    fn test_extract_sample_name_multiple_dots() {
2414        assert_eq!(extract_sample_name("image.v2.final.jpg"), "image.v2.final");
2415    }
2416}