| 1 | use ndarray::{Array1, Array2}; |
| 2 | use rusqlite::Connection; |
| 3 | use std::fs; |
| 4 | |
| 5 | fn get_top_n(v: Vec<f32>, vectors: Vec<Vec<f32>>, d: usize, top_n: usize) -> Vec<usize> { |
| 6 | let n = vectors.len(); |
| 7 | let a: Array2<f32> = Array2::from_shape_fn((n, d), |(i, j)| vectors[i][j]); |
| 8 | let b: Array1<f32> = Array1::from_shape_fn(d, |i| v[i]); |
| 9 | |
| 10 | let result = a.dot(&b); |
| 11 | let mut indexed_result: Vec<(usize, &f32)> = result.iter().enumerate().collect(); |
| 12 | indexed_result.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap()); |
| 13 | |
| 14 | let top_n_indices: Vec<usize> = indexed_result |
| 15 | .into_iter() |
| 16 | .map(|(index, _value)| index) |
| 17 | .take(top_n) |
| 18 | .collect(); |
| 19 | |
| 20 | return top_n_indices; |
| 21 | } |
| 22 | |
| 23 | #[derive(Debug, Clone)] |
| 24 | pub struct Chunk { |
| 25 | pub hash: String, |
| 26 | pub content: String, |
| 27 | pub embedding: Vec<f32>, |
| 28 | pub start_line: usize, |
| 29 | pub end_line: usize, |
| 30 | pub file_path: String, |
| 31 | pub index: usize, |
| 32 | } |
| 33 | |
| 34 | pub fn embedding_to_text(embedding: Vec<f32>) -> String { |
| 35 | return embedding |
| 36 | .iter() |
| 37 | .map(|f| f.to_string()) |
| 38 | .collect::<Vec<String>>() |
| 39 | .join(","); |
| 40 | } |
| 41 | |
| 42 | pub fn text_to_embedding(text: String) -> Result<Vec<f32>, &'static str> { |
| 43 | let mut embedding = Vec::new(); |
| 44 | for s in text.split(',') { |
| 45 | match s.parse::<f32>() { |
| 46 | Ok(value) => embedding.push(value), |
| 47 | Err(_) => { |
| 48 | println!("Failed to parse embedding from text: {}", text); |
| 49 | return Err("Failed to parse embedding from text"); |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | Ok(embedding) |
| 55 | } |
| 56 | |
| 57 | fn get_conn() -> Connection { |
| 58 | let path = dirs::home_dir() |
| 59 | .unwrap() |
| 60 | .join(".continue") |
| 61 | .join("index") |
| 62 | .join("sync.db"); |
| 63 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 64 | return Connection::open(path).unwrap(); |
| 65 | } |
| 66 | |
| 67 | pub fn create_database() { |
| 68 | let conn = get_conn(); |
| 69 | |
| 70 | conn.execute( |
| 71 | "CREATE TABLE IF NOT EXISTS chunks ( |
| 72 | id INTEGER PRIMARY KEY, |
| 73 | hash TEXT NOT NULL, |
| 74 | content TEXT NOT NULL, |
| 75 | embedding TEXT NOT NULL, |
| 76 | start_line INTEGER NOT NULL, |
| 77 | end_line INTEGER NOT NULL, |
| 78 | file_path TEXT NOT NULL, |
| 79 | idx INTEGER NOT NULL |
| 80 | )", |
| 81 | (), |
| 82 | ) |
| 83 | .unwrap(); |
| 84 | |
| 85 | conn.execute( |
| 86 | "CREATE TABLE IF NOT EXISTS tags ( |
| 87 | id INTEGER PRIMARY KEY, |
| 88 | chunk_hash TEXT NOT NULL, |
| 89 | tag TEXT NOT NULL |
| 90 | )", |
| 91 | (), |
| 92 | ) |
| 93 | .unwrap(); |
| 94 | } |
| 95 | |
| 96 | pub fn add_chunk(chunk: Chunk, tags: Vec<String>) { |
| 97 | let conn = get_conn(); |
| 98 | |
| 99 | conn.execute( |
| 100 | "INSERT INTO chunks (hash, content, embedding, start_line, end_line, file_path, idx) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", |
| 101 | (&chunk.hash, &chunk.content, &embedding_to_text(chunk.embedding), chunk.start_line, chunk.end_line, &chunk.file_path, chunk.index), |
| 102 | ) |
| 103 | .unwrap(); |
| 104 | |
| 105 | for tag in tags { |
| 106 | conn.execute( |
| 107 | "INSERT INTO tags (chunk_hash, tag) VALUES (?1, ?2)", |
| 108 | (&chunk.hash, &tag), |
| 109 | ) |
| 110 | .unwrap(); |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | pub fn remove_chunks_for_hash(hash: String) { |
| 115 | let conn = get_conn(); |
| 116 | |
| 117 | conn.execute("DELETE FROM chunks WHERE hash=?1", (&hash,)) |
| 118 | .unwrap(); |
| 119 | |
| 120 | conn.execute("DELETE FROM tags WHERE chunk_hash=?1", (&hash,)) |
| 121 | .unwrap(); |
| 122 | } |
| 123 | |
| 124 | pub fn add_tag(hash: String, tag: String) { |
| 125 | let conn = get_conn(); |
| 126 | |
| 127 | conn.execute( |
| 128 | "INSERT INTO tags (chunk_hash, tag) VALUES (?1, ?2)", |
| 129 | (&hash, &tag), |
| 130 | ) |
| 131 | .unwrap(); |
| 132 | } |
| 133 | |
| 134 | pub fn remove_tag(hash: String, tag: String) { |
| 135 | let conn = get_conn(); |
| 136 | |
| 137 | conn.execute( |
| 138 | "DELETE FROM tags WHERE chunk_hash=?1 AND tag=?2", |
| 139 | (&hash, &tag), |
| 140 | ) |
| 141 | .unwrap(); |
| 142 | } |
| 143 | |
| 144 | pub fn retrieve(n: usize, tags: Vec<String>, v: Vec<f32>) -> Vec<Chunk> { |
| 145 | let conn = get_conn(); |
| 146 | |
| 147 | let mut stmt = conn |
| 148 | .prepare(&format!( |
| 149 | " |
| 150 | SELECT * FROM chunks |
| 151 | WHERE hash IN ( |
| 152 | SELECT chunk_hash |
| 153 | FROM tags |
| 154 | WHERE tag IN (?1) |
| 155 | )", |
| 156 | )) |
| 157 | .unwrap(); |
| 158 | let chunk_rows = stmt |
| 159 | .query_map((tags.join(", "),), |row| { |
| 160 | Ok(Chunk { |
| 161 | hash: row.get(1)?, |
| 162 | content: row.get(2)?, |
| 163 | embedding: text_to_embedding(row.get(3)?).unwrap(), |
| 164 | start_line: row.get(4)?, |
| 165 | end_line: row.get(5)?, |
| 166 | file_path: row.get(6)?, |
| 167 | index: row.get(7)?, |
| 168 | }) |
| 169 | }) |
| 170 | .unwrap(); |
| 171 | |
| 172 | let mut chunks = Vec::new(); |
| 173 | let mut vectors: Vec<Vec<f32>> = Vec::new(); |
| 174 | for chunk in chunk_rows { |
| 175 | let chunk = chunk.unwrap(); |
| 176 | chunks.push(chunk.clone()); |
| 177 | let vector = chunk.embedding; |
| 178 | vectors.push(vector); |
| 179 | } |
| 180 | |
| 181 | let top_n_indices = get_top_n(v, vectors, 384, n); |
| 182 | return chunks |
| 183 | .iter() |
| 184 | .cloned() |
| 185 | .enumerate() |
| 186 | .filter(|(index, _chunk)| top_n_indices.contains(index)) |
| 187 | .map(|(_index, chunk)| chunk) |
| 188 | .collect::<Vec<Chunk>>(); |
| 189 | } |
| 190 | |
| 191 | #[cfg(test)] |
| 192 | mod tests { |
| 193 | use super::*; |
| 194 | use ndarray::{Array1, Array2}; |
| 195 | use rand::Rng; |
| 196 | use rusqlite::Connection; |
| 197 | use std::time::Instant; |
| 198 | |
| 199 | fn rand_embedding(n: i32) -> Vec<f32> { |
| 200 | let mut rng = rand::thread_rng(); |
| 201 | (0..n).map(|_| rng.gen()).collect() |
| 202 | } |
| 203 | |
| 204 | #[test] |
| 205 | fn test_create_database() { |
| 206 | create_database(); |
| 207 | |
| 208 | let conn = get_conn(); |
| 209 | let mut stmt = conn |
| 210 | .prepare("SELECT name FROM sqlite_master WHERE type='table'") |
| 211 | .unwrap(); |
| 212 | let mut table_names = stmt |
| 213 | .query_map([], |row| row.get::<usize, String>(0)) |
| 214 | .unwrap(); |
| 215 | |
| 216 | assert!(table_names.any(|table_name| table_name.unwrap().eq("chunks"))); |
| 217 | assert!(table_names.any(|table_name| table_name.unwrap().eq("tags"))) |
| 218 | } |
| 219 | |
| 220 | #[test] |
| 221 | fn benchmark_load_vectors() { |
| 222 | let conn = Connection::open("sync.db").unwrap(); |
| 223 | |
| 224 | conn.execute( |
| 225 | "CREATE TABLE chunks ( |
| 226 | id INTEGER PRIMARY KEY, |
| 227 | content TEXT NOT NULL, |
| 228 | embedding TEXT NOT NULL |
| 229 | )", |
| 230 | (), // empty list of parameters. |
| 231 | ) |
| 232 | .unwrap(); |
| 233 | |
| 234 | let time = Instant::now(); |
| 235 | |
| 236 | for _ in 0..10_000 { |
| 237 | let chunk = Chunk { |
| 238 | hash: "test".to_string(), |
| 239 | content: "Test content".to_string(), |
| 240 | embedding: rand_embedding(384), |
| 241 | start_line: 0, |
| 242 | end_line: 0, |
| 243 | file_path: "test".to_string(), |
| 244 | index: 0, |
| 245 | }; |
| 246 | conn.execute( |
| 247 | "INSERT INTO chunks (content, embedding) VALUES (?1, ?2)", |
| 248 | (&chunk.content, &embedding_to_text(chunk.embedding)), |
| 249 | ) |
| 250 | .unwrap(); |
| 251 | } |
| 252 | |
| 253 | println!("To insert took: {:.2?}", time.elapsed()); |
| 254 | |
| 255 | let mut stmt = conn |
| 256 | .prepare("SELECT id, content, embedding FROM chunks") |
| 257 | .unwrap(); |
| 258 | |
| 259 | let chunk_iter = stmt |
| 260 | .query_map([], |row| { |
| 261 | Ok(Chunk { |
| 262 | hash: row.get(1)?, |
| 263 | content: row.get(2)?, |
| 264 | embedding: text_to_embedding(row.get(3)?).unwrap(), |
| 265 | start_line: row.get(4)?, |
| 266 | end_line: row.get(5)?, |
| 267 | file_path: row.get(6)?, |
| 268 | index: row.get(7)?, |
| 269 | }) |
| 270 | }) |
| 271 | .unwrap(); |
| 272 | |
| 273 | println!("To load took: {:.2?}", time.elapsed()); |
| 274 | |
| 275 | let mut i = 0; |
| 276 | for chunk in chunk_iter { |
| 277 | i += 1; |
| 278 | let _ = chunk.unwrap().embedding; |
| 279 | } |
| 280 | |
| 281 | println!("Found {} chunks", i); |
| 282 | println!("To convert took: {:.2?}", time.elapsed()); |
| 283 | } |
| 284 | |
| 285 | #[test] |
| 286 | fn benchmark_ndarray() { |
| 287 | let mut rng = rand::thread_rng(); |
| 288 | let n = 10_000; |
| 289 | let d = 384; |
| 290 | let a: Array2<f32> = Array2::from_shape_fn((n, d), |_| rng.gen::<f32>()); |
| 291 | let b: Array1<f32> = Array1::from_shape_fn(d, |_| rng.gen::<f32>()); |
| 292 | |
| 293 | let time = Instant::now(); |
| 294 | |
| 295 | let result = a.dot(&b); |
| 296 | let mut indexed_result: Vec<(usize, &f32)> = result.iter().enumerate().collect(); |
| 297 | indexed_result.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap()); |
| 298 | |
| 299 | let top_n = 50; |
| 300 | let _: Vec<usize> = indexed_result |
| 301 | .into_iter() |
| 302 | .map(|(index, _value)| index) |
| 303 | .take(top_n) |
| 304 | .collect(); |
| 305 | |
| 306 | let elapsed = time.elapsed(); |
| 307 | println!("Elapsed time: {:.2?}", elapsed); |
| 308 | } |
| 309 | } |