voirs-cli 0.1.0-beta.1

Command-line interface for VoiRS speech synthesis
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
//! Voice search functionality.

use crate::error::{CliError, Result};
use std::collections::HashMap;
use voirs_sdk::config::AppConfig;
use voirs_sdk::types::VoiceConfig;
use voirs_sdk::{QualityLevel, Result as VoirsResult, VoirsPipeline};

/// Voice search functionality
pub struct VoiceSearch {
    /// Available voices
    voices: Vec<VoiceConfig>,
}

impl VoiceSearch {
    /// Create a new voice search instance
    pub async fn new(config: &AppConfig) -> Result<Self> {
        let pipeline = VoirsPipeline::builder().build().await?;
        let voices = pipeline.list_voices().await?;

        Ok(Self { voices })
    }

    /// Search voices by query string
    pub fn search(&self, query: &str) -> Vec<VoiceSearchResult> {
        let query_lower = query.to_lowercase();
        let terms: Vec<&str> = query_lower.split_whitespace().collect();

        let mut results = Vec::new();

        for voice in &self.voices {
            let score = self.calculate_relevance_score(voice, &terms);
            if score > 0.0 {
                results.push(VoiceSearchResult {
                    voice: voice.clone(),
                    relevance_score: score,
                    match_reasons: self.get_match_reasons(voice, &terms),
                });
            }
        }

        // Sort by relevance score (highest first)
        results.sort_by(|a, b| {
            b.relevance_score
                .partial_cmp(&a.relevance_score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        results
    }

    /// Search voices by specific criteria
    pub fn search_by_criteria(&self, criteria: &VoiceSearchCriteria) -> Vec<VoiceSearchResult> {
        let mut results = Vec::new();

        for voice in &self.voices {
            let mut score = 1.0;
            let mut reasons = Vec::new();
            let mut matches = true;

            // Language filter
            if let Some(ref language) = criteria.language {
                if voice.language.as_str().to_lowercase() != language.to_lowercase() {
                    matches = false;
                } else {
                    reasons.push("Matching language".to_string());
                }
            }

            // Gender filter
            if let Some(ref gender) = criteria.gender {
                if let Some(voice_gender) = &voice.characteristics.gender {
                    if format!("{:?}", voice_gender).to_lowercase() != gender.to_lowercase() {
                        matches = false;
                    } else {
                        reasons.push("Matching gender".to_string());
                        score += 0.5;
                    }
                } else if criteria.require_gender {
                    matches = false;
                }
            }

            // Age filter
            if let Some(ref age) = criteria.age {
                if let Some(voice_age) = &voice.characteristics.age {
                    if format!("{:?}", voice_age).to_lowercase() != age.to_lowercase() {
                        matches = false;
                    } else {
                        reasons.push("Matching age".to_string());
                        score += 0.3;
                    }
                } else if criteria.require_age {
                    matches = false;
                }
            }

            // Style filter
            if let Some(ref style) = criteria.style {
                if format!("{:?}", voice.characteristics.style).to_lowercase()
                    != style.to_lowercase()
                {
                    matches = false;
                } else {
                    reasons.push("Matching style".to_string());
                    score += 0.4;
                }
            }

            // Quality filter
            if let Some(ref quality) = criteria.min_quality {
                let voice_quality_score = match voice.characteristics.quality {
                    QualityLevel::Low => 1,
                    QualityLevel::Medium => 2,
                    QualityLevel::High => 3,
                    QualityLevel::Ultra => 4,
                };
                let min_quality_score = match quality.as_str() {
                    "low" => 1,
                    "medium" => 2,
                    "high" => 3,
                    "ultra" => 4,
                    _ => 1,
                };

                if voice_quality_score < min_quality_score {
                    matches = false;
                } else if voice_quality_score >= min_quality_score {
                    reasons.push("Meets quality requirements".to_string());
                    score += 0.2;
                }
            }

            // Emotion support filter
            if criteria.emotion_support {
                if voice.characteristics.emotion_support {
                    reasons.push("Supports emotions".to_string());
                    score += 0.3;
                } else if criteria.require_emotion_support {
                    matches = false;
                }
            }

            if matches {
                results.push(VoiceSearchResult {
                    voice: voice.clone(),
                    relevance_score: score,
                    match_reasons: reasons,
                });
            }
        }

        // Sort by relevance score
        results.sort_by(|a, b| {
            b.relevance_score
                .partial_cmp(&a.relevance_score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        results
    }

    /// Get voice recommendations based on text content
    pub fn recommend_for_text(&self, text: &str) -> Vec<VoiceSearchResult> {
        let mut criteria = VoiceSearchCriteria::default();

        // Analyze text to suggest appropriate voice characteristics
        let word_count = text.split_whitespace().count();
        let has_questions = text.contains('?');
        let has_exclamations = text.contains('!');
        let is_formal = self.is_formal_text(text);

        // Suggest style based on content
        if has_exclamations || text.to_uppercase() == text {
            criteria.style = Some("Energetic".to_string());
        } else if has_questions || is_formal {
            criteria.style = Some("Professional".to_string());
        } else if word_count > 100 {
            criteria.style = Some("Narrative".to_string());
        }

        // Suggest quality based on text length
        if word_count > 50 {
            criteria.min_quality = Some("high".to_string());
        } else {
            criteria.min_quality = Some("medium".to_string());
        }

        self.search_by_criteria(&criteria)
    }

    /// Calculate relevance score for a voice given search terms
    fn calculate_relevance_score(&self, voice: &VoiceConfig, terms: &[&str]) -> f32 {
        let mut score = 0.0;

        for term in terms {
            // Check voice ID (highest weight)
            if voice.id.to_lowercase().contains(term) {
                score += 3.0;
            }

            // Check voice name
            if voice.name.to_lowercase().contains(term) {
                score += 2.5;
            }

            // Check language
            if voice.language.as_str().to_lowercase().contains(term) {
                score += 2.0;
            }

            // Check description in metadata
            if let Some(description) = voice.metadata.get("description") {
                if description.to_lowercase().contains(term) {
                    score += 1.5;
                }
            }

            // Check characteristics
            if let Some(gender) = &voice.characteristics.gender {
                if format!("{:?}", gender).to_lowercase().contains(term) {
                    score += 1.0;
                }
            }

            if let Some(age) = &voice.characteristics.age {
                if format!("{:?}", age).to_lowercase().contains(term) {
                    score += 1.0;
                }
            }

            if format!("{:?}", voice.characteristics.style)
                .to_lowercase()
                .contains(term)
            {
                score += 1.0;
            }

            // Check metadata tags
            for (key, value) in &voice.metadata {
                if key.to_lowercase().contains(term) || value.to_lowercase().contains(term) {
                    score += 0.5;
                }
            }
        }

        score
    }

    /// Get reasons why a voice matched the search terms
    fn get_match_reasons(&self, voice: &VoiceConfig, terms: &[&str]) -> Vec<String> {
        let mut reasons = Vec::new();

        for term in terms {
            if voice.id.to_lowercase().contains(term) {
                reasons.push(format!("ID contains '{}'", term));
            }
            if voice.name.to_lowercase().contains(term) {
                reasons.push(format!("Name contains '{}'", term));
            }
            if voice.language.as_str().to_lowercase().contains(term) {
                reasons.push(format!("Language matches '{}'", term));
            }
            if let Some(description) = voice.metadata.get("description") {
                if description.to_lowercase().contains(term) {
                    reasons.push(format!("Description contains '{}'", term));
                }
            }
        }

        if reasons.is_empty() {
            reasons.push("General match".to_string());
        }

        reasons
    }

    /// Check if text appears to be formal
    fn is_formal_text(&self, text: &str) -> bool {
        let formal_indicators = [
            "please",
            "thank you",
            "regarding",
            "furthermore",
            "however",
            "therefore",
            "moreover",
            "nevertheless",
            "consequently",
            "accordingly",
        ];

        let text_lower = text.to_lowercase();
        formal_indicators
            .iter()
            .any(|&indicator| text_lower.contains(indicator))
    }

    /// Get voice statistics
    pub fn get_statistics(&self) -> VoiceStatistics {
        let mut stats = VoiceStatistics::default();

        stats.total_voices = self.voices.len();

        // Language distribution
        for voice in &self.voices {
            let lang = voice.language.as_str();
            *stats.languages.entry(lang.to_string()).or_insert(0) += 1;
        }

        // Gender distribution
        for voice in &self.voices {
            if let Some(gender) = &voice.characteristics.gender {
                let gender_str = format!("{:?}", gender);
                *stats.genders.entry(gender_str).or_insert(0) += 1;
            } else {
                *stats.genders.entry("Unknown".to_string()).or_insert(0) += 1;
            }
        }

        // Quality distribution
        for voice in &self.voices {
            let quality_str = format!("{:?}", voice.characteristics.quality);
            *stats.qualities.entry(quality_str).or_insert(0) += 1;
        }

        // Emotion support
        stats.emotion_support_count = self
            .voices
            .iter()
            .filter(|v| v.characteristics.emotion_support)
            .count();

        stats
    }
}

/// Voice search criteria
#[derive(Debug, Default)]
pub struct VoiceSearchCriteria {
    pub language: Option<String>,
    pub gender: Option<String>,
    pub age: Option<String>,
    pub style: Option<String>,
    pub min_quality: Option<String>,
    pub emotion_support: bool,
    pub require_gender: bool,
    pub require_age: bool,
    pub require_emotion_support: bool,
}

/// Voice search result
#[derive(Debug, Clone)]
pub struct VoiceSearchResult {
    pub voice: VoiceConfig,
    pub relevance_score: f32,
    pub match_reasons: Vec<String>,
}

/// Voice statistics
#[derive(Debug, Default)]
pub struct VoiceStatistics {
    pub total_voices: usize,
    pub languages: HashMap<String, usize>,
    pub genders: HashMap<String, usize>,
    pub qualities: HashMap<String, usize>,
    pub emotion_support_count: usize,
}

/// Configuration for voice search command
///
/// Consolidates all search parameters for finding voices in the VoiRS voice
/// registry. Supports text-based search, filtering by characteristics, and
/// voice statistics display.
///
/// # Examples
///
/// Basic text search:
/// ```no_run
/// use voirs_cli::commands::voice_search::VoiceSearchCommandConfig;
///
/// let config = VoiceSearchCommandConfig {
///     query: Some("friendly female voice"),
///     language: None,
///     gender: None,
///     age: None,
///     style: None,
///     min_quality: None,
///     emotion_support: false,
///     show_stats: false,
/// };
/// ```
///
/// Filtered search:
/// ```no_run
/// use voirs_cli::commands::voice_search::VoiceSearchCommandConfig;
///
/// let config = VoiceSearchCommandConfig {
///     query: Some("professional"),
///     language: Some("en-US"),
///     gender: Some("female"),
///     age: Some("young-adult"),
///     style: Some("formal"),
///     min_quality: Some("high"),
///     emotion_support: true,
///     show_stats: false,
/// };
/// ```
#[derive(Debug)]
pub struct VoiceSearchCommandConfig<'a> {
    /// Optional search query text (searches in name, description, tags)
    pub query: Option<&'a str>,
    /// Filter by language code (e.g., "en-US", "ja-JP")
    pub language: Option<&'a str>,
    /// Filter by gender ("male", "female", "neutral")
    pub gender: Option<&'a str>,
    /// Filter by age range ("child", "young-adult", "adult", "senior")
    pub age: Option<&'a str>,
    /// Filter by voice style (e.g., "casual", "formal", "energetic")
    pub style: Option<&'a str>,
    /// Minimum quality level ("low", "medium", "high", "ultra")
    pub min_quality: Option<&'a str>,
    /// Filter to only voices with emotion support
    pub emotion_support: bool,
    /// Show voice statistics instead of search results
    pub show_stats: bool,
}

/// Run voice search command
pub async fn run_voice_search(
    search_config: VoiceSearchCommandConfig<'_>,
    config: &AppConfig,
) -> Result<()> {
    let search = VoiceSearch::new(config).await?;

    if search_config.show_stats {
        print_voice_statistics(&search.get_statistics());
        return Ok(());
    }

    let results = if let Some(query) = search_config.query {
        search.search(query)
    } else {
        let criteria = VoiceSearchCriteria {
            language: search_config.language.map(|s| s.to_string()),
            gender: search_config.gender.map(|s| s.to_string()),
            age: search_config.age.map(|s| s.to_string()),
            style: search_config.style.map(|s| s.to_string()),
            min_quality: search_config.min_quality.map(|s| s.to_string()),
            emotion_support: search_config.emotion_support,
            require_gender: search_config.gender.is_some(),
            require_age: search_config.age.is_some(),
            require_emotion_support: search_config.emotion_support,
        };
        search.search_by_criteria(&criteria)
    };

    if results.is_empty() {
        println!("No voices found matching your criteria.");
        if let Some(query) = search_config.query {
            println!("Try using broader search terms or check the available voices with 'voirs voices list'.");
        }
        return Ok(());
    }

    println!("Found {} voice(s):", results.len());
    println!();

    for (i, result) in results.iter().enumerate().take(10) {
        // Limit to top 10 results
        print_voice_search_result(i + 1, result);
        if i < results.len() - 1 {
            println!("---");
        }
    }

    if results.len() > 10 {
        println!();
        println!(
            "... and {} more results. Use more specific search criteria to narrow down.",
            results.len() - 10
        );
    }

    Ok(())
}

/// Print voice search result
fn print_voice_search_result(index: usize, result: &VoiceSearchResult) {
    println!("{}. {} ({})", index, result.voice.name, result.voice.id);
    println!("   Language: {}", result.voice.language.as_str());

    if let Some(gender) = &result.voice.characteristics.gender {
        println!("   Gender: {:?}", gender);
    }

    if let Some(age) = &result.voice.characteristics.age {
        println!("   Age: {:?}", age);
    }

    println!("   Style: {:?}", result.voice.characteristics.style);
    println!("   Quality: {:?}", result.voice.characteristics.quality);

    if result.voice.characteristics.emotion_support {
        println!("   ✓ Emotion support");
    }

    println!("   Relevance: {:.1}", result.relevance_score);
    println!("   Matches: {}", result.match_reasons.join(", "));

    if let Some(description) = result.voice.metadata.get("description") {
        if description.len() <= 100 {
            println!("   Description: {}", description);
        } else {
            println!("   Description: {}...", &description[..97]);
        }
    }
}

/// Print voice statistics
fn print_voice_statistics(stats: &VoiceStatistics) {
    println!("Voice Database Statistics");
    println!("========================");
    println!("Total voices: {}", stats.total_voices);
    println!();

    println!("By Language:");
    let mut lang_vec: Vec<_> = stats.languages.iter().collect();
    lang_vec.sort_by_key(|(_, count)| **count);
    lang_vec.reverse();
    for (lang, count) in lang_vec {
        println!("  {}: {}", lang, count);
    }
    println!();

    println!("By Gender:");
    let mut gender_vec: Vec<_> = stats.genders.iter().collect();
    gender_vec.sort_by_key(|(_, count)| **count);
    gender_vec.reverse();
    for (gender, count) in gender_vec {
        println!("  {}: {}", gender, count);
    }
    println!();

    println!("By Quality:");
    let mut quality_vec: Vec<_> = stats.qualities.iter().collect();
    quality_vec.sort_by_key(|(_, count)| **count);
    quality_vec.reverse();
    for (quality, count) in quality_vec {
        println!("  {}: {}", quality, count);
    }
    println!();

    println!(
        "Emotion Support: {} voices ({:.1}%)",
        stats.emotion_support_count,
        (stats.emotion_support_count as f32 / stats.total_voices as f32) * 100.0
    );
}