18817535bSAndreas Gohr<?php 28817535bSAndreas Gohr 38817535bSAndreas Gohrnamespace dokuwiki\plugin\aichat; 48817535bSAndreas Gohr 5ab1f8ddeSAndreas Gohruse dokuwiki\Extension\Event; 6661701eeSAndreas Gohruse dokuwiki\File\PageResolver; 7294a9eafSAndreas Gohruse dokuwiki\plugin\aichat\Model\ChatInterface; 8294a9eafSAndreas Gohruse dokuwiki\plugin\aichat\Model\EmbeddingInterface; 9f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Storage\AbstractStorage; 108817535bSAndreas Gohruse dokuwiki\Search\Indexer; 112ecc089aSAndreas Gohruse splitbrain\phpcli\CLI; 128817535bSAndreas Gohruse TikToken\Encoder; 138817535bSAndreas Gohruse Vanderlee\Sentence\Sentence; 148817535bSAndreas Gohr 159da5f0dfSAndreas Gohr/** 169da5f0dfSAndreas Gohr * Manage the embeddings index 179da5f0dfSAndreas Gohr * 189da5f0dfSAndreas Gohr * Pages are split into chunks of 1000 tokens each. For each chunk the embedding vector is fetched from 197ee8b02dSAndreas Gohr * OpenAI and stored in the Storage backend. 209da5f0dfSAndreas Gohr */ 218817535bSAndreas Gohrclass Embeddings 228817535bSAndreas Gohr{ 2368908844SAndreas Gohr /** @var int maximum overlap between chunks in tokens */ 2430b9cbc7Ssplitbrain final public const MAX_OVERLAP_LEN = 200; 258817535bSAndreas Gohr 26294a9eafSAndreas Gohr /** @var ChatInterface */ 276a18e0f4SAndreas Gohr protected $chatModel; 286a18e0f4SAndreas Gohr 29294a9eafSAndreas Gohr /** @var EmbeddingInterface */ 306a18e0f4SAndreas Gohr protected $embedModel; 316a18e0f4SAndreas Gohr 322ecc089aSAndreas Gohr /** @var CLI|null */ 332ecc089aSAndreas Gohr protected $logger; 3468908844SAndreas Gohr /** @var Encoder */ 3568908844SAndreas Gohr protected $tokenEncoder; 368817535bSAndreas Gohr 377ee8b02dSAndreas Gohr /** @var AbstractStorage */ 387ee8b02dSAndreas Gohr protected $storage; 397ee8b02dSAndreas Gohr 4068908844SAndreas Gohr /** @var array remember sentences when chunking */ 4168908844SAndreas Gohr private $sentenceQueue = []; 4268908844SAndreas Gohr 43c2b7a1f7SAndreas Gohr /** @var int the time spent for the last similar chunk retrieval */ 44c2b7a1f7SAndreas Gohr public $timeSpent = 0; 45c2b7a1f7SAndreas Gohr 4634a1c478SAndreas Gohr protected $configChunkSize; 4734a1c478SAndreas Gohr protected $configContextChunks; 48720bb43fSAndreas Gohr protected $similarityThreshold; 4934a1c478SAndreas Gohr 5034a1c478SAndreas Gohr /** 5134a1c478SAndreas Gohr * Embeddings constructor. 5234a1c478SAndreas Gohr * 5334a1c478SAndreas Gohr * @param ChatInterface $chatModel 5434a1c478SAndreas Gohr * @param EmbeddingInterface $embedModel 5534a1c478SAndreas Gohr * @param AbstractStorage $storage 5634a1c478SAndreas Gohr * @param array $config The plugin configuration 5734a1c478SAndreas Gohr */ 586a18e0f4SAndreas Gohr public function __construct( 59294a9eafSAndreas Gohr ChatInterface $chatModel, 60294a9eafSAndreas Gohr EmbeddingInterface $embedModel, 6134a1c478SAndreas Gohr AbstractStorage $storage, 6234a1c478SAndreas Gohr $config 63*aa6bbe75SAndreas Gohr ) 64*aa6bbe75SAndreas Gohr { 656a18e0f4SAndreas Gohr $this->chatModel = $chatModel; 666a18e0f4SAndreas Gohr $this->embedModel = $embedModel; 67f6ef2e50SAndreas Gohr $this->storage = $storage; 6834a1c478SAndreas Gohr $this->configChunkSize = $config['chunkSize']; 6934a1c478SAndreas Gohr $this->configContextChunks = $config['contextChunks']; 70720bb43fSAndreas Gohr $this->similarityThreshold = $config['similarityThreshold'] / 100; 717ee8b02dSAndreas Gohr } 727ee8b02dSAndreas Gohr 737ee8b02dSAndreas Gohr /** 747ee8b02dSAndreas Gohr * Access storage 757ee8b02dSAndreas Gohr * 767ee8b02dSAndreas Gohr * @return AbstractStorage 777ee8b02dSAndreas Gohr */ 787ee8b02dSAndreas Gohr public function getStorage() 797ee8b02dSAndreas Gohr { 807ee8b02dSAndreas Gohr return $this->storage; 812ecc089aSAndreas Gohr } 822ecc089aSAndreas Gohr 832ecc089aSAndreas Gohr /** 84*aa6bbe75SAndreas Gohr * Override the number of used context chunks 85*aa6bbe75SAndreas Gohr * 86*aa6bbe75SAndreas Gohr * @param int $max 87*aa6bbe75SAndreas Gohr * @return void 88*aa6bbe75SAndreas Gohr */ 89*aa6bbe75SAndreas Gohr public function setConfigContextChunks(int $max) 90*aa6bbe75SAndreas Gohr { 91*aa6bbe75SAndreas Gohr if ($max <= 0) throw new \InvalidArgumentException('max context chunks must be greater than 0'); 92*aa6bbe75SAndreas Gohr $this->configContextChunks = $max; 93*aa6bbe75SAndreas Gohr } 94*aa6bbe75SAndreas Gohr 95*aa6bbe75SAndreas Gohr /** 96*aa6bbe75SAndreas Gohr * Override the similiarity threshold 97*aa6bbe75SAndreas Gohr * 98*aa6bbe75SAndreas Gohr * @param float $threshold 99*aa6bbe75SAndreas Gohr * @return void 100*aa6bbe75SAndreas Gohr */ 101*aa6bbe75SAndreas Gohr public function setSimilarityThreshold(float $threshold) 102*aa6bbe75SAndreas Gohr { 103*aa6bbe75SAndreas Gohr if ($threshold < 0 || $threshold > 1) throw new \InvalidArgumentException('threshold must be between 0 and 1'); 104*aa6bbe75SAndreas Gohr $this->similarityThreshold = $threshold; 105*aa6bbe75SAndreas Gohr } 106*aa6bbe75SAndreas Gohr 107*aa6bbe75SAndreas Gohr /** 1082ecc089aSAndreas Gohr * Add a logger instance 1092ecc089aSAndreas Gohr * 1102ecc089aSAndreas Gohr * @return void 1112ecc089aSAndreas Gohr */ 1122ecc089aSAndreas Gohr public function setLogger(CLI $logger) 1132ecc089aSAndreas Gohr { 1148817535bSAndreas Gohr $this->logger = $logger; 1158817535bSAndreas Gohr } 1168817535bSAndreas Gohr 1172ecc089aSAndreas Gohr /** 11868908844SAndreas Gohr * Get the token encoder instance 11968908844SAndreas Gohr * 12068908844SAndreas Gohr * @return Encoder 12168908844SAndreas Gohr */ 12268908844SAndreas Gohr public function getTokenEncoder() 12368908844SAndreas Gohr { 1247ebc7895Ssplitbrain if (!$this->tokenEncoder instanceof Encoder) { 12568908844SAndreas Gohr $this->tokenEncoder = new Encoder(); 12668908844SAndreas Gohr } 12768908844SAndreas Gohr return $this->tokenEncoder; 12868908844SAndreas Gohr } 12968908844SAndreas Gohr 13068908844SAndreas Gohr /** 1316a18e0f4SAndreas Gohr * Return the chunk size to use 1326a18e0f4SAndreas Gohr * 1336a18e0f4SAndreas Gohr * @return int 1346a18e0f4SAndreas Gohr */ 1356a18e0f4SAndreas Gohr public function getChunkSize() 1366a18e0f4SAndreas Gohr { 1376a18e0f4SAndreas Gohr return min( 13834a1c478SAndreas Gohr floor($this->chatModel->getMaxInputTokenLength() / 4), // be able to fit 4 chunks into the max input 13934a1c478SAndreas Gohr floor($this->embedModel->getMaxInputTokenLength() * 0.9), // only use 90% of the embedding model to be safe 14034a1c478SAndreas Gohr $this->configChunkSize, // this is usually the smallest 1416a18e0f4SAndreas Gohr ); 1426a18e0f4SAndreas Gohr } 1436a18e0f4SAndreas Gohr 1446a18e0f4SAndreas Gohr /** 1455284515dSAndreas Gohr * Update the embeddings storage 1462ecc089aSAndreas Gohr * 147ad38c5fdSAndreas Gohr * @param string $skipRE Regular expression to filter out pages (full RE with delimiters) 148d5c102b3SAndreas Gohr * @param string $matchRE Regular expression pages have to match to be included (full RE with delimiters) 1495284515dSAndreas Gohr * @param bool $clear Should any existing storage be cleared before updating? 1502ecc089aSAndreas Gohr * @return void 1515284515dSAndreas Gohr * @throws \Exception 1522ecc089aSAndreas Gohr */ 153d5c102b3SAndreas Gohr public function createNewIndex($skipRE = '', $matchRE = '', $clear = false) 1548817535bSAndreas Gohr { 1558817535bSAndreas Gohr $indexer = new Indexer(); 1568817535bSAndreas Gohr $pages = $indexer->getPages(); 1578817535bSAndreas Gohr 158f6ef2e50SAndreas Gohr $this->storage->startCreation($clear); 1595aa45b4dSAndreas Gohr foreach ($pages as $pid => $page) { 1605aa45b4dSAndreas Gohr $chunkID = $pid * 100; // chunk IDs start at page ID * 100 1615aa45b4dSAndreas Gohr 1625284515dSAndreas Gohr if ( 1635284515dSAndreas Gohr !page_exists($page) || 1645284515dSAndreas Gohr isHiddenPage($page) || 1654e206c13SAndreas Gohr filesize(wikiFN($page)) < 150 || // skip very small pages 166d5c102b3SAndreas Gohr ($skipRE && preg_match($skipRE, (string)$page)) || 167d5c102b3SAndreas Gohr ($matchRE && !preg_match($matchRE, ":$page")) 1685284515dSAndreas Gohr ) { 1695284515dSAndreas Gohr // this page should not be in the index (anymore) 1705284515dSAndreas Gohr $this->storage->deletePageChunks($page, $chunkID); 1715284515dSAndreas Gohr continue; 1725284515dSAndreas Gohr } 1735284515dSAndreas Gohr 1747ee8b02dSAndreas Gohr $firstChunk = $this->storage->getChunk($chunkID); 1757ee8b02dSAndreas Gohr if ($firstChunk && @filemtime(wikiFN($page)) < $firstChunk->getCreated()) { 1765aa45b4dSAndreas Gohr // page is older than the chunks we have, reuse the existing chunks 1777ee8b02dSAndreas Gohr $this->storage->reusePageChunks($page, $chunkID); 1787ebc7895Ssplitbrain if ($this->logger instanceof CLI) $this->logger->info("Reusing chunks for $page"); 1795aa45b4dSAndreas Gohr } else { 1805aa45b4dSAndreas Gohr // page is newer than the chunks we have, create new chunks 1817ee8b02dSAndreas Gohr $this->storage->deletePageChunks($page, $chunkID); 182ecb0a423SAndreas Gohr $chunks = $this->createPageChunks($page, $chunkID); 183ecb0a423SAndreas Gohr if ($chunks) $this->storage->addPageChunks($chunks); 1845aa45b4dSAndreas Gohr } 1855aa45b4dSAndreas Gohr } 1867ee8b02dSAndreas Gohr $this->storage->finalizeCreation(); 1875aa45b4dSAndreas Gohr } 1885aa45b4dSAndreas Gohr 1895aa45b4dSAndreas Gohr /** 1907ee8b02dSAndreas Gohr * Split the given page, fetch embedding vectors and return Chunks 1915aa45b4dSAndreas Gohr * 19288305719SAndreas Gohr * Will use the text renderer plugin if available to get the rendered text. 19388305719SAndreas Gohr * Otherwise the raw wiki text is used. 19488305719SAndreas Gohr * 1955aa45b4dSAndreas Gohr * @param string $page Name of the page to split 1967ee8b02dSAndreas Gohr * @param int $firstChunkID The ID of the first chunk of this page 1977ee8b02dSAndreas Gohr * @return Chunk[] A list of chunks created for this page 198ab1f8ddeSAndreas Gohr * @emits INDEXER_PAGE_ADD support plugins that add additional data to the page 1995aa45b4dSAndreas Gohr * @throws \Exception 2005aa45b4dSAndreas Gohr */ 201ab1f8ddeSAndreas Gohr public function createPageChunks($page, $firstChunkID) 2025aa45b4dSAndreas Gohr { 2037ee8b02dSAndreas Gohr $chunkList = []; 20488305719SAndreas Gohr 20588305719SAndreas Gohr global $ID; 20688305719SAndreas Gohr $ID = $page; 207303d0c59SAndreas Gohr try { 208661701eeSAndreas Gohr $text = p_cached_output(wikiFN($page), 'aichat', $page); 209303d0c59SAndreas Gohr } catch (\Throwable $e) { 210303d0c59SAndreas Gohr if ($this->logger) $this->logger->error( 211661701eeSAndreas Gohr 'Failed to render page {page}. Using raw text instead. {msg}', 212303d0c59SAndreas Gohr ['page' => $page, 'msg' => $e->getMessage()] 213303d0c59SAndreas Gohr ); 214303d0c59SAndreas Gohr $text = rawWiki($page); 215303d0c59SAndreas Gohr } 216661701eeSAndreas Gohr 217661701eeSAndreas Gohr $crumbs = $this->breadcrumbTrail($page); 21888305719SAndreas Gohr 219ab1f8ddeSAndreas Gohr // allow plugins to modify the text before splitting 220ab1f8ddeSAndreas Gohr $eventData = [ 221ab1f8ddeSAndreas Gohr 'page' => $page, 222ab1f8ddeSAndreas Gohr 'body' => '', 223ab1f8ddeSAndreas Gohr 'metadata' => ['title' => $page, 'relation_references' => []], 224ab1f8ddeSAndreas Gohr ]; 225ab1f8ddeSAndreas Gohr $event = new Event('INDEXER_PAGE_ADD', $eventData); 226ab1f8ddeSAndreas Gohr if ($event->advise_before()) { 227ab1f8ddeSAndreas Gohr $text = $eventData['body'] . ' ' . $text; 228ab1f8ddeSAndreas Gohr } else { 229ab1f8ddeSAndreas Gohr $text = $eventData['body']; 230ab1f8ddeSAndreas Gohr } 231ab1f8ddeSAndreas Gohr 23288305719SAndreas Gohr $parts = $this->splitIntoChunks($text); 2337ee8b02dSAndreas Gohr foreach ($parts as $part) { 23430b9cbc7Ssplitbrain if (trim((string)$part) == '') continue; // skip empty chunks 23593c1dbf4SAndreas Gohr 236661701eeSAndreas Gohr $part = $crumbs . "\n\n" . $part; // add breadcrumbs to each chunk 237661701eeSAndreas Gohr 238ad38c5fdSAndreas Gohr try { 2396a18e0f4SAndreas Gohr $embedding = $this->embedModel->getEmbedding($part); 240ad38c5fdSAndreas Gohr } catch (\Exception $e) { 2417ebc7895Ssplitbrain if ($this->logger instanceof CLI) { 242ad38c5fdSAndreas Gohr $this->logger->error( 243ad38c5fdSAndreas Gohr 'Failed to get embedding for chunk of page {page}: {msg}', 244ad38c5fdSAndreas Gohr ['page' => $page, 'msg' => $e->getMessage()] 245ad38c5fdSAndreas Gohr ); 246ad38c5fdSAndreas Gohr } 247ad38c5fdSAndreas Gohr continue; 248ad38c5fdSAndreas Gohr } 2497ee8b02dSAndreas Gohr $chunkList[] = new Chunk($page, $firstChunkID, $part, $embedding); 2507ee8b02dSAndreas Gohr $firstChunkID++; 2518817535bSAndreas Gohr } 2527ebc7895Ssplitbrain if ($this->logger instanceof CLI) { 2537ebc7895Ssplitbrain if ($chunkList !== []) { 254f8d5ae01SAndreas Gohr $this->logger->success( 255f8d5ae01SAndreas Gohr '{id} split into {count} chunks', 256f8d5ae01SAndreas Gohr ['id' => $page, 'count' => count($chunkList)] 257f8d5ae01SAndreas Gohr ); 25893c1dbf4SAndreas Gohr } else { 25993c1dbf4SAndreas Gohr $this->logger->warning('{id} could not be split into chunks', ['id' => $page]); 26093c1dbf4SAndreas Gohr } 2618817535bSAndreas Gohr } 2627ee8b02dSAndreas Gohr return $chunkList; 2638817535bSAndreas Gohr } 2648817535bSAndreas Gohr 2659e81bea7SAndreas Gohr /** 2669e81bea7SAndreas Gohr * Do a nearest neighbor search for chunks similar to the given question 2679e81bea7SAndreas Gohr * 2689e81bea7SAndreas Gohr * Returns only chunks the current user is allowed to read, may return an empty result. 26968908844SAndreas Gohr * The number of returned chunks depends on the MAX_CONTEXT_LEN setting. 2709e81bea7SAndreas Gohr * 2719e81bea7SAndreas Gohr * @param string $query The question 272e33a1d7aSAndreas Gohr * @param string $lang Limit results to this language 273*aa6bbe75SAndreas Gohr * @param bool $limits Apply chat token limits to the number of chunks returned? 2747ee8b02dSAndreas Gohr * @return Chunk[] 2759e81bea7SAndreas Gohr * @throws \Exception 2769e81bea7SAndreas Gohr */ 277*aa6bbe75SAndreas Gohr public function getSimilarChunks($query, $lang = '', $limits = true) 2788817535bSAndreas Gohr { 2799e81bea7SAndreas Gohr global $auth; 2806a18e0f4SAndreas Gohr $vector = $this->embedModel->getEmbedding($query); 2818817535bSAndreas Gohr 282*aa6bbe75SAndreas Gohr if ($limits) { 283e3640be8SAndreas Gohr $fetch = min( 28434a1c478SAndreas Gohr ($this->chatModel->getMaxInputTokenLength() / $this->getChunkSize()), 28534a1c478SAndreas Gohr $this->configContextChunks 286f6ef2e50SAndreas Gohr ); 287*aa6bbe75SAndreas Gohr } else { 288*aa6bbe75SAndreas Gohr $fetch = $this->configContextChunks; 289*aa6bbe75SAndreas Gohr } 290aee9b383SAndreas Gohr 291aee9b383SAndreas Gohr $time = microtime(true); 292e33a1d7aSAndreas Gohr $chunks = $this->storage->getSimilarChunks($vector, $lang, $fetch); 2935f71c9bbSAndreas Gohr $this->timeSpent = round(microtime(true) - $time, 2); 2947ebc7895Ssplitbrain if ($this->logger instanceof CLI) { 295aee9b383SAndreas Gohr $this->logger->info( 296c2f55081SAndreas Gohr 'Fetched {count} similar chunks from store in {time} seconds. Query: {query}', 297c2f55081SAndreas Gohr ['count' => count($chunks), 'time' => $this->timeSpent, 'query' => $query] 298aee9b383SAndreas Gohr ); 299aee9b383SAndreas Gohr } 30068908844SAndreas Gohr 30168908844SAndreas Gohr $size = 0; 3028817535bSAndreas Gohr $result = []; 3037ee8b02dSAndreas Gohr foreach ($chunks as $chunk) { 3049e81bea7SAndreas Gohr // filter out chunks the user is not allowed to read 3057ee8b02dSAndreas Gohr if ($auth && auth_quickaclcheck($chunk->getPage()) < AUTH_READ) continue; 306720bb43fSAndreas Gohr if ($chunk->getScore() < $this->similarityThreshold) continue; 30768908844SAndreas Gohr 308*aa6bbe75SAndreas Gohr if ($limits) { 30968908844SAndreas Gohr $chunkSize = count($this->getTokenEncoder()->encode($chunk->getText())); 31034a1c478SAndreas Gohr if ($size + $chunkSize > $this->chatModel->getMaxInputTokenLength()) break; // we have enough 311*aa6bbe75SAndreas Gohr } 31268908844SAndreas Gohr 3139e81bea7SAndreas Gohr $result[] = $chunk; 314*aa6bbe75SAndreas Gohr $size += $chunkSize ?? 0; 315*aa6bbe75SAndreas Gohr 316*aa6bbe75SAndreas Gohr if (count($result) >= $this->configContextChunks) break; // we have enough 3178817535bSAndreas Gohr } 3188817535bSAndreas Gohr return $result; 3198817535bSAndreas Gohr } 3208817535bSAndreas Gohr 321661701eeSAndreas Gohr /** 322661701eeSAndreas Gohr * Create a breadcrumb trail for the given page 323661701eeSAndreas Gohr * 324661701eeSAndreas Gohr * Uses the first heading of each namespace and the page itself. This is added as a prefix to 325661701eeSAndreas Gohr * each chunk to give the AI some context. 326661701eeSAndreas Gohr * 327661701eeSAndreas Gohr * @param string $id 328661701eeSAndreas Gohr * @return string 329661701eeSAndreas Gohr */ 330661701eeSAndreas Gohr protected function breadcrumbTrail($id) 331661701eeSAndreas Gohr { 332661701eeSAndreas Gohr $namespaces = explode(':', getNS($id)); 333661701eeSAndreas Gohr $resolver = new PageResolver($id); 334661701eeSAndreas Gohr $crumbs = []; 335661701eeSAndreas Gohr 336661701eeSAndreas Gohr // all namespaces 337661701eeSAndreas Gohr $check = ''; 338661701eeSAndreas Gohr foreach ($namespaces as $namespace) { 339661701eeSAndreas Gohr $check .= $namespace . ':'; 340661701eeSAndreas Gohr $page = $resolver->resolveId($check); 341661701eeSAndreas Gohr $title = p_get_first_heading($page); 342661701eeSAndreas Gohr $crumbs[] = $title ? "$title ($namespace)" : $namespace; 343661701eeSAndreas Gohr } 344661701eeSAndreas Gohr 345661701eeSAndreas Gohr // the page itself 346661701eeSAndreas Gohr $title = p_get_first_heading($id); 347661701eeSAndreas Gohr $page = noNS($id); 348661701eeSAndreas Gohr $crumbs[] = $title ? "$title ($page)" : $page; 349661701eeSAndreas Gohr 350661701eeSAndreas Gohr return implode(' » ', $crumbs); 351661701eeSAndreas Gohr } 3525786be46SAndreas Gohr 3535786be46SAndreas Gohr /** 3548817535bSAndreas Gohr * @param $text 3558817535bSAndreas Gohr * @return array 3568817535bSAndreas Gohr * @throws \Exception 3578817535bSAndreas Gohr * @todo support splitting too long sentences 3588817535bSAndreas Gohr */ 359ab1f8ddeSAndreas Gohr protected function splitIntoChunks($text) 3608817535bSAndreas Gohr { 3618817535bSAndreas Gohr $sentenceSplitter = new Sentence(); 36268908844SAndreas Gohr $tiktok = $this->getTokenEncoder(); 3638817535bSAndreas Gohr 3648817535bSAndreas Gohr $chunks = []; 3658817535bSAndreas Gohr $sentences = $sentenceSplitter->split($text); 3668817535bSAndreas Gohr 3678817535bSAndreas Gohr $chunklen = 0; 3688817535bSAndreas Gohr $chunk = ''; 3698817535bSAndreas Gohr while ($sentence = array_shift($sentences)) { 3708817535bSAndreas Gohr $slen = count($tiktok->encode($sentence)); 3716a18e0f4SAndreas Gohr if ($slen > $this->getChunkSize()) { 3728817535bSAndreas Gohr // sentence is too long, we need to split it further 373f8d5ae01SAndreas Gohr if ($this->logger instanceof CLI) $this->logger->warning( 374f8d5ae01SAndreas Gohr 'Sentence too long, splitting not implemented yet' 375f8d5ae01SAndreas Gohr ); 376ad38c5fdSAndreas Gohr continue; 3778817535bSAndreas Gohr } 3788817535bSAndreas Gohr 3796a18e0f4SAndreas Gohr if ($chunklen + $slen < $this->getChunkSize()) { 3808817535bSAndreas Gohr // add to current chunk 3818817535bSAndreas Gohr $chunk .= $sentence; 3828817535bSAndreas Gohr $chunklen += $slen; 38368908844SAndreas Gohr // remember sentence for overlap check 38468908844SAndreas Gohr $this->rememberSentence($sentence); 3858817535bSAndreas Gohr } else { 38668908844SAndreas Gohr // add current chunk to result 387ab1f8ddeSAndreas Gohr $chunk = trim($chunk); 388ab1f8ddeSAndreas Gohr if ($chunk !== '') $chunks[] = $chunk; 38968908844SAndreas Gohr 39068908844SAndreas Gohr // start new chunk with remembered sentences 3917ebc7895Ssplitbrain $chunk = implode(' ', $this->sentenceQueue); 39268908844SAndreas Gohr $chunk .= $sentence; 39368908844SAndreas Gohr $chunklen = count($tiktok->encode($chunk)); 3948817535bSAndreas Gohr } 3958817535bSAndreas Gohr } 3968817535bSAndreas Gohr $chunks[] = $chunk; 3978817535bSAndreas Gohr 3988817535bSAndreas Gohr return $chunks; 3998817535bSAndreas Gohr } 40068908844SAndreas Gohr 40168908844SAndreas Gohr /** 40268908844SAndreas Gohr * Add a sentence to the queue of remembered sentences 40368908844SAndreas Gohr * 40468908844SAndreas Gohr * @param string $sentence 40568908844SAndreas Gohr * @return void 40668908844SAndreas Gohr */ 40768908844SAndreas Gohr protected function rememberSentence($sentence) 40868908844SAndreas Gohr { 40968908844SAndreas Gohr // add sentence to queue 41068908844SAndreas Gohr $this->sentenceQueue[] = $sentence; 41168908844SAndreas Gohr 41268908844SAndreas Gohr // remove oldest sentences from queue until we are below the max overlap 41368908844SAndreas Gohr $encoder = $this->getTokenEncoder(); 4147ebc7895Ssplitbrain while (count($encoder->encode(implode(' ', $this->sentenceQueue))) > self::MAX_OVERLAP_LEN) { 41568908844SAndreas Gohr array_shift($this->sentenceQueue); 41668908844SAndreas Gohr } 41768908844SAndreas Gohr } 4188817535bSAndreas Gohr} 419