|
| 1 | +"""ChromaDB integration for podcast transcription search and RAG.""" |
| 2 | + |
| 3 | +from pathlib import Path |
| 4 | +from typing import Any, cast |
| 5 | + |
| 6 | +import chromadb |
| 7 | +from chromadb.config import Settings |
| 8 | +from loguru import logger |
| 9 | + |
| 10 | +from retrocast.datastore import Datastore |
| 11 | + |
| 12 | + |
| 13 | +class ChromaDBManager: |
| 14 | + """Manages ChromaDB collections for transcription segment indexing.""" |
| 15 | + |
| 16 | + def __init__(self, persist_directory: Path): |
| 17 | + """Initialize ChromaDB client with persistent storage. |
| 18 | +
|
| 19 | + Args: |
| 20 | + persist_directory: Directory path for ChromaDB persistence |
| 21 | + """ |
| 22 | + self.persist_directory = persist_directory |
| 23 | + self.persist_directory.mkdir(parents=True, exist_ok=True) |
| 24 | + |
| 25 | + logger.debug(f"Initializing ChromaDB at {persist_directory}") |
| 26 | + self.client = chromadb.PersistentClient( |
| 27 | + path=str(persist_directory), |
| 28 | + settings=Settings( |
| 29 | + anonymized_telemetry=False, |
| 30 | + allow_reset=True, |
| 31 | + ), |
| 32 | + ) |
| 33 | + self.collection_name = "transcription_segments" |
| 34 | + self.collection = self.client.get_or_create_collection( |
| 35 | + name=self.collection_name, |
| 36 | + metadata={"description": "Podcast transcription segments with timestamps"}, |
| 37 | + ) |
| 38 | + |
| 39 | + def index_transcriptions(self, datastore: Datastore, batch_size: int = 100) -> int: |
| 40 | + """Index all transcription segments from the database into ChromaDB. |
| 41 | +
|
| 42 | + Args: |
| 43 | + datastore: Datastore instance for querying transcription data |
| 44 | + batch_size: Number of segments to process per batch |
| 45 | +
|
| 46 | + Returns: |
| 47 | + Number of segments indexed |
| 48 | + """ |
| 49 | + logger.info("Starting transcription indexing...") |
| 50 | + |
| 51 | + # Query all transcription segments with metadata |
| 52 | + query = """ |
| 53 | + SELECT |
| 54 | + ts.transcription_id, |
| 55 | + ts.segment_index, |
| 56 | + ts.start_time, |
| 57 | + ts.end_time, |
| 58 | + ts.text, |
| 59 | + ts.speaker, |
| 60 | + t.podcast_title, |
| 61 | + t.episode_title, |
| 62 | + t.episode_url, |
| 63 | + t.media_path, |
| 64 | + t.language, |
| 65 | + t.backend, |
| 66 | + t.model_size |
| 67 | + FROM transcription_segments ts |
| 68 | + JOIN transcriptions t ON ts.transcription_id = t.transcription_id |
| 69 | + ORDER BY ts.transcription_id, ts.segment_index |
| 70 | + """ |
| 71 | + |
| 72 | + segments = list(datastore.db.execute(query).fetchall()) |
| 73 | + total_segments = len(segments) |
| 74 | + |
| 75 | + if total_segments == 0: |
| 76 | + logger.warning("No transcription segments found in database") |
| 77 | + return 0 |
| 78 | + |
| 79 | + logger.info(f"Found {total_segments} segments to index") |
| 80 | + |
| 81 | + # Process in batches |
| 82 | + indexed_count = 0 |
| 83 | + for i in range(0, total_segments, batch_size): |
| 84 | + batch = segments[i : i + batch_size] |
| 85 | + documents = [] |
| 86 | + metadatas = [] |
| 87 | + ids = [] |
| 88 | + |
| 89 | + for segment in batch: |
| 90 | + # Create unique ID for each segment |
| 91 | + segment_id = f"t{segment[0]}_s{segment[1]}" |
| 92 | + ids.append(segment_id) |
| 93 | + |
| 94 | + # The text to be embedded and searched |
| 95 | + documents.append(segment[4]) # text column |
| 96 | + |
| 97 | + # Metadata for context and filtering |
| 98 | + metadatas.append( |
| 99 | + { |
| 100 | + "transcription_id": str(segment[0]), |
| 101 | + "segment_index": str(segment[1]), |
| 102 | + "start_time": float(segment[2]), |
| 103 | + "end_time": float(segment[3]), |
| 104 | + "speaker": str(segment[5] or ""), |
| 105 | + "podcast_title": str(segment[6] or ""), |
| 106 | + "episode_title": str(segment[7] or ""), |
| 107 | + "episode_url": str(segment[8] or ""), |
| 108 | + "media_path": str(segment[9] or ""), |
| 109 | + "language": str(segment[10] or ""), |
| 110 | + "backend": str(segment[11] or ""), |
| 111 | + "model_size": str(segment[12] or ""), |
| 112 | + } |
| 113 | + ) |
| 114 | + |
| 115 | + # Add batch to collection |
| 116 | + self.collection.add(documents=documents, metadatas=cast(Any, metadatas), ids=ids) |
| 117 | + indexed_count += len(batch) |
| 118 | + |
| 119 | + logger.debug(f"Indexed {indexed_count}/{total_segments} segments") |
| 120 | + |
| 121 | + logger.info(f"Successfully indexed {indexed_count} segments") |
| 122 | + return indexed_count |
| 123 | + |
| 124 | + def search( |
| 125 | + self, query: str, n_results: int = 5, podcast_filter: str | None = None |
| 126 | + ) -> list[dict[str, Any]]: |
| 127 | + """Search transcription segments using semantic similarity. |
| 128 | +
|
| 129 | + Args: |
| 130 | + query: The search query text |
| 131 | + n_results: Maximum number of results to return |
| 132 | + podcast_filter: Optional podcast title to filter results |
| 133 | +
|
| 134 | + Returns: |
| 135 | + List of matching segments with metadata |
| 136 | + """ |
| 137 | + where_filter: Any = None |
| 138 | + if podcast_filter: |
| 139 | + where_filter = {"podcast_title": {"$eq": podcast_filter}} |
| 140 | + |
| 141 | + results = self.collection.query( |
| 142 | + query_texts=[query], n_results=n_results, where=where_filter |
| 143 | + ) |
| 144 | + |
| 145 | + # Format results for easier consumption |
| 146 | + formatted_results = [] |
| 147 | + if results["documents"] and results["documents"][0]: |
| 148 | + for i, doc in enumerate(results["documents"][0]): |
| 149 | + metadata = results["metadatas"][0][i] if results["metadatas"] else {} |
| 150 | + distance = results["distances"][0][i] if results["distances"] else None |
| 151 | + |
| 152 | + formatted_results.append( |
| 153 | + { |
| 154 | + "text": doc, |
| 155 | + "metadata": metadata, |
| 156 | + "distance": distance, |
| 157 | + "id": results["ids"][0][i] if results["ids"] else None, |
| 158 | + } |
| 159 | + ) |
| 160 | + |
| 161 | + return formatted_results |
| 162 | + |
| 163 | + def get_collection_count(self) -> int: |
| 164 | + """Get the number of segments in the collection. |
| 165 | +
|
| 166 | + Returns: |
| 167 | + Number of indexed segments |
| 168 | + """ |
| 169 | + return self.collection.count() |
| 170 | + |
| 171 | + def reset(self) -> None: |
| 172 | + """Clear all data from the collection.""" |
| 173 | + logger.warning(f"Resetting collection '{self.collection_name}'") |
| 174 | + self.client.delete_collection(name=self.collection_name) |
| 175 | + self.collection = self.client.get_or_create_collection( |
| 176 | + name=self.collection_name, |
| 177 | + metadata={"description": "Podcast transcription segments with timestamps"}, |
| 178 | + ) |
| 179 | + logger.info("Collection reset complete") |
0 commit comments