oximedia-scene 0.1.4

Scene understanding and AI-powered video analysis for OxiMedia
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! Scene captioning module for generating natural-language descriptions from scene features.
//!
//! Produces structured, template-driven captions for video scenes by combining
//! scene classification, object detection results, composition analysis, and motion
//! energy into human-readable descriptions. All generation is rule-based and
//! patent-free (no neural language models required).

use crate::error::{SceneError, SceneResult};
use serde::{Deserialize, Serialize};
use std::fmt;

/// Granularity level for caption generation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CaptionGranularity {
    /// Single-word or short phrase label.
    Brief,
    /// One-sentence description.
    Sentence,
    /// Multi-sentence paragraph.
    Paragraph,
}

/// Scene environment context.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SceneEnvironment {
    /// Outdoor daylight scene.
    OutdoorDay,
    /// Outdoor nighttime scene.
    OutdoorNight,
    /// Indoor scene.
    Indoor,
    /// Studio or controlled environment.
    Studio,
    /// Unknown or indeterminate environment.
    Unknown,
}

impl SceneEnvironment {
    /// Human-readable description.
    #[must_use]
    pub const fn description(&self) -> &'static str {
        match self {
            Self::OutdoorDay => "an outdoor daylight setting",
            Self::OutdoorNight => "an outdoor nighttime setting",
            Self::Indoor => "an indoor environment",
            Self::Studio => "a studio or controlled environment",
            Self::Unknown => "an unspecified environment",
        }
    }
}

/// Motion descriptor for captions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MotionDescriptor {
    /// No significant motion.
    Static,
    /// Slow, gentle motion.
    Slow,
    /// Moderate motion.
    Moderate,
    /// Fast, dynamic motion.
    Fast,
    /// Rapid, chaotic motion.
    Rapid,
}

impl MotionDescriptor {
    /// Build from normalised energy (0.0–1.0).
    #[must_use]
    pub fn from_energy(energy: f32) -> Self {
        if energy < 0.05 {
            Self::Static
        } else if energy < 0.2 {
            Self::Slow
        } else if energy < 0.45 {
            Self::Moderate
        } else if energy < 0.7 {
            Self::Fast
        } else {
            Self::Rapid
        }
    }

    /// Motion adverb for use in captions.
    #[must_use]
    pub const fn adverb(&self) -> &'static str {
        match self {
            Self::Static => "still",
            Self::Slow => "slowly",
            Self::Moderate => "steadily",
            Self::Fast => "quickly",
            Self::Rapid => "rapidly",
        }
    }

    /// Motion adjective for use in captions.
    #[must_use]
    pub const fn adjective(&self) -> &'static str {
        match self {
            Self::Static => "static",
            Self::Slow => "slow-paced",
            Self::Moderate => "moderate",
            Self::Fast => "fast-paced",
            Self::Rapid => "high-energy",
        }
    }
}

/// A detected object entry for caption generation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaptionObject {
    /// Object category label.
    pub label: String,
    /// Confidence (0.0–1.0).
    pub confidence: f32,
    /// Approximate count of this object in frame.
    pub count: u32,
}

impl CaptionObject {
    /// Create a new caption object.
    pub fn new(label: impl Into<String>, confidence: f32, count: u32) -> Self {
        Self {
            label: label.into(),
            confidence: confidence.clamp(0.0, 1.0),
            count,
        }
    }
}

/// Composition style for caption context.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompositionStyle {
    /// Subject centred in frame.
    Centred,
    /// Rule-of-thirds placement.
    RuleOfThirds,
    /// Strongly symmetrical composition.
    Symmetrical,
    /// Leading lines drawing eye.
    LeadingLines,
    /// Cluttered or complex composition.
    Complex,
    /// No dominant composition pattern.
    Undefined,
}

impl CompositionStyle {
    /// Phrase fragment describing the composition.
    #[must_use]
    pub const fn phrase(&self) -> &'static str {
        match self {
            Self::Centred => "with a centred subject",
            Self::RuleOfThirds => "composed using the rule of thirds",
            Self::Symmetrical => "with strong symmetry",
            Self::LeadingLines => "with leading lines guiding the eye",
            Self::Complex => "with a complex, layered composition",
            Self::Undefined => "",
        }
    }
}

/// Input descriptor for the scene captioner.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaptionInput {
    /// Scene environment context.
    pub environment: SceneEnvironment,
    /// Dominant subject/objects detected.
    pub objects: Vec<CaptionObject>,
    /// Normalised motion energy (0.0–1.0).
    pub motion_energy: f32,
    /// Composition style hint.
    pub composition: CompositionStyle,
    /// Optional mood descriptor (e.g. "tense", "serene", "joyful").
    pub mood: Option<String>,
    /// Optional activity description (e.g. "running", "conversation").
    pub activity: Option<String>,
    /// Number of visible people (-1 = unknown).
    pub person_count: i32,
}

impl CaptionInput {
    /// Create a minimal caption input.
    #[must_use]
    pub fn new(environment: SceneEnvironment) -> Self {
        Self {
            environment,
            objects: Vec::new(),
            motion_energy: 0.0,
            composition: CompositionStyle::Undefined,
            mood: None,
            activity: None,
            person_count: -1,
        }
    }

    /// Add a detected object.
    #[must_use]
    pub fn with_object(mut self, obj: CaptionObject) -> Self {
        self.objects.push(obj);
        self
    }

    /// Set normalised motion energy.
    #[must_use]
    pub fn with_motion_energy(mut self, energy: f32) -> Self {
        self.motion_energy = energy.clamp(0.0, 1.0);
        self
    }

    /// Set composition style.
    #[must_use]
    pub fn with_composition(mut self, style: CompositionStyle) -> Self {
        self.composition = style;
        self
    }

    /// Set mood hint.
    #[must_use]
    pub fn with_mood(mut self, mood: impl Into<String>) -> Self {
        self.mood = Some(mood.into());
        self
    }

    /// Set activity hint.
    #[must_use]
    pub fn with_activity(mut self, activity: impl Into<String>) -> Self {
        self.activity = Some(activity.into());
        self
    }

    /// Set person count.
    #[must_use]
    pub fn with_person_count(mut self, count: i32) -> Self {
        self.person_count = count;
        self
    }
}

/// A generated caption at a specified granularity.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Caption {
    /// Caption text.
    pub text: String,
    /// Granularity used.
    pub granularity: CaptionGranularity,
    /// Estimated confidence in caption quality (0.0–1.0).
    pub confidence: f32,
}

impl Caption {
    fn new(text: String, granularity: CaptionGranularity, confidence: f32) -> Self {
        Self {
            text,
            granularity,
            confidence: confidence.clamp(0.0, 1.0),
        }
    }
}

impl fmt::Display for Caption {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.text)
    }
}

/// Configuration for the scene captioner.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaptionerConfig {
    /// Minimum object confidence to include in caption.
    pub min_object_confidence: f32,
    /// Maximum number of distinct objects to mention.
    pub max_objects_mentioned: usize,
    /// Whether to include composition details in sentence/paragraph modes.
    pub include_composition: bool,
    /// Whether to include mood/atmosphere details.
    pub include_mood: bool,
}

impl Default for CaptionerConfig {
    fn default() -> Self {
        Self {
            min_object_confidence: 0.4,
            max_objects_mentioned: 4,
            include_composition: true,
            include_mood: true,
        }
    }
}

impl CaptionerConfig {
    /// Validate configuration parameters.
    pub fn validate(&self) -> SceneResult<()> {
        if self.min_object_confidence < 0.0 || self.min_object_confidence > 1.0 {
            return Err(SceneError::InvalidParameter(
                "min_object_confidence must be in [0.0, 1.0]".into(),
            ));
        }
        if self.max_objects_mentioned == 0 {
            return Err(SceneError::InvalidParameter(
                "max_objects_mentioned must be >= 1".into(),
            ));
        }
        Ok(())
    }
}

/// Scene captioner: generates natural-language captions from structured scene descriptors.
///
/// All text generation is template-driven and deterministic — no neural LM required.
pub struct SceneCaptioner {
    config: CaptionerConfig,
}

impl Default for SceneCaptioner {
    fn default() -> Self {
        Self::new()
    }
}

impl SceneCaptioner {
    /// Create with default configuration.
    #[must_use]
    pub fn new() -> Self {
        Self {
            config: CaptionerConfig::default(),
        }
    }

    /// Create with custom configuration.
    pub fn with_config(config: CaptionerConfig) -> SceneResult<Self> {
        config.validate()?;
        Ok(Self { config })
    }

    /// Generate a caption at the requested granularity.
    pub fn caption(&self, input: &CaptionInput, granularity: CaptionGranularity) -> Caption {
        match granularity {
            CaptionGranularity::Brief => self.generate_brief(input),
            CaptionGranularity::Sentence => self.generate_sentence(input),
            CaptionGranularity::Paragraph => self.generate_paragraph(input),
        }
    }

    /// Generate all granularity levels at once.
    pub fn caption_all(&self, input: &CaptionInput) -> [Caption; 3] {
        [
            self.caption(input, CaptionGranularity::Brief),
            self.caption(input, CaptionGranularity::Sentence),
            self.caption(input, CaptionGranularity::Paragraph),
        ]
    }

    // ── internal generators ──────────────────────────────────────────────────

    fn confident_objects<'a>(&self, input: &'a CaptionInput) -> Vec<&'a CaptionObject> {
        let mut objs: Vec<&CaptionObject> = input
            .objects
            .iter()
            .filter(|o| o.confidence >= self.config.min_object_confidence)
            .collect();
        // Sort by confidence descending, then trim.
        objs.sort_by(|a, b| {
            b.confidence
                .partial_cmp(&a.confidence)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        objs.truncate(self.config.max_objects_mentioned);
        objs
    }

    fn generate_brief(&self, input: &CaptionInput) -> Caption {
        let motion = MotionDescriptor::from_energy(input.motion_energy);
        let text = if let Some(activity) = &input.activity {
            activity.clone()
        } else {
            let env = match input.environment {
                SceneEnvironment::OutdoorDay => "outdoor scene",
                SceneEnvironment::OutdoorNight => "night scene",
                SceneEnvironment::Indoor => "indoor scene",
                SceneEnvironment::Studio => "studio shot",
                SceneEnvironment::Unknown => "scene",
            };
            format!("{} {}", motion.adjective(), env)
        };
        Caption::new(text, CaptionGranularity::Brief, 0.7)
    }

    fn generate_sentence(&self, input: &CaptionInput) -> Caption {
        let motion = MotionDescriptor::from_energy(input.motion_energy);
        let objs = self.confident_objects(input);

        // Subject fragment
        let subject = self.build_subject_fragment(input, &objs);

        // Action / motion fragment
        let action = if let Some(act) = &input.activity {
            format!(", {}", act)
        } else if motion != MotionDescriptor::Static {
            format!(", moving {}", motion.adverb())
        } else {
            String::new()
        };

        // Environment
        let env_frag = format!(" in {}", input.environment.description());

        // Composition
        let comp_frag = if self.config.include_composition {
            let phrase = input.composition.phrase();
            if phrase.is_empty() {
                String::new()
            } else {
                format!(", {}", phrase)
            }
        } else {
            String::new()
        };

        let text = format!("{}{}{}{}", subject, action, env_frag, comp_frag);
        // Capitalise first letter
        let text = capitalise_first(&text);
        Caption::new(text, CaptionGranularity::Sentence, 0.75)
    }

    fn generate_paragraph(&self, input: &CaptionInput) -> Caption {
        let sentence_caption = self.generate_sentence(input);
        let mut parts: Vec<String> = vec![sentence_caption.text.clone()];

        let objs = self.confident_objects(input);

        // Object detail sentence
        if objs.len() > 1 {
            let obj_labels: Vec<String> = objs
                .iter()
                .map(|o| {
                    if o.count > 1 {
                        format!("{} {}s", o.count, o.label)
                    } else {
                        o.label.clone()
                    }
                })
                .collect();
            let obj_text = join_with_oxford_comma(&obj_labels);
            parts.push(format!("The scene contains {}.", obj_text));
        }

        // Motion detail sentence
        let motion = MotionDescriptor::from_energy(input.motion_energy);
        let motion_sentence = match motion {
            MotionDescriptor::Static => {
                "The frame is largely static with minimal movement.".to_string()
            }
            MotionDescriptor::Slow => "Motion is gentle and unhurried.".to_string(),
            MotionDescriptor::Moderate => {
                "There is moderate movement throughout the frame.".to_string()
            }
            MotionDescriptor::Fast => "The scene features fast, dynamic motion.".to_string(),
            MotionDescriptor::Rapid => {
                "Rapid, high-energy movement dominates the frame.".to_string()
            }
        };
        parts.push(motion_sentence);

        // Mood sentence
        if self.config.include_mood {
            if let Some(mood) = &input.mood {
                parts.push(format!("The overall atmosphere is {}.", mood));
            }
        }

        let text = parts.join(" ");
        Caption::new(text, CaptionGranularity::Paragraph, 0.8)
    }

    fn build_subject_fragment<'a>(
        &self,
        input: &CaptionInput,
        objs: &[&'a CaptionObject],
    ) -> String {
        if input.person_count > 0 {
            let person_label = if input.person_count == 1 {
                "A person".to_string()
            } else {
                format!("{} people", input.person_count)
            };
            return person_label;
        }
        if let Some(first_obj) = objs.first() {
            let article = if starts_with_vowel(&first_obj.label) {
                "An"
            } else {
                "A"
            };
            return format!("{} {}", article, first_obj.label);
        }
        // Fallback to environment
        capitalise_first(input.environment.description())
    }
}

// ── helpers ──────────────────────────────────────────────────────────────────

fn capitalise_first(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        None => String::new(),
        Some(c) => c.to_uppercase().to_string() + chars.as_str(),
    }
}

fn starts_with_vowel(s: &str) -> bool {
    matches!(
        s.chars().next().map(|c| c.to_ascii_lowercase()),
        Some('a' | 'e' | 'i' | 'o' | 'u')
    )
}

fn join_with_oxford_comma(items: &[String]) -> String {
    match items.len() {
        0 => String::new(),
        1 => items[0].clone(),
        2 => format!("{} and {}", items[0], items[1]),
        _ => {
            let all_but_last = items[..items.len() - 1].join(", ");
            format!("{}, and {}", all_but_last, items[items.len() - 1])
        }
    }
}

// ── tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn make_input() -> CaptionInput {
        CaptionInput::new(SceneEnvironment::OutdoorDay)
            .with_motion_energy(0.3)
            .with_composition(CompositionStyle::RuleOfThirds)
            .with_mood("serene")
            .with_activity("a group of people walking")
            .with_person_count(3)
            .with_object(CaptionObject::new("dog", 0.85, 1))
            .with_object(CaptionObject::new("tree", 0.72, 2))
    }

    #[test]
    fn test_brief_caption_with_activity() {
        let captioner = SceneCaptioner::new();
        let input = make_input();
        let cap = captioner.caption(&input, CaptionGranularity::Brief);
        assert!(!cap.text.is_empty());
        assert_eq!(cap.granularity, CaptionGranularity::Brief);
    }

    #[test]
    fn test_brief_caption_without_activity() {
        let captioner = SceneCaptioner::new();
        let input = CaptionInput::new(SceneEnvironment::Indoor).with_motion_energy(0.0);
        let cap = captioner.caption(&input, CaptionGranularity::Brief);
        assert!(cap.text.contains("static") || cap.text.contains("indoor"));
    }

    #[test]
    fn test_sentence_caption_contains_environment() {
        let captioner = SceneCaptioner::new();
        let input = CaptionInput::new(SceneEnvironment::OutdoorNight).with_person_count(1);
        let cap = captioner.caption(&input, CaptionGranularity::Sentence);
        assert!(
            cap.text.to_lowercase().contains("night")
                || cap.text.to_lowercase().contains("outdoor")
        );
    }

    #[test]
    fn test_paragraph_caption_multi_sentence() {
        let captioner = SceneCaptioner::new();
        let input = make_input();
        let cap = captioner.caption(&input, CaptionGranularity::Paragraph);
        // Paragraph should contain at least two sentences
        let sentence_count = cap.text.matches('.').count();
        assert!(
            sentence_count >= 2,
            "Expected >= 2 sentences, got {sentence_count}"
        );
    }

    #[test]
    fn test_caption_all_returns_three() {
        let captioner = SceneCaptioner::new();
        let input = make_input();
        let caps = captioner.caption_all(&input);
        assert_eq!(caps.len(), 3);
        assert_eq!(caps[0].granularity, CaptionGranularity::Brief);
        assert_eq!(caps[1].granularity, CaptionGranularity::Sentence);
        assert_eq!(caps[2].granularity, CaptionGranularity::Paragraph);
    }

    #[test]
    fn test_motion_descriptor_from_energy() {
        assert_eq!(MotionDescriptor::from_energy(0.0), MotionDescriptor::Static);
        assert_eq!(MotionDescriptor::from_energy(0.1), MotionDescriptor::Slow);
        assert_eq!(
            MotionDescriptor::from_energy(0.3),
            MotionDescriptor::Moderate
        );
        assert_eq!(MotionDescriptor::from_energy(0.6), MotionDescriptor::Fast);
        assert_eq!(MotionDescriptor::from_energy(0.95), MotionDescriptor::Rapid);
    }

    #[test]
    fn test_config_validation_error() {
        let bad_config = CaptionerConfig {
            min_object_confidence: 1.5,
            ..Default::default()
        };
        assert!(bad_config.validate().is_err());

        let zero_obj_config = CaptionerConfig {
            max_objects_mentioned: 0,
            ..Default::default()
        };
        assert!(zero_obj_config.validate().is_err());
    }

    #[test]
    fn test_oxford_comma() {
        assert_eq!(join_with_oxford_comma(&[]), "");
        assert_eq!(join_with_oxford_comma(&["a".to_string()]), "a");
        assert_eq!(
            join_with_oxford_comma(&["a".to_string(), "b".to_string()]),
            "a and b"
        );
        assert_eq!(
            join_with_oxford_comma(&["a".to_string(), "b".to_string(), "c".to_string()]),
            "a, b, and c"
        );
    }

    #[test]
    fn test_object_confidence_filter() {
        let config = CaptionerConfig {
            min_object_confidence: 0.8,
            ..Default::default()
        };
        let captioner = SceneCaptioner::with_config(config).expect("valid config");
        let input = CaptionInput::new(SceneEnvironment::Studio)
            .with_object(CaptionObject::new("chair", 0.9, 1))
            .with_object(CaptionObject::new("table", 0.5, 1)); // below threshold
        let cap = captioner.caption(&input, CaptionGranularity::Paragraph);
        // "table" should not appear (below threshold)
        assert!(!cap.text.to_lowercase().contains("table"));
    }

    #[test]
    fn test_caption_display() {
        let cap = Caption::new(
            "A sunny scene.".to_string(),
            CaptionGranularity::Sentence,
            0.9,
        );
        assert_eq!(format!("{}", cap), "A sunny scene.");
    }
}