File size: 14,079 Bytes
5b89d45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
"""Universal ingestor that handles multiple input types: ZIP files, GitHub URLs, local directories, etc."""

import logging
import os
import zipfile
import requests
import tempfile
import shutil
from abc import ABC, abstractmethod
from typing import Any, Dict, Generator, Tuple, Optional
from urllib.parse import urlparse
from pathlib import Path

from langchain_core.documents import Document

logger = logging.getLogger(__name__)


class DataManager(ABC):
    """Abstract base class for data managers."""
    
    def __init__(self, dataset_id: str):
        self.dataset_id = dataset_id
    
    @abstractmethod
    def download(self) -> bool:
        """Downloads/prepares the data."""
        pass
    
    @abstractmethod
    def walk(self, get_content: bool = True) -> Generator[Tuple[Any, Dict], None, None]:
        """Yields (content, metadata) tuples for each file."""
        pass


class UniversalIngestor(DataManager):
    """Factory class to ingest data from various sources."""
    
    def __init__(self, source: str, local_dir: Optional[str] = None, **kwargs):
        """
        Args:
            source: Can be:
                - GitHub URL (e.g., "https://github.com/owner/repo")
                - GitHub repo ID (e.g., "owner/repo")
                - Local directory path
                - ZIP file path
                - Web URL
            local_dir: Directory to store/clone/download data
            **kwargs: Additional arguments for specific managers
        """
        super().__init__(dataset_id=source)
        self.source = source
        self.kwargs = kwargs
        self.local_dir = local_dir or os.path.join(tempfile.gettempdir(), "code_chatbot")
        self.delegate = self._detect_handler()
    
    def _detect_handler(self) -> DataManager:
        """Detects the type of input and returns the appropriate handler."""
        source = self.source.strip()
        
        # Check if it's a URL
        if self._is_url(source):
            if "github.com" in source or source.count("/") == 1 and "/" in source:
                # GitHub URL or repo ID (owner/repo)
                if "github.com" in source:
                    # Extract repo_id from URL
                    parts = urlparse(source).path.strip("/").split("/")
                    if len(parts) >= 2:
                        repo_id = f"{parts[0]}/{parts[1]}"
                    else:
                        raise ValueError(f"Invalid GitHub URL: {source}")
                else:
                    # Assume it's owner/repo format
                    repo_id = source
                
                return GitHubRepoManager(
                    repo_id=repo_id,
                    local_dir=self.local_dir,
                    **self.kwargs
                )
            
            # Other web URLs
            return WebDocManager(source, local_dir=self.local_dir)
        
        # Check if it's a ZIP file
        if source.lower().endswith('.zip') and os.path.isfile(source):
            return ZIPFileManager(source, local_dir=self.local_dir)
        
        # Check if it's a local directory
        if os.path.isdir(source):
            return LocalDirectoryManager(source)
        
        # Check if it's a local file
        if os.path.isfile(source):
            return LocalFileManager(source)
        
        raise ValueError(f"Unable to determine source type for: {source}")
    
    def _is_url(self, s: str) -> bool:
        """Checks if a string is a URL."""
        try:
            result = urlparse(s)
            return bool(result.scheme and result.netloc)
        except Exception:
            # Check if it looks like owner/repo (GitHub format)
            if "/" in s and s.count("/") == 1 and not os.path.exists(s):
                return True
            return False
    
    @property
    def local_path(self) -> str:
        """Returns the local path where data is stored."""
        if hasattr(self.delegate, "local_path"):
            return self.delegate.local_path
        if hasattr(self.delegate, "path"):
            return self.delegate.path
        return self.local_dir
    
    def download(self) -> bool:
        """Downloads/prepares the data."""
        return self.delegate.download()
    
    def walk(self, get_content: bool = True) -> Generator[Tuple[Any, Dict], None, None]:
        """Yields (content, metadata) tuples."""
        yield from self.delegate.walk(get_content)


class ZIPFileManager(DataManager):
    """Handles ZIP file ingestion."""
    
    def __init__(self, zip_path: str, local_dir: str):
        super().__init__(dataset_id=zip_path)
        self.zip_path = zip_path
        self.local_dir = local_dir
        self.path = os.path.join(local_dir, "extracted", os.path.basename(zip_path).replace('.zip', ''))
    
    def download(self) -> bool:
        """Extracts the ZIP file."""
        if os.path.exists(self.path):
            logger.info(f"ZIP already extracted to {self.path}")
            return True
        
        os.makedirs(self.path, exist_ok=True)
        
        try:
            with zipfile.ZipFile(self.zip_path, 'r') as zip_ref:
                zip_ref.extractall(self.path)
            logger.info(f"Extracted {self.zip_path} to {self.path}")
            return True
        except Exception as e:
            logger.error(f"Failed to extract ZIP: {e}")
            return False
    
    def walk(self, get_content: bool = True) -> Generator[Tuple[Any, Dict], None, None]:
        """Walks extracted files."""
        if not os.path.exists(self.path):
            return
        
        IGNORE_DIRS = {'__pycache__', '.git', 'node_modules', 'venv', '.venv', '.env'}
        IGNORE_EXTENSIONS = {
            '.pyc', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.svg', '.mp4', '.mov', 
            '.zip', '.tar', '.gz', '.pdf', '.exe', '.bin', '.pkl', '.npy', '.pt', '.pth'
        }
        
        for root, dirs, files in os.walk(self.path):
            dirs[:] = [d for d in dirs if d not in IGNORE_DIRS and not d.startswith('.')]
            
            for file in files:
                if file.startswith('.'):
                    continue
                
                file_path = os.path.join(root, file)
                _, ext = os.path.splitext(file)
                if ext.lower() in IGNORE_EXTENSIONS:
                    continue
                
                rel_path = os.path.relpath(file_path, self.path)
                
                if get_content:
                    try:
                        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                            content = f.read()
                        yield content, {
                            "file_path": file_path,
                            "source": rel_path,
                            "file_name": file
                        }
                    except Exception as e:
                        logger.warning(f"Failed to read {file_path}: {e}")
                else:
                    yield {"file_path": file_path, "source": rel_path, "file_name": file}


class LocalDirectoryManager(DataManager):
    """Handles local directory ingestion."""
    
    def __init__(self, path: str):
        super().__init__(dataset_id=path)
        self.path = path
        self.local_dir = path
    
    def download(self) -> bool:
        return os.path.isdir(self.path)
    
    def walk(self, get_content: bool = True) -> Generator[Tuple[Any, Dict], None, None]:
        """Walks local directory."""
        IGNORE_DIRS = {'__pycache__', '.git', 'node_modules', 'venv', '.venv', '.env'}
        IGNORE_EXTENSIONS = {
            '.pyc', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.svg', '.mp4', '.mov', 
            '.zip', '.tar', '.gz', '.pdf', '.exe', '.bin', '.pkl', '.npy', '.pt', '.pth'
        }
        
        for root, dirs, files in os.walk(self.path):
            dirs[:] = [d for d in dirs if d not in IGNORE_DIRS and not d.startswith('.')]
            
            for file in files:
                if file.startswith('.'):
                    continue
                
                file_path = os.path.join(root, file)
                _, ext = os.path.splitext(file)
                if ext.lower() in IGNORE_EXTENSIONS:
                    continue
                
                rel_path = os.path.relpath(file_path, self.path)
                
                if get_content:
                    try:
                        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                            content = f.read()
                        yield content, {
                            "file_path": file_path,
                            "source": rel_path,
                            "url": f"file://{file_path}"
                        }
                    except Exception as e:
                        logger.warning(f"Skipping {file_path}: {e}")
                else:
                    yield {"file_path": file_path, "source": rel_path}


class LocalFileManager(DataManager):
    """Handles single file ingestion."""
    
    def __init__(self, path: str):
        super().__init__(dataset_id=path)
        self.path = path
    
    def download(self) -> bool:
        return os.path.exists(self.path)
    
    def walk(self, get_content: bool = True) -> Generator[Tuple[Any, Dict], None, None]:
        """Yields the single file."""
        if get_content:
            try:
                with open(self.path, 'r', encoding='utf-8', errors='ignore') as f:
                    content = f.read()
                yield content, {"file_path": self.path, "source": os.path.basename(self.path)}
            except Exception as e:
                logger.error(f"Failed to read {self.path}: {e}")
        else:
            yield {"file_path": self.path, "source": os.path.basename(self.path)}


class GitHubRepoManager(DataManager):
    """Handles GitHub repository cloning and ingestion."""
    
    def __init__(self, repo_id: str, local_dir: str, access_token: Optional[str] = None, commit_hash: Optional[str] = None):
        """
        Args:
            repo_id: GitHub repo in format "owner/repo"
            local_dir: Directory to clone to
            access_token: GitHub token for private repos
            commit_hash: Optional commit hash to checkout
        """
        super().__init__(dataset_id=repo_id)
        self.repo_id = repo_id
        self.local_dir = local_dir
        self.access_token = access_token or os.getenv("GITHUB_TOKEN")
        self.commit_hash = commit_hash
        self.path = os.path.join(local_dir, repo_id.replace("/", "_"))
    
    def download(self) -> bool:
        """Clones the GitHub repository."""
        if os.path.exists(self.path) and os.listdir(self.path):
            logger.info(f"Repo already cloned at {self.path}")
            return True
        
        try:
            from git import Repo, GitCommandError
            
            if self.access_token:
                clone_url = f"https://{self.access_token}@github.com/{self.repo_id}.git"
            else:
                clone_url = f"https://github.com/{self.repo_id}.git"
            
            os.makedirs(self.local_dir, exist_ok=True)
            
            if self.commit_hash:
                repo = Repo.clone_from(clone_url, self.path)
                repo.git.checkout(self.commit_hash)
            else:
                Repo.clone_from(clone_url, self.path, depth=1, single_branch=True)
            
            logger.info(f"Cloned {self.repo_id} to {self.path}")
            return True
        except ImportError:
            logger.error("GitPython not installed. Install with: pip install gitpython")
            raise
        except Exception as e:
            logger.error(f"Failed to clone {self.repo_id}: {e}")
            return False
    
    def walk(self, get_content: bool = True) -> Generator[Tuple[Any, Dict], None, None]:
        """Walks cloned repository."""
        if not os.path.exists(self.path):
            return
        
        # Use LocalDirectoryManager logic
        manager = LocalDirectoryManager(self.path)
        yield from manager.walk(get_content)


class WebDocManager(DataManager):
    """Handles web page/document ingestion."""
    
    def __init__(self, url: str, local_dir: str):
        super().__init__(dataset_id=url)
        self.url = url
        self.local_dir = local_dir
    
    def download(self) -> bool:
        """Checks if URL is accessible."""
        try:
            response = requests.get(self.url, timeout=10)
            return response.status_code == 200
        except Exception as e:
            logger.error(f"Could not reach {self.url}: {e}")
            return False
    
    def walk(self, get_content: bool = True) -> Generator[Tuple[Any, Dict], None, None]:
        """Fetches web page content."""
        try:
            response = requests.get(self.url, timeout=10)
            if get_content:
                from bs4 import BeautifulSoup
                soup = BeautifulSoup(response.content, 'html.parser')
                text = soup.get_text(separator='\n')
                yield text, {"file_path": self.url, "url": self.url, "source": "web"}
            else:
                yield {"file_path": self.url, "url": self.url, "source": "web"}
        except Exception as e:
            logger.error(f"Failed to fetch {self.url}: {e}")


def process_source(source: str, extract_to: str) -> Tuple[list, str]:
    """
    Convenience function to process any source type and return documents + local path.
    
    Returns:
        Tuple of (documents, local_path)
    """
    ingestor = UniversalIngestor(source, local_dir=extract_to)
    
    if not ingestor.download():
        raise ValueError(f"Failed to download/prepare source: {source}")
    
    documents = []
    for content, metadata in ingestor.walk(get_content=True):
        documents.append(Document(
            page_content=content,
            metadata=metadata
        ))
    
    return documents, ingestor.local_path