trustformers-tokenizers 0.1.1

Tokenizers for TrustformeRS
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
use async_trait::async_trait;
use futures::future::{BoxFuture, FutureExt};
use futures::stream::Stream;
use std::sync::Arc;
use tokio::sync::{mpsc, Semaphore};
use tokio::task;
use trustformers_core::errors::Result;
use trustformers_core::traits::{TokenizedInput, Tokenizer};

/// Async version of the Tokenizer trait
#[async_trait]
pub trait AsyncTokenizer: Send + Sync {
    /// Asynchronously encode a single text
    async fn encode_async(&self, text: &str) -> Result<TokenizedInput>;

    /// Asynchronously encode text pairs
    async fn encode_pair_async(&self, text: &str, text2: &str) -> Result<TokenizedInput>;

    /// Asynchronously decode token IDs to text
    async fn decode_async(&self, ids: &[u32]) -> Result<String>;

    /// Asynchronously encode multiple texts in parallel
    async fn encode_batch_async(&self, texts: &[&str]) -> Result<Vec<TokenizedInput>>;

    /// Asynchronously encode text pairs in parallel
    async fn encode_pair_batch_async(
        &self,
        text_pairs: &[(&str, &str)],
    ) -> Result<Vec<TokenizedInput>>;

    /// Stream-based encoding for large datasets
    fn encode_stream<'a>(
        &'a self,
        texts: Vec<String>,
    ) -> BoxFuture<'a, Result<Box<dyn Stream<Item = Result<TokenizedInput>> + Send + Unpin>>>;
}

/// Wrapper that adds async capabilities to any synchronous tokenizer
pub struct AsyncTokenizerWrapper<T> {
    tokenizer: Arc<T>,
    max_concurrent_tasks: usize,
    task_semaphore: Arc<Semaphore>,
}

impl<T> AsyncTokenizerWrapper<T>
where
    T: Tokenizer + Send + Sync + 'static,
{
    /// Create a new async wrapper around a synchronous tokenizer
    pub fn new(tokenizer: T, max_concurrent_tasks: Option<usize>) -> Self {
        let max_tasks = max_concurrent_tasks.unwrap_or(num_cpus::get() * 2);
        Self {
            tokenizer: Arc::new(tokenizer),
            max_concurrent_tasks: max_tasks,
            task_semaphore: Arc::new(Semaphore::new(max_tasks)),
        }
    }

    /// Set the maximum number of concurrent tasks
    pub fn with_max_concurrent_tasks(mut self, max_tasks: usize) -> Self {
        self.max_concurrent_tasks = max_tasks;
        self.task_semaphore = Arc::new(Semaphore::new(max_tasks));
        self
    }

    /// Get the underlying synchronous tokenizer
    pub fn inner(&self) -> &Arc<T> {
        &self.tokenizer
    }
}

#[async_trait]
impl<T> AsyncTokenizer for AsyncTokenizerWrapper<T>
where
    T: Tokenizer + Send + Sync + 'static,
{
    async fn encode_async(&self, text: &str) -> Result<TokenizedInput> {
        let tokenizer = Arc::clone(&self.tokenizer);
        let text = text.to_string();
        let _permit = self.task_semaphore.acquire().await.map_err(|_| {
            trustformers_core::errors::TrustformersError::other(
                anyhow::anyhow!("Failed to acquire semaphore permit").to_string(),
            )
        })?;

        task::spawn_blocking(move || tokenizer.encode(&text)).await.map_err(|e| {
            trustformers_core::errors::TrustformersError::other(
                anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
            )
        })?
    }

    async fn encode_pair_async(&self, text: &str, text2: &str) -> Result<TokenizedInput> {
        let tokenizer = Arc::clone(&self.tokenizer);
        let text = text.to_string();
        let text2 = text2.to_string();
        let _permit = self.task_semaphore.acquire().await.map_err(|_| {
            trustformers_core::errors::TrustformersError::other(
                anyhow::anyhow!("Failed to acquire semaphore permit").to_string(),
            )
        })?;

        task::spawn_blocking(move || tokenizer.encode_pair(&text, &text2))
            .await
            .map_err(|e| {
                trustformers_core::errors::TrustformersError::other(
                    anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                )
            })?
    }

    async fn decode_async(&self, ids: &[u32]) -> Result<String> {
        let tokenizer = Arc::clone(&self.tokenizer);
        let ids = ids.to_vec();
        let _permit = self.task_semaphore.acquire().await.map_err(|_| {
            trustformers_core::errors::TrustformersError::other(
                anyhow::anyhow!("Failed to acquire semaphore permit").to_string(),
            )
        })?;

        task::spawn_blocking(move || tokenizer.decode(&ids)).await.map_err(|e| {
            trustformers_core::errors::TrustformersError::other(
                anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
            )
        })?
    }

    async fn encode_batch_async(&self, texts: &[&str]) -> Result<Vec<TokenizedInput>> {
        let mut tasks = Vec::new();

        for text in texts {
            let tokenizer = Arc::clone(&self.tokenizer);
            let text = text.to_string();
            let semaphore = Arc::clone(&self.task_semaphore);

            let task = task::spawn(async move {
                let _permit = semaphore.acquire().await.map_err(|_| {
                    trustformers_core::errors::TrustformersError::other(
                        anyhow::anyhow!("Failed to acquire semaphore permit").to_string(),
                    )
                })?;

                task::spawn_blocking(move || tokenizer.encode(&text)).await.map_err(|e| {
                    trustformers_core::errors::TrustformersError::other(
                        anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                    )
                })?
            });

            tasks.push(task);
        }

        let mut results = Vec::with_capacity(texts.len());
        for task in tasks {
            let result = task.await.map_err(|e| {
                trustformers_core::errors::TrustformersError::other(
                    anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                )
            })??;
            results.push(result);
        }

        Ok(results)
    }

    async fn encode_pair_batch_async(
        &self,
        text_pairs: &[(&str, &str)],
    ) -> Result<Vec<TokenizedInput>> {
        let mut tasks = Vec::new();

        for (text1, text2) in text_pairs {
            let tokenizer = Arc::clone(&self.tokenizer);
            let text1 = text1.to_string();
            let text2 = text2.to_string();
            let semaphore = Arc::clone(&self.task_semaphore);

            let task = task::spawn(async move {
                let _permit = semaphore.acquire().await.map_err(|_| {
                    trustformers_core::errors::TrustformersError::other(
                        anyhow::anyhow!("Failed to acquire semaphore permit").to_string(),
                    )
                })?;

                task::spawn_blocking(move || tokenizer.encode_pair(&text1, &text2))
                    .await
                    .map_err(|e| {
                        trustformers_core::errors::TrustformersError::other(
                            anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                        )
                    })?
            });

            tasks.push(task);
        }

        let mut results = Vec::with_capacity(text_pairs.len());
        for task in tasks {
            let result = task.await.map_err(|e| {
                trustformers_core::errors::TrustformersError::other(
                    anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                )
            })??;
            results.push(result);
        }

        Ok(results)
    }

    fn encode_stream<'a>(
        &'a self,
        texts: Vec<String>,
    ) -> BoxFuture<'a, Result<Box<dyn Stream<Item = Result<TokenizedInput>> + Send + Unpin>>> {
        async move {
            let (tx, rx) = mpsc::unbounded_channel();
            let tokenizer = Arc::clone(&self.tokenizer);
            let semaphore = Arc::clone(&self.task_semaphore);

            // Spawn a task to process all texts
            task::spawn(async move {
                for text in texts {
                    let tokenizer = Arc::clone(&tokenizer);
                    let semaphore = Arc::clone(&semaphore);
                    let tx = tx.clone();

                    task::spawn(async move {
                        let result = async {
                            let _permit = semaphore.acquire().await.map_err(|_| {
                                trustformers_core::errors::TrustformersError::other(
                                    anyhow::anyhow!("Failed to acquire semaphore permit")
                                        .to_string(),
                                )
                            })?;

                            task::spawn_blocking(move || tokenizer.encode(&text)).await.map_err(
                                |e| {
                                    trustformers_core::errors::TrustformersError::other(
                                        anyhow::anyhow!(format!("Task join error: {}", e))
                                            .to_string(),
                                    )
                                },
                            )?
                        }
                        .await;

                        let _ = tx.send(result);
                    });
                }
            });

            let stream = tokio_stream::wrappers::UnboundedReceiverStream::new(rx);
            Ok(Box::new(stream)
                as Box<
                    dyn Stream<Item = Result<TokenizedInput>> + Send + Unpin,
                >)
        }
        .boxed()
    }
}

/// Configuration for async tokenization operations
#[derive(Debug, Clone)]
pub struct AsyncTokenizerConfig {
    /// Maximum number of concurrent tokenization tasks
    pub max_concurrent_tasks: usize,

    /// Buffer size for streaming operations
    pub stream_buffer_size: usize,

    /// Timeout for individual tokenization operations (in milliseconds)
    pub task_timeout_ms: Option<u64>,

    /// Enable task cancellation on timeout
    pub enable_cancellation: bool,
}

impl Default for AsyncTokenizerConfig {
    fn default() -> Self {
        Self {
            max_concurrent_tasks: num_cpus::get() * 2,
            stream_buffer_size: 1000,
            task_timeout_ms: None,
            enable_cancellation: false,
        }
    }
}

/// Advanced async tokenizer with configurable behavior
pub struct ConfigurableAsyncTokenizer<T> {
    tokenizer: Arc<T>,
    config: AsyncTokenizerConfig,
    task_semaphore: Arc<Semaphore>,
}

impl<T> ConfigurableAsyncTokenizer<T>
where
    T: Tokenizer + Send + Sync + 'static,
{
    /// Create a new configurable async tokenizer
    pub fn new(tokenizer: T, config: AsyncTokenizerConfig) -> Self {
        let semaphore = Arc::new(Semaphore::new(config.max_concurrent_tasks));
        Self {
            tokenizer: Arc::new(tokenizer),
            config,
            task_semaphore: semaphore,
        }
    }

    /// Update configuration
    pub fn update_config(&mut self, config: AsyncTokenizerConfig) {
        self.task_semaphore = Arc::new(Semaphore::new(config.max_concurrent_tasks));
        self.config = config;
    }

    /// Get current configuration
    pub fn config(&self) -> &AsyncTokenizerConfig {
        &self.config
    }

    /// Process a large batch with progress reporting
    pub async fn encode_large_batch_with_progress<F>(
        &self,
        texts: &[&str],
        mut progress_callback: F,
    ) -> Result<Vec<TokenizedInput>>
    where
        F: FnMut(usize, usize) + Send + 'static,
    {
        let total = texts.len();
        let mut completed = 0;
        let mut results = Vec::with_capacity(total);

        // Process in chunks to avoid overwhelming the system
        let chunk_size = (self.config.max_concurrent_tasks).max(1);

        for chunk in texts.chunks(chunk_size) {
            let chunk_results = self.encode_batch_async(chunk).await?;
            results.extend(chunk_results);

            completed += chunk.len();
            progress_callback(completed, total);
        }

        Ok(results)
    }
}

#[async_trait]
impl<T> AsyncTokenizer for ConfigurableAsyncTokenizer<T>
where
    T: Tokenizer + Send + Sync + 'static,
{
    async fn encode_async(&self, text: &str) -> Result<TokenizedInput> {
        let tokenizer = Arc::clone(&self.tokenizer);
        let text = text.to_string();
        let _permit = self.task_semaphore.acquire().await.map_err(|_| {
            trustformers_core::errors::TrustformersError::other(
                anyhow::anyhow!("Failed to acquire semaphore permit").to_string(),
            )
        })?;

        let encoding_task = task::spawn_blocking(move || tokenizer.encode(&text));

        if let Some(timeout_ms) = self.config.task_timeout_ms {
            match tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), encoding_task)
                .await
            {
                Ok(result) => result.map_err(|e| {
                    trustformers_core::errors::TrustformersError::other(
                        anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                    )
                })?,
                Err(_) => Err(trustformers_core::errors::TrustformersError::other(
                    anyhow::anyhow!("Tokenization timeout".to_string()).to_string(),
                )),
            }
        } else {
            encoding_task.await.map_err(|e| {
                trustformers_core::errors::TrustformersError::other(
                    anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                )
            })?
        }
    }

    async fn encode_pair_async(&self, text: &str, text2: &str) -> Result<TokenizedInput> {
        let tokenizer = Arc::clone(&self.tokenizer);
        let text = text.to_string();
        let text2 = text2.to_string();
        let _permit = self.task_semaphore.acquire().await.map_err(|_| {
            trustformers_core::errors::TrustformersError::other(
                anyhow::anyhow!("Failed to acquire semaphore permit").to_string(),
            )
        })?;

        let encoding_task = task::spawn_blocking(move || tokenizer.encode_pair(&text, &text2));

        if let Some(timeout_ms) = self.config.task_timeout_ms {
            match tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), encoding_task)
                .await
            {
                Ok(result) => result.map_err(|e| {
                    trustformers_core::errors::TrustformersError::other(
                        anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                    )
                })?,
                Err(_) => Err(trustformers_core::errors::TrustformersError::other(
                    anyhow::anyhow!("Tokenization timeout".to_string()).to_string(),
                )),
            }
        } else {
            encoding_task.await.map_err(|e| {
                trustformers_core::errors::TrustformersError::other(
                    anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                )
            })?
        }
    }

    async fn decode_async(&self, ids: &[u32]) -> Result<String> {
        let tokenizer = Arc::clone(&self.tokenizer);
        let ids = ids.to_vec();
        let _permit = self.task_semaphore.acquire().await.map_err(|_| {
            trustformers_core::errors::TrustformersError::other(
                anyhow::anyhow!("Failed to acquire semaphore permit").to_string(),
            )
        })?;

        let decoding_task = task::spawn_blocking(move || tokenizer.decode(&ids));

        if let Some(timeout_ms) = self.config.task_timeout_ms {
            match tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), decoding_task)
                .await
            {
                Ok(result) => result.map_err(|e| {
                    trustformers_core::errors::TrustformersError::other(
                        anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                    )
                })?,
                Err(_) => Err(trustformers_core::errors::TrustformersError::other(
                    anyhow::anyhow!("Decoding timeout".to_string()).to_string(),
                )),
            }
        } else {
            decoding_task.await.map_err(|e| {
                trustformers_core::errors::TrustformersError::other(
                    anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                )
            })?
        }
    }

    async fn encode_batch_async(&self, texts: &[&str]) -> Result<Vec<TokenizedInput>> {
        let mut tasks = Vec::new();

        for text in texts {
            let tokenizer = Arc::clone(&self.tokenizer);
            let text = text.to_string();
            let semaphore = Arc::clone(&self.task_semaphore);
            let timeout_ms = self.config.task_timeout_ms;

            let task = task::spawn(async move {
                let _permit = semaphore.acquire().await.map_err(|_| {
                    trustformers_core::errors::TrustformersError::other(
                        anyhow::anyhow!("Failed to acquire semaphore permit").to_string(),
                    )
                })?;

                let encoding_task = task::spawn_blocking(move || tokenizer.encode(&text));

                if let Some(timeout_ms) = timeout_ms {
                    match tokio::time::timeout(
                        std::time::Duration::from_millis(timeout_ms),
                        encoding_task,
                    )
                    .await
                    {
                        Ok(result) => result.map_err(|e| {
                            trustformers_core::errors::TrustformersError::other(
                                anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                            )
                        })?,
                        Err(_) => Err(trustformers_core::errors::TrustformersError::other(
                            anyhow::anyhow!("Tokenization timeout").to_string(),
                        )),
                    }
                } else {
                    encoding_task.await.map_err(|e| {
                        trustformers_core::errors::TrustformersError::other(
                            anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                        )
                    })?
                }
            });

            tasks.push(task);
        }

        let mut results = Vec::with_capacity(texts.len());
        for task in tasks {
            let result = task.await.map_err(|e| {
                trustformers_core::errors::TrustformersError::other(
                    anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                )
            })??;
            results.push(result);
        }

        Ok(results)
    }

    async fn encode_pair_batch_async(
        &self,
        text_pairs: &[(&str, &str)],
    ) -> Result<Vec<TokenizedInput>> {
        let mut tasks = Vec::new();

        for (text1, text2) in text_pairs {
            let tokenizer = Arc::clone(&self.tokenizer);
            let text1 = text1.to_string();
            let text2 = text2.to_string();
            let semaphore = Arc::clone(&self.task_semaphore);
            let timeout_ms = self.config.task_timeout_ms;

            let task = task::spawn(async move {
                let _permit = semaphore.acquire().await.map_err(|_| {
                    trustformers_core::errors::TrustformersError::other(
                        anyhow::anyhow!("Failed to acquire semaphore permit").to_string(),
                    )
                })?;

                let encoding_task =
                    task::spawn_blocking(move || tokenizer.encode_pair(&text1, &text2));

                if let Some(timeout_ms) = timeout_ms {
                    match tokio::time::timeout(
                        std::time::Duration::from_millis(timeout_ms),
                        encoding_task,
                    )
                    .await
                    {
                        Ok(result) => result.map_err(|e| {
                            trustformers_core::errors::TrustformersError::other(
                                anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                            )
                        })?,
                        Err(_) => Err(trustformers_core::errors::TrustformersError::other(
                            anyhow::anyhow!("Tokenization timeout").to_string(),
                        )),
                    }
                } else {
                    encoding_task.await.map_err(|e| {
                        trustformers_core::errors::TrustformersError::other(
                            anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                        )
                    })?
                }
            });

            tasks.push(task);
        }

        let mut results = Vec::with_capacity(text_pairs.len());
        for task in tasks {
            let result = task.await.map_err(|e| {
                trustformers_core::errors::TrustformersError::other(
                    anyhow::anyhow!(format!("Task join error: {}", e)).to_string(),
                )
            })??;
            results.push(result);
        }

        Ok(results)
    }

    fn encode_stream<'a>(
        &'a self,
        texts: Vec<String>,
    ) -> BoxFuture<'a, Result<Box<dyn Stream<Item = Result<TokenizedInput>> + Send + Unpin>>> {
        async move {
            let (tx, rx) = mpsc::channel(self.config.stream_buffer_size);
            let tokenizer = Arc::clone(&self.tokenizer);
            let semaphore = Arc::clone(&self.task_semaphore);
            let timeout_ms = self.config.task_timeout_ms;

            // Spawn a task to process all texts
            task::spawn(async move {
                for text in texts {
                    let tokenizer = Arc::clone(&tokenizer);
                    let semaphore = Arc::clone(&semaphore);
                    let tx = tx.clone();

                    task::spawn(async move {
                        let result = async {
                            let _permit = semaphore.acquire().await.map_err(|_| {
                                trustformers_core::errors::TrustformersError::other(
                                    anyhow::anyhow!("Failed to acquire semaphore permit")
                                        .to_string(),
                                )
                            })?;

                            let encoding_task =
                                task::spawn_blocking(move || tokenizer.encode(&text));

                            if let Some(timeout_ms) = timeout_ms {
                                match tokio::time::timeout(
                                    std::time::Duration::from_millis(timeout_ms),
                                    encoding_task,
                                )
                                .await
                                {
                                    Ok(result) => result.map_err(|e| {
                                        trustformers_core::errors::TrustformersError::other(
                                            anyhow::anyhow!(format!("Task join error: {}", e))
                                                .to_string(),
                                        )
                                    })?,
                                    Err(_) => {
                                        Err(trustformers_core::errors::TrustformersError::other(
                                            anyhow::anyhow!("Tokenization timeout").to_string(),
                                        ))
                                    },
                                }
                            } else {
                                encoding_task.await.map_err(|e| {
                                    trustformers_core::errors::TrustformersError::other(
                                        anyhow::anyhow!(format!("Task join error: {}", e))
                                            .to_string(),
                                    )
                                })?
                            }
                        }
                        .await;

                        let _ = tx.send(result).await;
                    });
                }
            });

            let stream = tokio_stream::wrappers::ReceiverStream::new(rx);
            Ok(Box::new(stream)
                as Box<
                    dyn Stream<Item = Result<TokenizedInput>> + Send + Unpin,
                >)
        }
        .boxed()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::wordpiece::WordPieceTokenizer;
    use futures::StreamExt;
    use std::time::Instant;

    #[tokio::test]
    async fn test_async_tokenizer_wrapper() {
        let mut vocab = std::collections::HashMap::new();
        vocab.insert("[UNK]".to_string(), 0);
        vocab.insert("[CLS]".to_string(), 1);
        vocab.insert("[SEP]".to_string(), 2);
        vocab.insert("[PAD]".to_string(), 3);
        vocab.insert("[MASK]".to_string(), 4);
        vocab.insert("hello".to_string(), 5);
        vocab.insert("world".to_string(), 6);

        let tokenizer = WordPieceTokenizer::new(vocab, true);
        let async_tokenizer = AsyncTokenizerWrapper::new(tokenizer, Some(4));

        let result = async_tokenizer
            .encode_async("Hello world")
            .await
            .expect("Operation failed in test");
        assert!(!result.input_ids.is_empty());
    }

    #[tokio::test]
    async fn test_batch_async_encoding() {
        let tokenizer = WordPieceTokenizer::from_pretrained("bert-base-uncased")
            .expect("Operation failed in test");
        let async_tokenizer = AsyncTokenizerWrapper::new(tokenizer, Some(4));

        let texts = vec!["Hello world", "This is a test", "Async tokenization"];
        let results = async_tokenizer
            .encode_batch_async(&texts)
            .await
            .expect("Operation failed in test");

        assert_eq!(results.len(), texts.len());
        for result in &results {
            assert!(!result.input_ids.is_empty());
        }
    }

    #[tokio::test]
    async fn test_configurable_async_tokenizer() {
        let tokenizer = WordPieceTokenizer::from_pretrained("bert-base-uncased")
            .expect("Operation failed in test");
        let config = AsyncTokenizerConfig {
            max_concurrent_tasks: 2,
            stream_buffer_size: 100,
            task_timeout_ms: Some(5000),
            enable_cancellation: true,
        };
        let async_tokenizer = ConfigurableAsyncTokenizer::new(tokenizer, config);

        let result = async_tokenizer
            .encode_async("Hello world")
            .await
            .expect("Operation failed in test");
        assert!(!result.input_ids.is_empty());
    }

    #[tokio::test]
    async fn test_async_decode() {
        let mut vocab = std::collections::HashMap::new();
        vocab.insert("[UNK]".to_string(), 0);
        vocab.insert("[CLS]".to_string(), 1);
        vocab.insert("[SEP]".to_string(), 2);
        vocab.insert("[PAD]".to_string(), 3);
        vocab.insert("[MASK]".to_string(), 4);
        vocab.insert("hello".to_string(), 5);
        vocab.insert("world".to_string(), 6);

        let tokenizer = WordPieceTokenizer::new(vocab, true);
        let async_tokenizer = AsyncTokenizerWrapper::new(tokenizer, Some(4));

        let encoded = async_tokenizer
            .encode_async("Hello world")
            .await
            .expect("Operation failed in test");
        let decoded = async_tokenizer
            .decode_async(&encoded.input_ids)
            .await
            .expect("Operation failed in test");

        assert!(!decoded.is_empty());
        assert!(
            decoded.to_lowercase().contains("hello") || decoded.to_lowercase().contains("world")
        );
    }

    #[tokio::test]
    async fn test_stream_encoding() {
        let mut vocab = std::collections::HashMap::new();
        vocab.insert("[UNK]".to_string(), 0);
        vocab.insert("[CLS]".to_string(), 1);
        vocab.insert("[SEP]".to_string(), 2);
        vocab.insert("[PAD]".to_string(), 3);
        vocab.insert("[MASK]".to_string(), 4);
        vocab.insert("hello".to_string(), 5);
        vocab.insert("world".to_string(), 6);
        vocab.insert("this".to_string(), 7);
        vocab.insert("is".to_string(), 8);
        vocab.insert("a".to_string(), 9);
        vocab.insert("test".to_string(), 10);
        vocab.insert("async".to_string(), 11);
        vocab.insert("tokenization".to_string(), 12);

        let tokenizer = WordPieceTokenizer::new(vocab, true);
        let async_tokenizer = AsyncTokenizerWrapper::new(tokenizer, Some(4));

        let texts = vec![
            "Hello world".to_string(),
            "This is a test".to_string(),
            "Async tokenization".to_string(),
        ];

        let mut stream = async_tokenizer
            .encode_stream(texts.clone())
            .await
            .expect("Operation failed in test");
        let mut results = Vec::new();

        while let Some(result) = stream.next().await {
            results.push(result.expect("Operation failed in test"));
        }

        assert_eq!(results.len(), texts.len());
    }

    #[tokio::test]
    async fn test_large_batch_with_progress() {
        let tokenizer = WordPieceTokenizer::from_pretrained("bert-base-uncased")
            .expect("Operation failed in test");
        let config = AsyncTokenizerConfig::default();
        let async_tokenizer = ConfigurableAsyncTokenizer::new(tokenizer, config);

        let texts: Vec<&str> = (0..100)
            .map(
                |i| {
                    if i % 2 == 0 {
                        "Hello world"
                    } else {
                        "This is a test"
                    }
                },
            )
            .collect();

        let progress_updates = Arc::new(std::sync::Mutex::new(Vec::new()));
        let progress_updates_clone = Arc::clone(&progress_updates);

        let results = async_tokenizer
            .encode_large_batch_with_progress(&texts, move |completed, total| {
                progress_updates_clone
                    .lock()
                    .expect("lock should not be poisoned")
                    .push((completed, total));
            })
            .await
            .expect("Operation failed in test");

        assert_eq!(results.len(), texts.len());

        let updates = progress_updates.lock().expect("lock should not be poisoned");
        assert!(!updates.is_empty());
        assert_eq!(
            updates.last().expect("Operation failed in test").0,
            texts.len()
        );
        assert_eq!(
            updates.last().expect("Operation failed in test").1,
            texts.len()
        );
    }

    #[tokio::test]
    async fn test_concurrent_performance() {
        let tokenizer = WordPieceTokenizer::from_pretrained("bert-base-uncased")
            .expect("Operation failed in test");
        let async_tokenizer = AsyncTokenizerWrapper::new(tokenizer, Some(8));

        let texts: Vec<&str> = (0..50)
            .map(|i| {
                if i % 2 == 0 {
                    "Hello world from async tokenization"
                } else {
                    "This is a performance test"
                }
            })
            .collect();

        let start = Instant::now();
        let results = async_tokenizer
            .encode_batch_async(&texts)
            .await
            .expect("Operation failed in test");
        let duration = start.elapsed();

        assert_eq!(results.len(), texts.len());
        println!("Encoded {} texts in {:?}", texts.len(), duration);

        // Verify all results are valid
        for result in &results {
            assert!(!result.input_ids.is_empty());
            assert_eq!(result.input_ids.len(), result.attention_mask.len());
        }
    }
}