Elffuss BraidHub

kikocis/GraphRAG-SDK public

423ab603a5a9 · 2.1 KiBRawPermalink
1import re
2import requests
3from bs4 import BeautifulSoup
4from abc import ABC, abstractmethod
5
6def Source(source:str) ->'AbstractSource':
7 """
8 Creates a source object
9
10 Parameters:
11 source (str): path to source
12
13 Returns:
14 AbstractSource: source
15 """
16
17 if not isinstance(source, str) or source == "":
18 raise Exception("Invalid argument, source should be a none empty string.")
19
20 if ".pdf" in source.lower():
21 return PDF(source)
22 elif ".html" in source.lower():
23 return HTML(source)
24 else:
25 return TEXT(source)
26
27class AbstractSource(ABC):
28 """
29 Abstract class representing a source file
30 """
31
32 def __init__(self, source:str):
33 self.source = source
34 self.content = None
35
36 @abstractmethod
37 def load(self) -> str:
38 pass
39
40 def __eq__(self, other) -> bool:
41 if not isinstance(other, AbstractSource):
42 return False
43
44 return self.source == other.source
45
46 def __hash__(self):
47 return hash(self.source)
48
49class PDF(AbstractSource):
50 """
51 PDF resource
52 """
53
54 def __init__(self, source):
55 super().__init__(source)
56
57 def load(self):
58 raise Exception("Not implemented")
59 # extract text from PDF, populate self.content
60 self.content = None
61
62class TEXT(AbstractSource):
63 """
64 TEXT resource
65 """
66
67 def __init__(self, source):
68 super().__init__(source)
69
70 def load(self):
71 if self.content is None:
72 # populate self.content
73 with open(self.source, 'r') as f:
74 self.content = f.read()
75
76 return self.content
77
78class HTML(AbstractSource):
79 """
80 HTML resource
81 """
82
83 def __init__(self, source):
84 super().__init__(source)
85
86 def load(self):
87 with open(self.source, 'r') as f:
88 self.content = f.read()
89
90 # extract text from HTML, populate self.content
91 soup = BeautifulSoup(self.content, 'html.parser')
92
93 # Extract text from the HTML
94 self.content = soup.get_text()
95
96 # Remove extra newlines
97 self.content = re.sub(r'\n{2,}', '\n', self.content)