File size: 10,184 Bytes
b34efa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
"""
Document processor module for Norwegian RAG chatbot.
Orchestrates the document processing pipeline with remote embeddings.
"""

import os
import json
import numpy as np
from typing import List, Dict, Any, Optional, Tuple, Union
from datetime import datetime

from .extractor import TextExtractor
from .chunker import TextChunker
from ..api.huggingface_api import HuggingFaceAPI
from ..api.config import CHUNK_SIZE, CHUNK_OVERLAP

class DocumentProcessor:
    """
    Orchestrates the document processing pipeline:
    1. Extract text from documents
    2. Split text into chunks
    3. Generate embeddings using remote API
    4. Store processed documents and embeddings
    """
    
    def __init__(
        self,
        api_client: Optional[HuggingFaceAPI] = None,
        documents_dir: str = "/home/ubuntu/chatbot_project/data/documents",
        processed_dir: str = "/home/ubuntu/chatbot_project/data/processed",
        chunk_size: int = CHUNK_SIZE,
        chunk_overlap: int = CHUNK_OVERLAP,
        chunking_strategy: str = "paragraph"
    ):
        """
        Initialize the document processor.
        
        Args:
            api_client: HuggingFaceAPI client for generating embeddings
            documents_dir: Directory for storing original documents
            processed_dir: Directory for storing processed documents and embeddings
            chunk_size: Maximum size of each chunk
            chunk_overlap: Overlap between consecutive chunks
            chunking_strategy: Strategy for chunking text ('fixed', 'paragraph', or 'sentence')
        """
        self.api_client = api_client or HuggingFaceAPI()
        self.documents_dir = documents_dir
        self.processed_dir = processed_dir
        self.chunk_size = chunk_size
        self.chunk_overlap = chunk_overlap
        self.chunking_strategy = chunking_strategy
        
        # Ensure directories exist
        os.makedirs(self.documents_dir, exist_ok=True)
        os.makedirs(self.processed_dir, exist_ok=True)
        
        # Initialize document index
        self.document_index_path = os.path.join(self.processed_dir, "document_index.json")
        self.document_index = self._load_document_index()
    
    def process_document(
        self,
        file_path: str,
        document_id: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None
    ) -> str:
        """
        Process a document through the entire pipeline.
        
        Args:
            file_path: Path to the document file
            document_id: Optional custom document ID
            metadata: Optional metadata for the document
            
        Returns:
            Document ID
        """
        # Generate document ID if not provided
        if document_id is None:
            document_id = f"doc_{datetime.now().strftime('%Y%m%d%H%M%S')}_{os.path.basename(file_path)}"
        
        # Extract text from document
        text = TextExtractor.extract_from_file(file_path)
        if not text:
            raise ValueError(f"Failed to extract text from {file_path}")
        
        # Split text into chunks
        chunks = TextChunker.chunk_text(
            text,
            chunk_size=self.chunk_size,
            chunk_overlap=self.chunk_overlap,
            strategy=self.chunking_strategy
        )
        
        # Clean chunks
        chunks = [TextChunker.clean_chunk(chunk) for chunk in chunks]
        
        # Generate embeddings using remote API
        embeddings = self.api_client.generate_embeddings(chunks)
        
        # Prepare metadata
        if metadata is None:
            metadata = {}
        
        metadata.update({
            "filename": os.path.basename(file_path),
            "processed_date": datetime.now().isoformat(),
            "chunk_count": len(chunks),
            "chunking_strategy": self.chunking_strategy,
            "embedding_model": self.api_client.embedding_model_id
        })
        
        # Save processed document
        self._save_processed_document(document_id, chunks, embeddings, metadata)
        
        # Update document index
        self._update_document_index(document_id, metadata)
        
        return document_id
    
    def process_text(
        self,
        text: str,
        document_id: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None
    ) -> str:
        """
        Process text directly through the pipeline.
        
        Args:
            text: Text content to process
            document_id: Optional custom document ID
            metadata: Optional metadata for the document
            
        Returns:
            Document ID
        """
        # Generate document ID if not provided
        if document_id is None:
            document_id = f"text_{datetime.now().strftime('%Y%m%d%H%M%S')}"
        
        # Split text into chunks
        chunks = TextChunker.chunk_text(
            text,
            chunk_size=self.chunk_size,
            chunk_overlap=self.chunk_overlap,
            strategy=self.chunking_strategy
        )
        
        # Clean chunks
        chunks = [TextChunker.clean_chunk(chunk) for chunk in chunks]
        
        # Generate embeddings using remote API
        embeddings = self.api_client.generate_embeddings(chunks)
        
        # Prepare metadata
        if metadata is None:
            metadata = {}
        
        metadata.update({
            "source": "direct_text",
            "processed_date": datetime.now().isoformat(),
            "chunk_count": len(chunks),
            "chunking_strategy": self.chunking_strategy,
            "embedding_model": self.api_client.embedding_model_id
        })
        
        # Save processed document
        self._save_processed_document(document_id, chunks, embeddings, metadata)
        
        # Update document index
        self._update_document_index(document_id, metadata)
        
        return document_id
    
    def get_document_chunks(self, document_id: str) -> List[str]:
        """
        Get all chunks for a document.
        
        Args:
            document_id: Document ID
            
        Returns:
            List of text chunks
        """
        document_path = os.path.join(self.processed_dir, f"{document_id}.json")
        if not os.path.exists(document_path):
            raise FileNotFoundError(f"Document not found: {document_id}")
        
        with open(document_path, 'r', encoding='utf-8') as f:
            document_data = json.load(f)
        
        return document_data.get("chunks", [])
    
    def get_document_embeddings(self, document_id: str) -> List[List[float]]:
        """
        Get all embeddings for a document.
        
        Args:
            document_id: Document ID
            
        Returns:
            List of embedding vectors
        """
        document_path = os.path.join(self.processed_dir, f"{document_id}.json")
        if not os.path.exists(document_path):
            raise FileNotFoundError(f"Document not found: {document_id}")
        
        with open(document_path, 'r', encoding='utf-8') as f:
            document_data = json.load(f)
        
        return document_data.get("embeddings", [])
    
    def get_all_documents(self) -> Dict[str, Dict[str, Any]]:
        """
        Get all documents in the index.
        
        Returns:
            Dictionary of document IDs to metadata
        """
        return self.document_index
    
    def delete_document(self, document_id: str) -> bool:
        """
        Delete a document and its processed data.
        
        Args:
            document_id: Document ID
            
        Returns:
            True if successful, False otherwise
        """
        if document_id not in self.document_index:
            return False
        
        # Remove from index
        del self.document_index[document_id]
        self._save_document_index()
        
        # Delete processed file
        document_path = os.path.join(self.processed_dir, f"{document_id}.json")
        if os.path.exists(document_path):
            os.remove(document_path)
        
        return True
    
    def _save_processed_document(
        self,
        document_id: str,
        chunks: List[str],
        embeddings: List[List[float]],
        metadata: Dict[str, Any]
    ) -> None:
        """
        Save processed document data.
        
        Args:
            document_id: Document ID
            chunks: List of text chunks
            embeddings: List of embedding vectors
            metadata: Document metadata
        """
        document_data = {
            "document_id": document_id,
            "metadata": metadata,
            "chunks": chunks,
            "embeddings": embeddings
        }
        
        document_path = os.path.join(self.processed_dir, f"{document_id}.json")
        with open(document_path, 'w', encoding='utf-8') as f:
            json.dump(document_data, f, ensure_ascii=False, indent=2)
    
    def _load_document_index(self) -> Dict[str, Dict[str, Any]]:
        """
        Load the document index from disk.
        
        Returns:
            Dictionary of document IDs to metadata
        """
        if os.path.exists(self.document_index_path):
            try:
                with open(self.document_index_path, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception as e:
                print(f"Error loading document index: {str(e)}")
        
        return {}
    
    def _save_document_index(self) -> None:
        """
        Save the document index to disk.
        """
        with open(self.document_index_path, 'w', encoding='utf-8') as f:
            json.dump(self.document_index, f, ensure_ascii=False, indent=2)
    
    def _update_document_index(self, document_id: str, metadata: Dict[str, Any]) -> None:
        """
        Update the document index with a new or updated document.
        
        Args:
            document_id: Document ID
            metadata: Document metadata
        """
        self.document_index[document_id] = metadata
        self._save_document_index()