xref: /plugin/aichat/Storage/SQLiteStorage.php (revision e33a1d7adcbf36c57f516e2f829ec8ad59cdb47b)
13379af09SAndreas Gohr<?php /** @noinspection SqlResolve */
2f6ef2e50SAndreas Gohr
3f6ef2e50SAndreas Gohrnamespace dokuwiki\plugin\aichat\Storage;
4f6ef2e50SAndreas Gohr
5*e33a1d7aSAndreas Gohruse dokuwiki\plugin\aichat\AIChat;
6f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Chunk;
7f6ef2e50SAndreas Gohruse dokuwiki\plugin\sqlite\SQLiteDB;
83379af09SAndreas Gohruse KMeans\Cluster;
93379af09SAndreas Gohruse KMeans\Space;
10f6ef2e50SAndreas Gohr
11f6ef2e50SAndreas Gohr/**
12f6ef2e50SAndreas Gohr * Implements the storage backend using a SQLite database
1335555bacSAndreas Gohr *
1435555bacSAndreas Gohr * Note: all embeddings are stored and returned as normalized vectors
15f6ef2e50SAndreas Gohr */
16f6ef2e50SAndreas Gohrclass SQLiteStorage extends AbstractStorage
17f6ef2e50SAndreas Gohr{
1881b450c8SAndreas Gohr    /** @var float minimum similarity to consider a chunk a match */
1981b450c8SAndreas Gohr    const SIMILARITY_THRESHOLD = 0.75;
2081b450c8SAndreas Gohr
213379af09SAndreas Gohr    /** @var int Number of documents to randomly sample to create the clusters */
223379af09SAndreas Gohr    const SAMPLE_SIZE = 2000;
233379af09SAndreas Gohr    /** @var int The average size of each cluster */
243379af09SAndreas Gohr    const CLUSTER_SIZE = 400;
253379af09SAndreas Gohr
26f6ef2e50SAndreas Gohr    /** @var SQLiteDB */
27f6ef2e50SAndreas Gohr    protected $db;
28f6ef2e50SAndreas Gohr
29*e33a1d7aSAndreas Gohr    protected $useLanguageClusters = false;
30*e33a1d7aSAndreas Gohr
31f6ef2e50SAndreas Gohr    /**
32f6ef2e50SAndreas Gohr     * Initializes the database connection and registers our custom function
33f6ef2e50SAndreas Gohr     *
34f6ef2e50SAndreas Gohr     * @throws \Exception
35f6ef2e50SAndreas Gohr     */
36f6ef2e50SAndreas Gohr    public function __construct()
37f6ef2e50SAndreas Gohr    {
38f6ef2e50SAndreas Gohr        $this->db = new SQLiteDB('aichat', DOKU_PLUGIN . 'aichat/db/');
39f6ef2e50SAndreas Gohr        $this->db->getPdo()->sqliteCreateFunction('COSIM', [$this, 'sqliteCosineSimilarityCallback'], 2);
40*e33a1d7aSAndreas Gohr
41*e33a1d7aSAndreas Gohr        $helper = plugin_load('helper', 'aichat');
42*e33a1d7aSAndreas Gohr        $this->useLanguageClusters = $helper->getConf('preferUIlanguage') >= AIChat::LANG_UI_LIMITED;
43f6ef2e50SAndreas Gohr    }
44f6ef2e50SAndreas Gohr
45f6ef2e50SAndreas Gohr    /** @inheritdoc */
46f6ef2e50SAndreas Gohr    public function getChunk($chunkID)
47f6ef2e50SAndreas Gohr    {
48f6ef2e50SAndreas Gohr        $record = $this->db->queryRecord('SELECT * FROM embeddings WHERE id = ?', [$chunkID]);
49f6ef2e50SAndreas Gohr        if (!$record) return null;
50f6ef2e50SAndreas Gohr
51f6ef2e50SAndreas Gohr        return new Chunk(
52f6ef2e50SAndreas Gohr            $record['page'],
53f6ef2e50SAndreas Gohr            $record['id'],
54f6ef2e50SAndreas Gohr            $record['chunk'],
55f6ef2e50SAndreas Gohr            json_decode($record['embedding'], true),
56*e33a1d7aSAndreas Gohr            $record['lang'],
57f6ef2e50SAndreas Gohr            $record['created']
58f6ef2e50SAndreas Gohr        );
59f6ef2e50SAndreas Gohr    }
60f6ef2e50SAndreas Gohr
61f6ef2e50SAndreas Gohr    /** @inheritdoc */
62f6ef2e50SAndreas Gohr    public function startCreation($clear = false)
63f6ef2e50SAndreas Gohr    {
64f6ef2e50SAndreas Gohr        if ($clear) {
65f6ef2e50SAndreas Gohr            /** @noinspection SqlWithoutWhere */
66f6ef2e50SAndreas Gohr            $this->db->exec('DELETE FROM embeddings');
67f6ef2e50SAndreas Gohr        }
68f6ef2e50SAndreas Gohr    }
69f6ef2e50SAndreas Gohr
70f6ef2e50SAndreas Gohr    /** @inheritdoc */
71f6ef2e50SAndreas Gohr    public function reusePageChunks($page, $firstChunkID)
72f6ef2e50SAndreas Gohr    {
73f6ef2e50SAndreas Gohr        // no-op
74f6ef2e50SAndreas Gohr    }
75f6ef2e50SAndreas Gohr
76f6ef2e50SAndreas Gohr    /** @inheritdoc */
77f6ef2e50SAndreas Gohr    public function deletePageChunks($page, $firstChunkID)
78f6ef2e50SAndreas Gohr    {
79f6ef2e50SAndreas Gohr        $this->db->exec('DELETE FROM embeddings WHERE page = ?', [$page]);
80f6ef2e50SAndreas Gohr    }
81f6ef2e50SAndreas Gohr
82f6ef2e50SAndreas Gohr    /** @inheritdoc */
83f6ef2e50SAndreas Gohr    public function addPageChunks($chunks)
84f6ef2e50SAndreas Gohr    {
85f6ef2e50SAndreas Gohr        foreach ($chunks as $chunk) {
86f6ef2e50SAndreas Gohr            $this->db->saveRecord('embeddings', [
87f6ef2e50SAndreas Gohr                'page' => $chunk->getPage(),
88f6ef2e50SAndreas Gohr                'id' => $chunk->getId(),
89f6ef2e50SAndreas Gohr                'chunk' => $chunk->getText(),
90f6ef2e50SAndreas Gohr                'embedding' => json_encode($chunk->getEmbedding()),
91*e33a1d7aSAndreas Gohr                'created' => $chunk->getCreated(),
92*e33a1d7aSAndreas Gohr                'lang' => $chunk->getLanguage(),
93f6ef2e50SAndreas Gohr            ]);
94f6ef2e50SAndreas Gohr        }
95f6ef2e50SAndreas Gohr    }
96f6ef2e50SAndreas Gohr
97f6ef2e50SAndreas Gohr    /** @inheritdoc */
98f6ef2e50SAndreas Gohr    public function finalizeCreation()
99f6ef2e50SAndreas Gohr    {
1003379af09SAndreas Gohr        if (!$this->hasClusters()) {
1013379af09SAndreas Gohr            $this->createClusters();
1023379af09SAndreas Gohr        }
1033379af09SAndreas Gohr        $this->setChunkClusters();
1043379af09SAndreas Gohr
105f6ef2e50SAndreas Gohr        $this->db->exec('VACUUM');
106f6ef2e50SAndreas Gohr    }
107f6ef2e50SAndreas Gohr
108f6ef2e50SAndreas Gohr    /** @inheritdoc */
1093379af09SAndreas Gohr    public function runMaintenance()
1103379af09SAndreas Gohr    {
1113379af09SAndreas Gohr        $this->createClusters();
1123379af09SAndreas Gohr        $this->setChunkClusters();
1133379af09SAndreas Gohr    }
1143379af09SAndreas Gohr
1153379af09SAndreas Gohr    /** @inheritdoc */
11601f06932SAndreas Gohr    public function getPageChunks($page, $firstChunkID)
11701f06932SAndreas Gohr    {
11801f06932SAndreas Gohr        $result = $this->db->queryAll(
11901f06932SAndreas Gohr            'SELECT * FROM embeddings WHERE page = ?',
12001f06932SAndreas Gohr            [$page]
12101f06932SAndreas Gohr        );
12201f06932SAndreas Gohr        $chunks = [];
12301f06932SAndreas Gohr        foreach ($result as $record) {
12401f06932SAndreas Gohr            $chunks[] = new Chunk(
12501f06932SAndreas Gohr                $record['page'],
12601f06932SAndreas Gohr                $record['id'],
12701f06932SAndreas Gohr                $record['chunk'],
12801f06932SAndreas Gohr                json_decode($record['embedding'], true),
129*e33a1d7aSAndreas Gohr                $record['lang'],
13001f06932SAndreas Gohr                $record['created']
13101f06932SAndreas Gohr            );
13201f06932SAndreas Gohr        }
13301f06932SAndreas Gohr        return $chunks;
13401f06932SAndreas Gohr    }
13501f06932SAndreas Gohr
13601f06932SAndreas Gohr    /** @inheritdoc */
137*e33a1d7aSAndreas Gohr    public function getSimilarChunks($vector, $lang = '', $limit = 4)
138f6ef2e50SAndreas Gohr    {
139*e33a1d7aSAndreas Gohr        $cluster = $this->getCluster($vector, $lang);
1408285fff9SAndreas Gohr        if ($this->logger) $this->logger->info(
1418285fff9SAndreas Gohr            'Using cluster {cluster} for similarity search', ['cluster' => $cluster]
1428285fff9SAndreas Gohr        );
1433379af09SAndreas Gohr
144f6ef2e50SAndreas Gohr        $result = $this->db->queryAll(
145f6ef2e50SAndreas Gohr            'SELECT *, COSIM(?, embedding) AS similarity
146f6ef2e50SAndreas Gohr               FROM embeddings
1473379af09SAndreas Gohr              WHERE cluster = ?
1483379af09SAndreas Gohr                AND GETACCESSLEVEL(page) > 0
14981b450c8SAndreas Gohr                AND similarity > CAST(? AS FLOAT)
150f6ef2e50SAndreas Gohr           ORDER BY similarity DESC
151f6ef2e50SAndreas Gohr              LIMIT ?',
1523379af09SAndreas Gohr            [json_encode($vector), $cluster, self::SIMILARITY_THRESHOLD, $limit]
153f6ef2e50SAndreas Gohr        );
154f6ef2e50SAndreas Gohr        $chunks = [];
155f6ef2e50SAndreas Gohr        foreach ($result as $record) {
156f6ef2e50SAndreas Gohr            $chunks[] = new Chunk(
157f6ef2e50SAndreas Gohr                $record['page'],
158f6ef2e50SAndreas Gohr                $record['id'],
159f6ef2e50SAndreas Gohr                $record['chunk'],
160f6ef2e50SAndreas Gohr                json_decode($record['embedding'], true),
161*e33a1d7aSAndreas Gohr                $record['lang'],
1629b3d1b36SAndreas Gohr                $record['created'],
1639b3d1b36SAndreas Gohr                $record['similarity']
164f6ef2e50SAndreas Gohr            );
165f6ef2e50SAndreas Gohr        }
166f6ef2e50SAndreas Gohr        return $chunks;
167f6ef2e50SAndreas Gohr    }
168f6ef2e50SAndreas Gohr
169f6ef2e50SAndreas Gohr    /** @inheritdoc */
170f6ef2e50SAndreas Gohr    public function statistics()
171f6ef2e50SAndreas Gohr    {
172f6ef2e50SAndreas Gohr        $items = $this->db->queryValue('SELECT COUNT(*) FROM embeddings');
173f6ef2e50SAndreas Gohr        $size = $this->db->queryValue(
174f6ef2e50SAndreas Gohr            'SELECT page_count * page_size as size FROM pragma_page_count(), pragma_page_size()'
175f6ef2e50SAndreas Gohr        );
176*e33a1d7aSAndreas Gohr        $query = "SELECT cluster || ' ' || lang, COUNT(*) || ' chunks' as cnt FROM embeddings GROUP BY cluster ORDER BY cluster";
1773379af09SAndreas Gohr        $clusters = $this->db->queryKeyValueList($query);
1783379af09SAndreas Gohr
179f6ef2e50SAndreas Gohr        return [
180f6ef2e50SAndreas Gohr            'storage type' => 'SQLite',
181f6ef2e50SAndreas Gohr            'chunks' => $items,
1823379af09SAndreas Gohr            'db size' => filesize_h($size),
1833379af09SAndreas Gohr            'clusters' => $clusters,
184f6ef2e50SAndreas Gohr        ];
185f6ef2e50SAndreas Gohr    }
186f6ef2e50SAndreas Gohr
187f6ef2e50SAndreas Gohr    /**
188f6ef2e50SAndreas Gohr     * Method registered as SQLite callback to calculate the cosine similarity
189f6ef2e50SAndreas Gohr     *
190f6ef2e50SAndreas Gohr     * @param string $query JSON encoded vector array
191f6ef2e50SAndreas Gohr     * @param string $embedding JSON encoded vector array
192f6ef2e50SAndreas Gohr     * @return float
193f6ef2e50SAndreas Gohr     */
194f6ef2e50SAndreas Gohr    public function sqliteCosineSimilarityCallback($query, $embedding)
195f6ef2e50SAndreas Gohr    {
196f6ef2e50SAndreas Gohr        return (float)$this->cosineSimilarity(json_decode($query), json_decode($embedding));
197f6ef2e50SAndreas Gohr    }
198f6ef2e50SAndreas Gohr
199f6ef2e50SAndreas Gohr    /**
200f6ef2e50SAndreas Gohr     * Calculate the cosine similarity between two vectors
201f6ef2e50SAndreas Gohr     *
20235555bacSAndreas Gohr     * Actually just calculating the dot product of the two vectors, since they are normalized
20335555bacSAndreas Gohr     *
20435555bacSAndreas Gohr     * @param float[] $queryVector The normalized vector of the search phrase
20535555bacSAndreas Gohr     * @param float[] $embedding The normalized vector of the chunk
206f6ef2e50SAndreas Gohr     * @return float
207f6ef2e50SAndreas Gohr     */
208f6ef2e50SAndreas Gohr    protected function cosineSimilarity($queryVector, $embedding)
209f6ef2e50SAndreas Gohr    {
210f6ef2e50SAndreas Gohr        $dotProduct = 0;
211f6ef2e50SAndreas Gohr        foreach ($queryVector as $key => $value) {
212f6ef2e50SAndreas Gohr            $dotProduct += $value * $embedding[$key];
213f6ef2e50SAndreas Gohr        }
21435555bacSAndreas Gohr        return $dotProduct;
215f6ef2e50SAndreas Gohr    }
2163379af09SAndreas Gohr
2173379af09SAndreas Gohr    /**
2183379af09SAndreas Gohr     * Create new clusters based on random chunks
2193379af09SAndreas Gohr     *
220*e33a1d7aSAndreas Gohr     * @return void
2213379af09SAndreas Gohr     */
2223379af09SAndreas Gohr    protected function createClusters()
2233379af09SAndreas Gohr    {
224*e33a1d7aSAndreas Gohr        if($this->useLanguageClusters) {
225*e33a1d7aSAndreas Gohr            $result = $this->db->queryAll('SELECT DISTINCT lang FROM embeddings');
226*e33a1d7aSAndreas Gohr            $langs = array_column($result, 'lang');
227*e33a1d7aSAndreas Gohr            foreach ($langs as $lang) {
228*e33a1d7aSAndreas Gohr                $this->createLanguageClusters($lang);
229*e33a1d7aSAndreas Gohr            }
230*e33a1d7aSAndreas Gohr        } else {
231*e33a1d7aSAndreas Gohr            $this->createLanguageClusters('');
232*e33a1d7aSAndreas Gohr        }
233*e33a1d7aSAndreas Gohr    }
234*e33a1d7aSAndreas Gohr
235*e33a1d7aSAndreas Gohr    /**
236*e33a1d7aSAndreas Gohr     * Create new clusters based on random chunks for the given Language
237*e33a1d7aSAndreas Gohr     *
238*e33a1d7aSAndreas Gohr     * @param string $lang The language to cluster, empty when all languages go into the same cluster
239*e33a1d7aSAndreas Gohr     * @noinspection SqlWithoutWhere
240*e33a1d7aSAndreas Gohr     */
241*e33a1d7aSAndreas Gohr    protected function createLanguageClusters($lang)
242*e33a1d7aSAndreas Gohr    {
243*e33a1d7aSAndreas Gohr        if($lang != '') {
244*e33a1d7aSAndreas Gohr            $where = 'WHERE lang = '. $this->db->getPdo()->quote($lang);
245*e33a1d7aSAndreas Gohr        } else {
246*e33a1d7aSAndreas Gohr            $where = '';
247*e33a1d7aSAndreas Gohr        }
248*e33a1d7aSAndreas Gohr
249*e33a1d7aSAndreas Gohr        if ($this->logger) $this->logger->info('Creating new {lang} clusters...', ['lang' => $lang]);
2503379af09SAndreas Gohr        $this->db->getPdo()->beginTransaction();
2513379af09SAndreas Gohr        try {
2523379af09SAndreas Gohr            // clean up old cluster data
253*e33a1d7aSAndreas Gohr            $query = "DELETE FROM clusters $where";
2543379af09SAndreas Gohr            $this->db->exec($query);
255*e33a1d7aSAndreas Gohr            $query = "UPDATE embeddings SET cluster = NULL $where";
2563379af09SAndreas Gohr            $this->db->exec($query);
2573379af09SAndreas Gohr
2583379af09SAndreas Gohr            // get a random selection of chunks
259*e33a1d7aSAndreas Gohr            $query = "SELECT id, embedding FROM embeddings $where ORDER BY RANDOM() LIMIT ?";
2603379af09SAndreas Gohr            $result = $this->db->queryAll($query, [self::SAMPLE_SIZE]);
2613379af09SAndreas Gohr            if (!$result) return; // no data to cluster
2623379af09SAndreas Gohr            $dimensions = count(json_decode($result[0]['embedding'], true));
2633379af09SAndreas Gohr
2643379af09SAndreas Gohr            // get the number of all chunks, to calculate the number of clusters
265*e33a1d7aSAndreas Gohr            $query = "SELECT COUNT(*) FROM embeddings $where";
2663379af09SAndreas Gohr            $total = $this->db->queryValue($query);
2673379af09SAndreas Gohr            $clustercount = ceil($total / self::CLUSTER_SIZE);
2683379af09SAndreas Gohr            if ($this->logger) $this->logger->info('Creating {clusters} clusters', ['clusters' => $clustercount]);
2693379af09SAndreas Gohr
2703379af09SAndreas Gohr            // cluster them using kmeans
2713379af09SAndreas Gohr            $space = new Space($dimensions);
2723379af09SAndreas Gohr            foreach ($result as $record) {
2733379af09SAndreas Gohr                $space->addPoint(json_decode($record['embedding'], true));
2743379af09SAndreas Gohr            }
2753379af09SAndreas Gohr            $clusters = $space->solve($clustercount, function ($space, $clusters) {
2763379af09SAndreas Gohr                static $iterations = 0;
2773379af09SAndreas Gohr                ++$iterations;
2783379af09SAndreas Gohr                if ($this->logger) {
2793379af09SAndreas Gohr                    $clustercounts = join(',', array_map('count', $clusters));
2803379af09SAndreas Gohr                    $this->logger->info('Iteration {iteration}: [{clusters}]', [
2813379af09SAndreas Gohr                        'iteration' => $iterations, 'clusters' => $clustercounts
2823379af09SAndreas Gohr                    ]);
2833379af09SAndreas Gohr                }
2843379af09SAndreas Gohr            }, Cluster::INIT_KMEANS_PLUS_PLUS);
2853379af09SAndreas Gohr
2863379af09SAndreas Gohr            // store the clusters
2873379af09SAndreas Gohr            foreach ($clusters as $clusterID => $cluster) {
2883379af09SAndreas Gohr                /** @var Cluster $cluster */
2893379af09SAndreas Gohr                $centroid = $cluster->getCoordinates();
290*e33a1d7aSAndreas Gohr                $query = 'INSERT INTO clusters (lang, centroid) VALUES (?, ?)';
291*e33a1d7aSAndreas Gohr                $this->db->exec($query, [$lang, json_encode($centroid)]);
2923379af09SAndreas Gohr            }
2933379af09SAndreas Gohr
2943379af09SAndreas Gohr            $this->db->getPdo()->commit();
2953379af09SAndreas Gohr            if ($this->logger) $this->logger->success('Created {clusters} clusters', ['clusters' => count($clusters)]);
2963379af09SAndreas Gohr        } catch (\Exception $e) {
2973379af09SAndreas Gohr            $this->db->getPdo()->rollBack();
298*e33a1d7aSAndreas Gohr            throw new \RuntimeException('Clustering failed: '.$e->getMessage(), 0, $e);
2993379af09SAndreas Gohr        }
3003379af09SAndreas Gohr    }
3013379af09SAndreas Gohr
3023379af09SAndreas Gohr    /**
3033379af09SAndreas Gohr     * Assign the nearest cluster for all chunks that don't have one
3043379af09SAndreas Gohr     *
3053379af09SAndreas Gohr     * @return void
3063379af09SAndreas Gohr     */
3073379af09SAndreas Gohr    protected function setChunkClusters()
3083379af09SAndreas Gohr    {
3093379af09SAndreas Gohr        if ($this->logger) $this->logger->info('Assigning clusters to chunks...');
310*e33a1d7aSAndreas Gohr        $query = 'SELECT id, embedding, lang FROM embeddings WHERE cluster IS NULL';
3113379af09SAndreas Gohr        $handle = $this->db->query($query);
3123379af09SAndreas Gohr
3133379af09SAndreas Gohr        while ($record = $handle->fetch(\PDO::FETCH_ASSOC)) {
3143379af09SAndreas Gohr            $vector = json_decode($record['embedding'], true);
315*e33a1d7aSAndreas Gohr            $cluster = $this->getCluster($vector, $this->useLanguageClusters ? $record['lang'] : '');
3163379af09SAndreas Gohr            $query = 'UPDATE embeddings SET cluster = ? WHERE id = ?';
3173379af09SAndreas Gohr            $this->db->exec($query, [$cluster, $record['id']]);
3183379af09SAndreas Gohr            if ($this->logger) $this->logger->success(
3193379af09SAndreas Gohr                'Chunk {id} assigned to cluster {cluster}', ['id' => $record['id'], 'cluster' => $cluster]
3203379af09SAndreas Gohr            );
3213379af09SAndreas Gohr        }
3223379af09SAndreas Gohr        $handle->closeCursor();
3233379af09SAndreas Gohr    }
3243379af09SAndreas Gohr
3253379af09SAndreas Gohr    /**
3263379af09SAndreas Gohr     * Get the nearest cluster for the given vector
3273379af09SAndreas Gohr     *
3283379af09SAndreas Gohr     * @param float[] $vector
3293379af09SAndreas Gohr     * @return int|null
3303379af09SAndreas Gohr     */
331*e33a1d7aSAndreas Gohr    protected function getCluster($vector, $lang)
3323379af09SAndreas Gohr    {
333*e33a1d7aSAndreas Gohr        if($lang != '') {
334*e33a1d7aSAndreas Gohr            $where = 'WHERE lang = '. $this->db->getPdo()->quote($lang);
335*e33a1d7aSAndreas Gohr        } else {
336*e33a1d7aSAndreas Gohr            $where = '';
337*e33a1d7aSAndreas Gohr        }
338*e33a1d7aSAndreas Gohr
339*e33a1d7aSAndreas Gohr        $query = "SELECT cluster, centroid
340*e33a1d7aSAndreas Gohr                    FROM clusters
341*e33a1d7aSAndreas Gohr                   $where
342*e33a1d7aSAndreas Gohr                ORDER BY COSIM(centroid, ?) DESC
343*e33a1d7aSAndreas Gohr                   LIMIT 1";
344*e33a1d7aSAndreas Gohr
3453379af09SAndreas Gohr        $result = $this->db->queryRecord($query, [json_encode($vector)]);
3463379af09SAndreas Gohr        if (!$result) return null;
3473379af09SAndreas Gohr        return $result['cluster'];
3483379af09SAndreas Gohr    }
3493379af09SAndreas Gohr
3503379af09SAndreas Gohr    /**
3513379af09SAndreas Gohr     * Check if clustering has been done before
3523379af09SAndreas Gohr     * @return bool
3533379af09SAndreas Gohr     */
3543379af09SAndreas Gohr    protected function hasClusters()
3553379af09SAndreas Gohr    {
3563379af09SAndreas Gohr        $query = 'SELECT COUNT(*) FROM clusters';
3573379af09SAndreas Gohr        return $this->db->queryValue($query) > 0;
3583379af09SAndreas Gohr    }
3598c8b7ba6SAndreas Gohr
3608c8b7ba6SAndreas Gohr    /**
3618c8b7ba6SAndreas Gohr     * Writes TSV files for visualizing with http://projector.tensorflow.org/
3628c8b7ba6SAndreas Gohr     *
3638c8b7ba6SAndreas Gohr     * @param string $vectorfile path to the file with the vectors
3648c8b7ba6SAndreas Gohr     * @param string $metafile path to the file with the metadata
3658c8b7ba6SAndreas Gohr     * @return void
3668c8b7ba6SAndreas Gohr     */
3678c8b7ba6SAndreas Gohr    public function dumpTSV($vectorfile, $metafile)
3688c8b7ba6SAndreas Gohr    {
3698c8b7ba6SAndreas Gohr        $query = 'SELECT * FROM embeddings';
3708c8b7ba6SAndreas Gohr        $handle = $this->db->query($query);
3718c8b7ba6SAndreas Gohr
3728c8b7ba6SAndreas Gohr        $header = implode("\t", ['id', 'page', 'created']);
3738c8b7ba6SAndreas Gohr        file_put_contents($metafile, $header . "\n", FILE_APPEND);
3748c8b7ba6SAndreas Gohr
3758c8b7ba6SAndreas Gohr        while ($row = $handle->fetch(\PDO::FETCH_ASSOC)) {
3768c8b7ba6SAndreas Gohr            $vector = json_decode($row['embedding'], true);
3778c8b7ba6SAndreas Gohr            $vector = implode("\t", $vector);
3788c8b7ba6SAndreas Gohr
3798c8b7ba6SAndreas Gohr            $meta = implode("\t", [$row['id'], $row['page'], $row['created']]);
3808c8b7ba6SAndreas Gohr
3818c8b7ba6SAndreas Gohr            file_put_contents($vectorfile, $vector . "\n", FILE_APPEND);
3828c8b7ba6SAndreas Gohr            file_put_contents($metafile, $meta . "\n", FILE_APPEND);
3838c8b7ba6SAndreas Gohr        }
3848c8b7ba6SAndreas Gohr    }
385f6ef2e50SAndreas Gohr}
386