I'll help you create a Python script that implements similar code and markdown chunking functionality to store in a SQLite database, based on the Continue repository's approach. Here's a solution:
python
import sqlite3
import re
from dataclasses import dataclass
from typing import List, Tuple, Optional
import os
@[Redacted Person]
class Chunk:
filepath: str
content: str
start_line: int
end_line: int
digest: str # Cache key/hash of content
class CodebaseChunker:
def __init__(self, db_path: str, max_chunk_size: int = 512):
self.db_path = db_path
self.max_chunk_size = max_chunk_size
self.setup_database()
def setup_database(self):
"""Initialize SQLite database with required tables"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
# Create chunks table
c.execute('''
CREATE TABLE IF NOT EXISTS chunks (
id INTEGER PRIMARY KEY,
path TEXT NOT NULL,
content TEXT NOT NULL,
start_line INTEGER NOT NULL,
end_line INTEGER NOT NULL,
cache_key TEXT NOT NULL
)''')
# Create metadata table
c.execute('''
CREATE TABLE IF NOT EXISTS chunk_tags (
id INTEGER PRIMARY KEY,
chunk_id INTEGER NOT NULL,
tag TEXT NOT NULL,
FOREIGN KEY (chunk_id) REFERENCES chunks (id)
)''')
conn.commit()
conn.close()
def get_file_language(self, filepath: str) -> str:
"""Get markdown language tag for file based on extension"""
ext_to_lang = {
'py': 'python',
'js': 'javascript',
'jsx': 'jsx',
'tsx': 'tsx',
'ts': 'typescript',
'java': 'java',
'go': 'go',
'rb': 'ruby',
'rs': 'rust',
'c': 'c',
'cpp': 'cpp',
'cs': '[Redacted Person]',
'php': 'php',
'md': 'markdown',
'json': 'json',
'html': 'html',
'css': 'css',
'sh': 'shell',
'[Redacted Person]': '[Redacted Person]',
'sql': 'sql'
}
ext = filepath.split('.')[-1]
return ext_to_lang.get(ext, ext)
def chunk_code(self, content: str) -> List[Tuple[int, int, str]]:
"""Split code into chunks based on max size and logical boundaries"""
lines = content.split('\n')
chunks = []
current_chunk = []
current_chunk_size = 0
start_line = 0
for i, line in enumerate(lines):
line_size = len(line.split()) # Rough token count estimation
if current_chunk_size + line_size > self.max_chunk_size and current_chunk:
# Store chunk and start new one
chunk_content = '\n'.join(current_chunk)
chunks.append((start_line, i - 1, chunk_content))
current_chunk = [line]
current_chunk_size = line_size
start_line = i
else:
current_chunk.append(line)
current_chunk_size += line_size
# Add final chunk
if current_chunk:
chunks.append((start_line, len(lines) - 1, '\n'.join(current_chunk)))
return chunks
def chunk_markdown(self, content: str) -> List[Tuple[int, int, str]]:
"""Split markdown into chunks based on headers and max size"""
lines = content.split('\n')
chunks = []
current_chunk = []
current_chunk_size = 0
start_line = 0
for i, line in enumerate(lines):
# Start new chunk on headers
if re.match(r'^#{1,6}\s', line) and current_chunk:
chunk_content = '\n'.join(current_chunk)
chunks.append((start_line, i - 1, chunk_content))
current_chunk = [line]
current_chunk_size = len(line.split())
start_line = i
continue
line_size = len(line.split())
if current_chunk_size + line_size > self.max_chunk_size and current_chunk:
chunk_content = '\n'.join(current_chunk)
chunks.append((start_line, i - 1, chunk_content))
current_chunk = [line]
current_chunk_size = line_size
start_line = i
else:
current_chunk.append(line)
current_chunk_size += line_size
# Add final chunk
if current_chunk:
chunks.append((start_line, len(lines) - 1, '\n'.join(current_chunk)))
return chunks
def process_file(self, filepath: str, content: str, tag: str) -> List[Chunk]:
"""Process a single file into chunks"""
is_markdown = filepath.endswith('.md')
chunks = (
self.chunk_markdown(content) if is_markdown
else self.chunk_code(content)
)
return [
Chunk(
filepath=filepath,
content=chunk_content,
start_line=start,
end_line=end,
digest=f"{filepath}:{start}:{end}" # Simple cache key
)
for start, end, chunk_content in chunks
]
def store_chunks(self, chunks: List[Chunk], tag: str):
"""Store chunks in SQLite database"""
conn = sqlite3.connect(self.db_path)
c = conn.cursor()
for chunk in chunks:
# Insert chunk
c.execute('''
INSERT INTO chunks (path, content, start_line, end_line, cache_key)
VALUES (?, ?, ?, ?, ?)
''', (chunk.filepath, chunk.content, chunk.start_line, chunk.end_line, chunk.digest))
chunk_id = c.lastrowid
# Insert tag
c.execute('''
INSERT INTO chunk_tags (chunk_id, tag)
VALUES (?, ?)
''', (chunk_id, tag))
conn.commit()
conn.close()
def process_directory(self, directory: str, tag: str, exclude_patterns: Optional[List[str]] = None):
"""Process all files in a directory"""
if exclude_patterns is None:
exclude_patterns = [r'\.git', r'node_modules', r'__pycache__', r'\.env']
exclude_regex = '|'.join(exclude_patterns)
for root, _, files in os.walk(directory):
if re.search(exclude_regex, root):
continue
for file in files:
filepath = os.path.join(root, file)
# Skip excluded files
if re.search(exclude_regex, filepath):
continue
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
chunks = self.process_file(filepath, content, tag)
self.store_chunks(chunks, tag)
except Exception as e:
print(f"Error processing {filepath}: {e}")
def main():
# Example usage
chunker = CodebaseChunker('codebase.db')
# Process a directory
chunker.process_directory(
'./my_project',
'main', # Tag/branch name
exclude_patterns=[r'\.git', r'node_modules', r'dist']
)
if __name__ == "__main__":
main()
This script implements key features from Continue's codebase chunking system: