Elffuss BraidHub

kikocis/GraphRAG-SDK public

c4d9d856add1 · 2.2 KiBRawPermalink
1import re
2import requests
3from bs4 import BeautifulSoup
4from abc import ABC, abstractmethod
5
6def download_resource(url):
7 print(f"Downloading: {url}")
8
9 # Send an HTTP GET request to the URL
10 response = requests.get(url)
11
12 # Check if the request was successful (status code 200)
13 content = None
14 if response.status_code == 200:
15 # Retrieve content
16 content = response.text
17 else:
18 print(f"Failed to retrieve content. Status code: {response.status_code}")
19
20 return content
21
22def Source(source:str):
23 if not isinstance(source, str) or source == "":
24 raise Exception("Invalid argument, source should be a none empty string.")
25
26 if ".pdf" in source.lower():
27 return PDF(source)
28 elif ".html" in source.lower():
29 return HTML(source)
30 else:
31 return TEXT(source)
32
33class AbstractSource(ABC):
34 def __init__(self, source:str):
35 self.source = source
36 self.content = None
37
38 @abstractmethod
39 def load(self) -> str:
40 pass
41
42 def __eq__(self, other) -> bool:
43 if not isinstance(other, AbstractSource):
44 return False
45
46 return self.source == other.source
47
48 def __hash__(self):
49 return hash(self.source)
50
51class PDF(AbstractSource):
52 def __init__(self, source):
53 super().__init__(source)
54
55 def load(self):
56 # extract text from PDF, populate self.content
57 self.content = None
58
59class TEXT(AbstractSource):
60 def __init__(self, source):
61 super().__init__(source)
62
63 def load(self):
64 if self.content is None:
65 # populate self.content
66 with open(self.source, 'r') as f:
67 self.content = f.read()
68
69 return self.content
70
71class HTML(AbstractSource):
72 def __init__(self, source):
73 super().__init__(source)
74
75 def load(self):
76 with open(self.source, 'r') as f:
77 self.content = f.read()
78
79 # extract text from HTML, populate self.content
80 soup = BeautifulSoup(self.content, 'html.parser')
81
82 # Extract text from the HTML
83 self.content = soup.get_text()
84
85 # Remove extra newlines
86 self.content = re.sub(r'\n{2,}', '\n', self.content)