import sqlite3
import os
import re
from typing import List, Dict, Generator
# Database Initialization
def init_db(db_path="chunks.db"):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS chunks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filepath TEXT NOT NULL,
content TEXT NOT NULL,
start_line INTEGER NOT NULL,
end_line INTEGER NOT NULL,
chunk_type TEXT NOT NULL
)
""")
conn.commit()
return conn
# Markdown Chunking
def chunk_markdown(content: str, max_chunk_size: int = 500) -> Generator[Dict, None, None]:
lines = content.split("\n")
current_chunk = []
current_header = None
start_line = 0
for i, line in enumerate(lines):
if line.startswith("#"): # Markdown header
if current_chunk:
yield {
"content": "\n".join(current_chunk),
"start_line": start_line,
"end_line": i - 1,
"header": current_header or "No Header"
}
current_chunk = []
current_header = line.strip()
start_line = i
current_chunk.append(line)
# Split chunk if it exceeds max_chunk_size
if len("\n".join(current_chunk)) > max_chunk_size:
yield {
"content": "\n".join(current_chunk),
"start_line": start_line,
"end_line": i,
"header": current_header or "No Header"
}
current_chunk = []
start_line = i + 1
if current_chunk:
yield {
"content": "\n".join(current_chunk),
"start_line": start_line,
"end_line": len(lines) - 1,
"header": current_header or "No Header"
}
# Code Chunking
def chunk_code(content: str, max_chunk_size: int = 500) -> Generator[Dict, None, None]:
lines = content.split("\n")
current_chunk = []
start_line = 0
for i, line in enumerate(lines):
current_chunk.append(line)
# Split chunk if it exceeds max_chunk_size
if len("\n".join(current_chunk)) > max_chunk_size:
yield {
"content": "\n".join(current_chunk),
"start_line": start_line,
"end_line": i
}
current_chunk = []
start_line = i + 1
if current_chunk:
yield {
"content": "\n".join(current_chunk),
"start_line": start_line,
"end_line": len(lines) - 1
}
# File Chunking Logic
def process_file(filepath: str, max_chunk_size: int = 500) -> List[Dict]:
_, ext = os.path.splitext(filepath)
with open(filepath, "r", encoding="utf-8") as f:
content = f.read()
if ext in {".md", ".markdown"}: # Markdown files
return list(chunk_markdown(content, max_chunk_size))
elif ext in {".py", ".js", ".ts", ".java", ".cpp", ".c"}: # Code files
return list(chunk_code(content, max_chunk_size))
else:
print(f"Unsupported file type: {ext}")
return []
# Store Chunks in SQLite
def store_chunks(db_conn, filepath: str, chunks: List[Dict], chunk_type: str):
cursor = db_conn.cursor()
for chunk in chunks:
cursor.execute("""
INSERT INTO chunks (filepath, content, start_line, end_line, chunk_type)
VALUES (?, ?, ?, ?, ?)
""", (filepath, chunk["content"], chunk["start_line"], chunk["end_line"], chunk_type))
db_conn.commit()
# Walk Directory and Process Files
def walk_and_process(dir_path: str, db_conn, max_chunk_size: int = 500):
for root, _, files in os.walk(dir_path):
for file in files:
filepath = os.path.join(root, file)
chunks = process_file(filepath, max_chunk_size)
if chunks:
_, ext = os.path.splitext(filepath)
chunk_type = "markdown" if ext in {".md", ".markdown"} else "code"
store_chunks(db_conn, filepath, chunks, chunk_type)
# Main Function
if __name__ == "__main__":
db_conn = init_db()
directory_to_process = input("Enter the directory path to process: ").strip()
walk_and_process(directory_to_process, db_conn)
print("Processing complete. Chunks have been stored in chunks.db.")