Elffuss BraidHub

kikocis/GraphRAG-SDK public

ca14f368bce9 · 1.7 KiBRawPermalink
1from typing import Iterator
2from abc import ABC, abstractmethod
3from graphrag_sdk.Document import Document
4from graphrag_sdk.document_loaders import *
5
6def Source(path:str, instruction:str|None=None) ->'AbstractSource':
7 """
8 Creates a source object
9
10 Parameters:
11 path (str): path to source
12 instruction (str): source specific instruction for the LLM
13
14 Returns:
15 AbstractSource: source
16 """
17
18 if not isinstance(path, str) or path == "":
19 raise Exception("Invalid argument, path should be a none empty string.")
20
21 s = None
22
23 if ".pdf" in path.lower():
24 s = PDF(path)
25 elif ".html" in path.lower() or "http" in path.lower():
26 s = HTML(path)
27 else:
28 s = TEXT(path)
29
30 # Set source instructions
31 s.instruction = instruction
32
33 return s
34
35class AbstractSource(ABC):
36 """
37 Abstract class representing a source file
38 """
39
40 def __init__(self, path:str):
41 self.path = path
42 self.loader = None
43
44 def load(self) -> Iterator[Document]:
45 return self.loader.load()
46
47 def __eq__(self, other) -> bool:
48 if not isinstance(other, AbstractSource):
49 return False
50
51 return self.path == other.path
52
53 def __hash__(self):
54 return hash(self.path)
55
56class PDF(AbstractSource):
57 """
58 PDF resource
59 """
60
61 def __init__(self, path):
62 super().__init__(path)
63 self.loader = PDFLoader(self.path)
64
65class TEXT(AbstractSource):
66 """
67 TEXT resource
68 """
69
70 def __init__(self, path):
71 super().__init__(path)
72 self.loader = TextLoader(self.path)
73
74class HTML(AbstractSource):
75 """
76 HTML resource
77 """
78
79 def __init__(self, path):
80 super().__init__(path)
81 self.loader = HTMLLoader(self.path)