1+ <?php
2+
3+ declare (strict_types=1 );
4+
5+ namespace Codewithkyrian \Transformers \PostProcessors ;
6+
7+ /**
8+ * A post-processor that applies multiple post-processors in sequence.
9+ */
10+ class PostProcessorSequence extends PostProcessor
11+ {
12+
13+ /**
14+ * List of post-processors to apply.
15+ */
16+ protected array $ processors ;
17+
18+ /**
19+ * Creates a new instance of PostProcessorSequence.
20+ *
21+ * @param array $config The configuration array.
22+ * - 'processors' (array): The list of post-processors to apply.
23+ */
24+ public function __construct (array $ config )
25+ {
26+ parent ::__construct ($ config );
27+
28+ $ this ->processors = array_map (
29+ fn ($ processorConfig ) => PostProcessor::fromConfig ($ processorConfig ),
30+ $ config ['processors ' ]
31+ );
32+ }
33+
34+ /**
35+ * Post-process the given tokens.
36+ *
37+ * @param array $tokens The list of tokens for the first sequence.
38+ * @param string[]|null $tokenPair The input tokens for the second sequence in a pair.
39+ * * @param bool $addSpecialTokens Whether to add the special tokens associated with the corresponding model.
40+ *
41+ * @return PostProcessedOutput An array containing the post-processed tokens and token_type_ids.
42+ */
43+ public function postProcess (array $ tokens , ?array $ tokenPair = null , bool $ addSpecialTokens = true ): PostProcessedOutput
44+ {
45+ $ tokenTypeIds = null ;
46+
47+ foreach ($ this ->processors as $ processor ) {
48+ if ($ processor instanceof ByteLevelPostProcessor) {
49+ // Special case where we need to pass the tokens_pair to the post-processor
50+ $ output = $ processor ->postProcess ($ tokens );
51+ $ tokens = $ output ->tokens ;
52+
53+ if ($ tokenPair !== null ) {
54+ $ pairOutput = $ processor ->postProcess ($ tokenPair );
55+ $ tokenPair = $ pairOutput ->tokens ;
56+ }
57+ } else {
58+ $ output = $ processor ->postProcess ($ tokens , $ tokenPair , $ addSpecialTokens );
59+ $ tokens = $ output ->tokens ;
60+ $ tokenTypeIds = $ output ->tokenTypeIds ;
61+ }
62+ }
63+
64+ return new PostProcessedOutput ($ tokens , $ tokenTypeIds );
65+ }
66+ }
67+
68+ ?>
0 commit comments