xref: /plugin/aichat/Storage/SQLiteStorage.php (revision 7ebc78955c65af90e7ee0afbd07adc15271113ba)
1*7ebc7895Ssplitbrain<?php
2*7ebc7895Ssplitbrain
3*7ebc7895Ssplitbrain/** @noinspection SqlResolve */
4f6ef2e50SAndreas Gohr
5f6ef2e50SAndreas Gohrnamespace dokuwiki\plugin\aichat\Storage;
6f6ef2e50SAndreas Gohr
7e33a1d7aSAndreas Gohruse dokuwiki\plugin\aichat\AIChat;
8f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Chunk;
9f6ef2e50SAndreas Gohruse dokuwiki\plugin\sqlite\SQLiteDB;
103379af09SAndreas Gohruse KMeans\Cluster;
113379af09SAndreas Gohruse KMeans\Space;
12f6ef2e50SAndreas Gohr
13f6ef2e50SAndreas Gohr/**
14f6ef2e50SAndreas Gohr * Implements the storage backend using a SQLite database
1535555bacSAndreas Gohr *
1635555bacSAndreas Gohr * Note: all embeddings are stored and returned as normalized vectors
17f6ef2e50SAndreas Gohr */
18f6ef2e50SAndreas Gohrclass SQLiteStorage extends AbstractStorage
19f6ef2e50SAndreas Gohr{
2081b450c8SAndreas Gohr    /** @var float minimum similarity to consider a chunk a match */
21*7ebc7895Ssplitbrain    public const SIMILARITY_THRESHOLD = 0.75;
2281b450c8SAndreas Gohr
233379af09SAndreas Gohr    /** @var int Number of documents to randomly sample to create the clusters */
24*7ebc7895Ssplitbrain    public const SAMPLE_SIZE = 2000;
253379af09SAndreas Gohr    /** @var int The average size of each cluster */
26*7ebc7895Ssplitbrain    public const CLUSTER_SIZE = 400;
273379af09SAndreas Gohr
28f6ef2e50SAndreas Gohr    /** @var SQLiteDB */
29f6ef2e50SAndreas Gohr    protected $db;
30f6ef2e50SAndreas Gohr
31e33a1d7aSAndreas Gohr    protected $useLanguageClusters = false;
32e33a1d7aSAndreas Gohr
33f6ef2e50SAndreas Gohr    /**
34f6ef2e50SAndreas Gohr     * Initializes the database connection and registers our custom function
35f6ef2e50SAndreas Gohr     *
36f6ef2e50SAndreas Gohr     * @throws \Exception
37f6ef2e50SAndreas Gohr     */
38f6ef2e50SAndreas Gohr    public function __construct()
39f6ef2e50SAndreas Gohr    {
40f6ef2e50SAndreas Gohr        $this->db = new SQLiteDB('aichat', DOKU_PLUGIN . 'aichat/db/');
41f6ef2e50SAndreas Gohr        $this->db->getPdo()->sqliteCreateFunction('COSIM', [$this, 'sqliteCosineSimilarityCallback'], 2);
42e33a1d7aSAndreas Gohr
43e33a1d7aSAndreas Gohr        $helper = plugin_load('helper', 'aichat');
44e33a1d7aSAndreas Gohr        $this->useLanguageClusters = $helper->getConf('preferUIlanguage') >= AIChat::LANG_UI_LIMITED;
45f6ef2e50SAndreas Gohr    }
46f6ef2e50SAndreas Gohr
47f6ef2e50SAndreas Gohr    /** @inheritdoc */
48f6ef2e50SAndreas Gohr    public function getChunk($chunkID)
49f6ef2e50SAndreas Gohr    {
50f6ef2e50SAndreas Gohr        $record = $this->db->queryRecord('SELECT * FROM embeddings WHERE id = ?', [$chunkID]);
51f6ef2e50SAndreas Gohr        if (!$record) return null;
52f6ef2e50SAndreas Gohr
53f6ef2e50SAndreas Gohr        return new Chunk(
54f6ef2e50SAndreas Gohr            $record['page'],
55f6ef2e50SAndreas Gohr            $record['id'],
56f6ef2e50SAndreas Gohr            $record['chunk'],
57f6ef2e50SAndreas Gohr            json_decode($record['embedding'], true),
58e33a1d7aSAndreas Gohr            $record['lang'],
59f6ef2e50SAndreas Gohr            $record['created']
60f6ef2e50SAndreas Gohr        );
61f6ef2e50SAndreas Gohr    }
62f6ef2e50SAndreas Gohr
63f6ef2e50SAndreas Gohr    /** @inheritdoc */
64f6ef2e50SAndreas Gohr    public function startCreation($clear = false)
65f6ef2e50SAndreas Gohr    {
66f6ef2e50SAndreas Gohr        if ($clear) {
67f6ef2e50SAndreas Gohr            /** @noinspection SqlWithoutWhere */
68f6ef2e50SAndreas Gohr            $this->db->exec('DELETE FROM embeddings');
69f6ef2e50SAndreas Gohr        }
70f6ef2e50SAndreas Gohr    }
71f6ef2e50SAndreas Gohr
72f6ef2e50SAndreas Gohr    /** @inheritdoc */
73f6ef2e50SAndreas Gohr    public function reusePageChunks($page, $firstChunkID)
74f6ef2e50SAndreas Gohr    {
75f6ef2e50SAndreas Gohr        // no-op
76f6ef2e50SAndreas Gohr    }
77f6ef2e50SAndreas Gohr
78f6ef2e50SAndreas Gohr    /** @inheritdoc */
79f6ef2e50SAndreas Gohr    public function deletePageChunks($page, $firstChunkID)
80f6ef2e50SAndreas Gohr    {
81f6ef2e50SAndreas Gohr        $this->db->exec('DELETE FROM embeddings WHERE page = ?', [$page]);
82f6ef2e50SAndreas Gohr    }
83f6ef2e50SAndreas Gohr
84f6ef2e50SAndreas Gohr    /** @inheritdoc */
85f6ef2e50SAndreas Gohr    public function addPageChunks($chunks)
86f6ef2e50SAndreas Gohr    {
87f6ef2e50SAndreas Gohr        foreach ($chunks as $chunk) {
88f6ef2e50SAndreas Gohr            $this->db->saveRecord('embeddings', [
89f6ef2e50SAndreas Gohr                'page' => $chunk->getPage(),
90f6ef2e50SAndreas Gohr                'id' => $chunk->getId(),
91f6ef2e50SAndreas Gohr                'chunk' => $chunk->getText(),
92f6ef2e50SAndreas Gohr                'embedding' => json_encode($chunk->getEmbedding()),
93e33a1d7aSAndreas Gohr                'created' => $chunk->getCreated(),
94e33a1d7aSAndreas Gohr                'lang' => $chunk->getLanguage(),
95f6ef2e50SAndreas Gohr            ]);
96f6ef2e50SAndreas Gohr        }
97f6ef2e50SAndreas Gohr    }
98f6ef2e50SAndreas Gohr
99f6ef2e50SAndreas Gohr    /** @inheritdoc */
100f6ef2e50SAndreas Gohr    public function finalizeCreation()
101f6ef2e50SAndreas Gohr    {
1023379af09SAndreas Gohr        if (!$this->hasClusters()) {
1033379af09SAndreas Gohr            $this->createClusters();
1043379af09SAndreas Gohr        }
1053379af09SAndreas Gohr        $this->setChunkClusters();
1063379af09SAndreas Gohr
107f6ef2e50SAndreas Gohr        $this->db->exec('VACUUM');
108f6ef2e50SAndreas Gohr    }
109f6ef2e50SAndreas Gohr
110f6ef2e50SAndreas Gohr    /** @inheritdoc */
1113379af09SAndreas Gohr    public function runMaintenance()
1123379af09SAndreas Gohr    {
1133379af09SAndreas Gohr        $this->createClusters();
1143379af09SAndreas Gohr        $this->setChunkClusters();
1153379af09SAndreas Gohr    }
1163379af09SAndreas Gohr
1173379af09SAndreas Gohr    /** @inheritdoc */
11801f06932SAndreas Gohr    public function getPageChunks($page, $firstChunkID)
11901f06932SAndreas Gohr    {
12001f06932SAndreas Gohr        $result = $this->db->queryAll(
12101f06932SAndreas Gohr            'SELECT * FROM embeddings WHERE page = ?',
12201f06932SAndreas Gohr            [$page]
12301f06932SAndreas Gohr        );
12401f06932SAndreas Gohr        $chunks = [];
12501f06932SAndreas Gohr        foreach ($result as $record) {
12601f06932SAndreas Gohr            $chunks[] = new Chunk(
12701f06932SAndreas Gohr                $record['page'],
12801f06932SAndreas Gohr                $record['id'],
12901f06932SAndreas Gohr                $record['chunk'],
13001f06932SAndreas Gohr                json_decode($record['embedding'], true),
131e33a1d7aSAndreas Gohr                $record['lang'],
13201f06932SAndreas Gohr                $record['created']
13301f06932SAndreas Gohr            );
13401f06932SAndreas Gohr        }
13501f06932SAndreas Gohr        return $chunks;
13601f06932SAndreas Gohr    }
13701f06932SAndreas Gohr
13801f06932SAndreas Gohr    /** @inheritdoc */
139e33a1d7aSAndreas Gohr    public function getSimilarChunks($vector, $lang = '', $limit = 4)
140f6ef2e50SAndreas Gohr    {
141e33a1d7aSAndreas Gohr        $cluster = $this->getCluster($vector, $lang);
1428285fff9SAndreas Gohr        if ($this->logger) $this->logger->info(
143*7ebc7895Ssplitbrain            'Using cluster {cluster} for similarity search',
144*7ebc7895Ssplitbrain            ['cluster' => $cluster]
1458285fff9SAndreas Gohr        );
1463379af09SAndreas Gohr
147f6ef2e50SAndreas Gohr        $result = $this->db->queryAll(
148f6ef2e50SAndreas Gohr            'SELECT *, COSIM(?, embedding) AS similarity
149f6ef2e50SAndreas Gohr               FROM embeddings
1503379af09SAndreas Gohr              WHERE cluster = ?
1513379af09SAndreas Gohr                AND GETACCESSLEVEL(page) > 0
15281b450c8SAndreas Gohr                AND similarity > CAST(? AS FLOAT)
153f6ef2e50SAndreas Gohr           ORDER BY similarity DESC
154f6ef2e50SAndreas Gohr              LIMIT ?',
1553379af09SAndreas Gohr            [json_encode($vector), $cluster, self::SIMILARITY_THRESHOLD, $limit]
156f6ef2e50SAndreas Gohr        );
157f6ef2e50SAndreas Gohr        $chunks = [];
158f6ef2e50SAndreas Gohr        foreach ($result as $record) {
159f6ef2e50SAndreas Gohr            $chunks[] = new Chunk(
160f6ef2e50SAndreas Gohr                $record['page'],
161f6ef2e50SAndreas Gohr                $record['id'],
162f6ef2e50SAndreas Gohr                $record['chunk'],
163f6ef2e50SAndreas Gohr                json_decode($record['embedding'], true),
164e33a1d7aSAndreas Gohr                $record['lang'],
1659b3d1b36SAndreas Gohr                $record['created'],
1669b3d1b36SAndreas Gohr                $record['similarity']
167f6ef2e50SAndreas Gohr            );
168f6ef2e50SAndreas Gohr        }
169f6ef2e50SAndreas Gohr        return $chunks;
170f6ef2e50SAndreas Gohr    }
171f6ef2e50SAndreas Gohr
172f6ef2e50SAndreas Gohr    /** @inheritdoc */
173f6ef2e50SAndreas Gohr    public function statistics()
174f6ef2e50SAndreas Gohr    {
175f6ef2e50SAndreas Gohr        $items = $this->db->queryValue('SELECT COUNT(*) FROM embeddings');
176f6ef2e50SAndreas Gohr        $size = $this->db->queryValue(
177f6ef2e50SAndreas Gohr            'SELECT page_count * page_size as size FROM pragma_page_count(), pragma_page_size()'
178f6ef2e50SAndreas Gohr        );
179e33a1d7aSAndreas Gohr        $query = "SELECT cluster || ' ' || lang, COUNT(*) || ' chunks' as cnt FROM embeddings GROUP BY cluster ORDER BY cluster";
1803379af09SAndreas Gohr        $clusters = $this->db->queryKeyValueList($query);
1813379af09SAndreas Gohr
182f6ef2e50SAndreas Gohr        return [
183f6ef2e50SAndreas Gohr            'storage type' => 'SQLite',
184f6ef2e50SAndreas Gohr            'chunks' => $items,
1853379af09SAndreas Gohr            'db size' => filesize_h($size),
1863379af09SAndreas Gohr            'clusters' => $clusters,
187f6ef2e50SAndreas Gohr        ];
188f6ef2e50SAndreas Gohr    }
189f6ef2e50SAndreas Gohr
190f6ef2e50SAndreas Gohr    /**
191f6ef2e50SAndreas Gohr     * Method registered as SQLite callback to calculate the cosine similarity
192f6ef2e50SAndreas Gohr     *
193f6ef2e50SAndreas Gohr     * @param string $query JSON encoded vector array
194f6ef2e50SAndreas Gohr     * @param string $embedding JSON encoded vector array
195f6ef2e50SAndreas Gohr     * @return float
196f6ef2e50SAndreas Gohr     */
197f6ef2e50SAndreas Gohr    public function sqliteCosineSimilarityCallback($query, $embedding)
198f6ef2e50SAndreas Gohr    {
199f6ef2e50SAndreas Gohr        return (float)$this->cosineSimilarity(json_decode($query), json_decode($embedding));
200f6ef2e50SAndreas Gohr    }
201f6ef2e50SAndreas Gohr
202f6ef2e50SAndreas Gohr    /**
203f6ef2e50SAndreas Gohr     * Calculate the cosine similarity between two vectors
204f6ef2e50SAndreas Gohr     *
20535555bacSAndreas Gohr     * Actually just calculating the dot product of the two vectors, since they are normalized
20635555bacSAndreas Gohr     *
20735555bacSAndreas Gohr     * @param float[] $queryVector The normalized vector of the search phrase
20835555bacSAndreas Gohr     * @param float[] $embedding The normalized vector of the chunk
209f6ef2e50SAndreas Gohr     * @return float
210f6ef2e50SAndreas Gohr     */
211f6ef2e50SAndreas Gohr    protected function cosineSimilarity($queryVector, $embedding)
212f6ef2e50SAndreas Gohr    {
213f6ef2e50SAndreas Gohr        $dotProduct = 0;
214f6ef2e50SAndreas Gohr        foreach ($queryVector as $key => $value) {
215f6ef2e50SAndreas Gohr            $dotProduct += $value * $embedding[$key];
216f6ef2e50SAndreas Gohr        }
21735555bacSAndreas Gohr        return $dotProduct;
218f6ef2e50SAndreas Gohr    }
2193379af09SAndreas Gohr
2203379af09SAndreas Gohr    /**
2213379af09SAndreas Gohr     * Create new clusters based on random chunks
2223379af09SAndreas Gohr     *
223e33a1d7aSAndreas Gohr     * @return void
2243379af09SAndreas Gohr     */
2253379af09SAndreas Gohr    protected function createClusters()
2263379af09SAndreas Gohr    {
227e33a1d7aSAndreas Gohr        if ($this->useLanguageClusters) {
228e33a1d7aSAndreas Gohr            $result = $this->db->queryAll('SELECT DISTINCT lang FROM embeddings');
229e33a1d7aSAndreas Gohr            $langs = array_column($result, 'lang');
230e33a1d7aSAndreas Gohr            foreach ($langs as $lang) {
231e33a1d7aSAndreas Gohr                $this->createLanguageClusters($lang);
232e33a1d7aSAndreas Gohr            }
233e33a1d7aSAndreas Gohr        } else {
234e33a1d7aSAndreas Gohr            $this->createLanguageClusters('');
235e33a1d7aSAndreas Gohr        }
236e33a1d7aSAndreas Gohr    }
237e33a1d7aSAndreas Gohr
238e33a1d7aSAndreas Gohr    /**
239e33a1d7aSAndreas Gohr     * Create new clusters based on random chunks for the given Language
240e33a1d7aSAndreas Gohr     *
241e33a1d7aSAndreas Gohr     * @param string $lang The language to cluster, empty when all languages go into the same cluster
242e33a1d7aSAndreas Gohr     * @noinspection SqlWithoutWhere
243e33a1d7aSAndreas Gohr     */
244e33a1d7aSAndreas Gohr    protected function createLanguageClusters($lang)
245e33a1d7aSAndreas Gohr    {
246e33a1d7aSAndreas Gohr        if ($lang != '') {
247e33a1d7aSAndreas Gohr            $where = 'WHERE lang = ' . $this->db->getPdo()->quote($lang);
248e33a1d7aSAndreas Gohr        } else {
249e33a1d7aSAndreas Gohr            $where = '';
250e33a1d7aSAndreas Gohr        }
251e33a1d7aSAndreas Gohr
252e33a1d7aSAndreas Gohr        if ($this->logger) $this->logger->info('Creating new {lang} clusters...', ['lang' => $lang]);
2533379af09SAndreas Gohr        $this->db->getPdo()->beginTransaction();
2543379af09SAndreas Gohr        try {
2553379af09SAndreas Gohr            // clean up old cluster data
256e33a1d7aSAndreas Gohr            $query = "DELETE FROM clusters $where";
2573379af09SAndreas Gohr            $this->db->exec($query);
258e33a1d7aSAndreas Gohr            $query = "UPDATE embeddings SET cluster = NULL $where";
2593379af09SAndreas Gohr            $this->db->exec($query);
2603379af09SAndreas Gohr
2613379af09SAndreas Gohr            // get a random selection of chunks
262e33a1d7aSAndreas Gohr            $query = "SELECT id, embedding FROM embeddings $where ORDER BY RANDOM() LIMIT ?";
2633379af09SAndreas Gohr            $result = $this->db->queryAll($query, [self::SAMPLE_SIZE]);
2643379af09SAndreas Gohr            if (!$result) return; // no data to cluster
2653379af09SAndreas Gohr            $dimensions = count(json_decode($result[0]['embedding'], true));
2663379af09SAndreas Gohr
267adfc5429SAndreas Gohr            // how many clusters?
268adfc5429SAndreas Gohr            if (count($result) < self::CLUSTER_SIZE * 3) {
269adfc5429SAndreas Gohr                // there would be less than 3 clusters, so just use one
270adfc5429SAndreas Gohr                $clustercount = 1;
271adfc5429SAndreas Gohr            } else {
2723379af09SAndreas Gohr                // get the number of all chunks, to calculate the number of clusters
273e33a1d7aSAndreas Gohr                $query = "SELECT COUNT(*) FROM embeddings $where";
2743379af09SAndreas Gohr                $total = $this->db->queryValue($query);
2753379af09SAndreas Gohr                $clustercount = ceil($total / self::CLUSTER_SIZE);
276adfc5429SAndreas Gohr            }
2773379af09SAndreas Gohr            if ($this->logger) $this->logger->info('Creating {clusters} clusters', ['clusters' => $clustercount]);
2783379af09SAndreas Gohr
2793379af09SAndreas Gohr            // cluster them using kmeans
2803379af09SAndreas Gohr            $space = new Space($dimensions);
2813379af09SAndreas Gohr            foreach ($result as $record) {
2823379af09SAndreas Gohr                $space->addPoint(json_decode($record['embedding'], true));
2833379af09SAndreas Gohr            }
2843379af09SAndreas Gohr            $clusters = $space->solve($clustercount, function ($space, $clusters) {
2853379af09SAndreas Gohr                static $iterations = 0;
2863379af09SAndreas Gohr                ++$iterations;
2873379af09SAndreas Gohr                if ($this->logger) {
288*7ebc7895Ssplitbrain                    $clustercounts = implode(',', array_map('count', $clusters));
2893379af09SAndreas Gohr                    $this->logger->info('Iteration {iteration}: [{clusters}]', [
2903379af09SAndreas Gohr                        'iteration' => $iterations, 'clusters' => $clustercounts
2913379af09SAndreas Gohr                    ]);
2923379af09SAndreas Gohr                }
2933379af09SAndreas Gohr            }, Cluster::INIT_KMEANS_PLUS_PLUS);
2943379af09SAndreas Gohr
2953379af09SAndreas Gohr            // store the clusters
296*7ebc7895Ssplitbrain            foreach ($clusters as $cluster) {
2973379af09SAndreas Gohr                /** @var Cluster $cluster */
2983379af09SAndreas Gohr                $centroid = $cluster->getCoordinates();
299e33a1d7aSAndreas Gohr                $query = 'INSERT INTO clusters (lang, centroid) VALUES (?, ?)';
300e33a1d7aSAndreas Gohr                $this->db->exec($query, [$lang, json_encode($centroid)]);
3013379af09SAndreas Gohr            }
3023379af09SAndreas Gohr
3033379af09SAndreas Gohr            $this->db->getPdo()->commit();
3043379af09SAndreas Gohr            if ($this->logger) $this->logger->success('Created {clusters} clusters', ['clusters' => count($clusters)]);
3053379af09SAndreas Gohr        } catch (\Exception $e) {
3063379af09SAndreas Gohr            $this->db->getPdo()->rollBack();
307e33a1d7aSAndreas Gohr            throw new \RuntimeException('Clustering failed: ' . $e->getMessage(), 0, $e);
3083379af09SAndreas Gohr        }
3093379af09SAndreas Gohr    }
3103379af09SAndreas Gohr
3113379af09SAndreas Gohr    /**
3123379af09SAndreas Gohr     * Assign the nearest cluster for all chunks that don't have one
3133379af09SAndreas Gohr     *
3143379af09SAndreas Gohr     * @return void
3153379af09SAndreas Gohr     */
3163379af09SAndreas Gohr    protected function setChunkClusters()
3173379af09SAndreas Gohr    {
3183379af09SAndreas Gohr        if ($this->logger) $this->logger->info('Assigning clusters to chunks...');
319e33a1d7aSAndreas Gohr        $query = 'SELECT id, embedding, lang FROM embeddings WHERE cluster IS NULL';
3203379af09SAndreas Gohr        $handle = $this->db->query($query);
3213379af09SAndreas Gohr
3223379af09SAndreas Gohr        while ($record = $handle->fetch(\PDO::FETCH_ASSOC)) {
3233379af09SAndreas Gohr            $vector = json_decode($record['embedding'], true);
324e33a1d7aSAndreas Gohr            $cluster = $this->getCluster($vector, $this->useLanguageClusters ? $record['lang'] : '');
3253379af09SAndreas Gohr            $query = 'UPDATE embeddings SET cluster = ? WHERE id = ?';
3263379af09SAndreas Gohr            $this->db->exec($query, [$cluster, $record['id']]);
3273379af09SAndreas Gohr            if ($this->logger) $this->logger->success(
328*7ebc7895Ssplitbrain                'Chunk {id} assigned to cluster {cluster}',
329*7ebc7895Ssplitbrain                ['id' => $record['id'], 'cluster' => $cluster]
3303379af09SAndreas Gohr            );
3313379af09SAndreas Gohr        }
3323379af09SAndreas Gohr        $handle->closeCursor();
3333379af09SAndreas Gohr    }
3343379af09SAndreas Gohr
3353379af09SAndreas Gohr    /**
3363379af09SAndreas Gohr     * Get the nearest cluster for the given vector
3373379af09SAndreas Gohr     *
3383379af09SAndreas Gohr     * @param float[] $vector
3393379af09SAndreas Gohr     * @return int|null
3403379af09SAndreas Gohr     */
341e33a1d7aSAndreas Gohr    protected function getCluster($vector, $lang)
3423379af09SAndreas Gohr    {
343e33a1d7aSAndreas Gohr        if ($lang != '') {
344e33a1d7aSAndreas Gohr            $where = 'WHERE lang = ' . $this->db->getPdo()->quote($lang);
345e33a1d7aSAndreas Gohr        } else {
346e33a1d7aSAndreas Gohr            $where = '';
347e33a1d7aSAndreas Gohr        }
348e33a1d7aSAndreas Gohr
349e33a1d7aSAndreas Gohr        $query = "SELECT cluster, centroid
350e33a1d7aSAndreas Gohr                    FROM clusters
351e33a1d7aSAndreas Gohr                   $where
352e33a1d7aSAndreas Gohr                ORDER BY COSIM(centroid, ?) DESC
353e33a1d7aSAndreas Gohr                   LIMIT 1";
354e33a1d7aSAndreas Gohr
3553379af09SAndreas Gohr        $result = $this->db->queryRecord($query, [json_encode($vector)]);
3563379af09SAndreas Gohr        if (!$result) return null;
3573379af09SAndreas Gohr        return $result['cluster'];
3583379af09SAndreas Gohr    }
3593379af09SAndreas Gohr
3603379af09SAndreas Gohr    /**
3613379af09SAndreas Gohr     * Check if clustering has been done before
3623379af09SAndreas Gohr     * @return bool
3633379af09SAndreas Gohr     */
3643379af09SAndreas Gohr    protected function hasClusters()
3653379af09SAndreas Gohr    {
3663379af09SAndreas Gohr        $query = 'SELECT COUNT(*) FROM clusters';
3673379af09SAndreas Gohr        return $this->db->queryValue($query) > 0;
3683379af09SAndreas Gohr    }
3698c8b7ba6SAndreas Gohr
3708c8b7ba6SAndreas Gohr    /**
3718c8b7ba6SAndreas Gohr     * Writes TSV files for visualizing with http://projector.tensorflow.org/
3728c8b7ba6SAndreas Gohr     *
3738c8b7ba6SAndreas Gohr     * @param string $vectorfile path to the file with the vectors
3748c8b7ba6SAndreas Gohr     * @param string $metafile path to the file with the metadata
3758c8b7ba6SAndreas Gohr     * @return void
3768c8b7ba6SAndreas Gohr     */
3778c8b7ba6SAndreas Gohr    public function dumpTSV($vectorfile, $metafile)
3788c8b7ba6SAndreas Gohr    {
3798c8b7ba6SAndreas Gohr        $query = 'SELECT * FROM embeddings';
3808c8b7ba6SAndreas Gohr        $handle = $this->db->query($query);
3818c8b7ba6SAndreas Gohr
3828c8b7ba6SAndreas Gohr        $header = implode("\t", ['id', 'page', 'created']);
3838c8b7ba6SAndreas Gohr        file_put_contents($metafile, $header . "\n", FILE_APPEND);
3848c8b7ba6SAndreas Gohr
3858c8b7ba6SAndreas Gohr        while ($row = $handle->fetch(\PDO::FETCH_ASSOC)) {
3868c8b7ba6SAndreas Gohr            $vector = json_decode($row['embedding'], true);
3878c8b7ba6SAndreas Gohr            $vector = implode("\t", $vector);
3888c8b7ba6SAndreas Gohr
3898c8b7ba6SAndreas Gohr            $meta = implode("\t", [$row['id'], $row['page'], $row['created']]);
3908c8b7ba6SAndreas Gohr
3918c8b7ba6SAndreas Gohr            file_put_contents($vectorfile, $vector . "\n", FILE_APPEND);
3928c8b7ba6SAndreas Gohr            file_put_contents($metafile, $meta . "\n", FILE_APPEND);
3938c8b7ba6SAndreas Gohr        }
3948c8b7ba6SAndreas Gohr    }
395f6ef2e50SAndreas Gohr}
396