Farid Karimli commited on
Commit
e27870a
·
1 Parent(s): 0f566b9

HTML & latex to Markdown

Browse files
code/modules/config/constants.py CHANGED
@@ -6,6 +6,8 @@ load_dotenv()
6
  # API Keys - Loaded from the .env file
7
 
8
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
 
 
9
  HUGGINGFACE_TOKEN = os.getenv("HUGGINGFACE_TOKEN")
10
  LITERAL_API_KEY = os.getenv("LITERAL_API_KEY")
11
 
@@ -14,7 +16,8 @@ opening_message = f"Hey, What Can I Help You With?\n\nYou can me ask me question
14
  # Prompt Templates
15
 
16
  openai_prompt_template = """Use the following pieces of information to answer the user's question.
17
- If you don't know the answer, just say that you don't know.
 
18
 
19
  Context: {context}
20
  Question: {question}
@@ -24,7 +27,10 @@ Helpful answer:
24
  """
25
 
26
  openai_prompt_template_with_history = """Use the following pieces of information to answer the user's question.
 
 
27
  If you don't know the answer, just say that you don't know, don't try to make up an answer.
 
28
  Use the history to answer the question if you can.
29
  Chat History:
30
  {chat_history}
@@ -37,7 +43,7 @@ Helpful answer:
37
 
38
  tinyllama_prompt_template = """
39
  <|im_start|>system
40
- Assistant is an intelligent chatbot designed to help students with questions regarding the course. Only answer questions using the context below and if you're not sure of an answer, you can say "I don't know". Always give a breif and concise answer to the question. Use the history to answer the question if you can.
41
 
42
  Context:
43
  {context}
@@ -56,7 +62,7 @@ Question: {question}
56
 
57
  tinyllama_prompt_template_with_history = """
58
  <|im_start|>system
59
- Assistant is an intelligent chatbot designed to help students with questions regarding the course. Only answer questions using the context below and if you're not sure of an answer, you can say "I don't know". Always give a breif and concise answer to the question.
60
 
61
  Chat History:
62
  {chat_history}
 
6
  # API Keys - Loaded from the .env file
7
 
8
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
9
+ GPT4o_API_KEY = os.getenv("GPT4o_API_KEY")
10
+ LLAMA_CLOUD_API_KEY = os.getenv("LLAMA_CLOUD_API_KEY")
11
  HUGGINGFACE_TOKEN = os.getenv("HUGGINGFACE_TOKEN")
12
  LITERAL_API_KEY = os.getenv("LITERAL_API_KEY")
13
 
 
16
  # Prompt Templates
17
 
18
  openai_prompt_template = """Use the following pieces of information to answer the user's question.
19
+ You are an intelligent chatbot designed to help students with questions regarding the course. Render math equations in LaTeX format between $$ signs, and explain the parameters and variables in the equations.
20
+ If you don't know the answer, just say that you don't know.
21
 
22
  Context: {context}
23
  Question: {question}
 
27
  """
28
 
29
  openai_prompt_template_with_history = """Use the following pieces of information to answer the user's question.
30
+ You are an intelligent chatbot designed to help students with questions regarding the course. Render math equations in LaTeX format between $$ signs.
31
+
32
  If you don't know the answer, just say that you don't know, don't try to make up an answer.
33
+
34
  Use the history to answer the question if you can.
35
  Chat History:
36
  {chat_history}
 
43
 
44
  tinyllama_prompt_template = """
45
  <|im_start|>system
46
+ Assistant is an intelligent chatbot designed to help students with questions regarding the course. Only answer questions using the context below and if you're not sure of an answer, you can say "I don't know". Always give a brief and concise answer to the question. When asked for formulas, give a brief description of the formula and output math equations in LaTeX format between $ signs.
47
 
48
  Context:
49
  {context}
 
62
 
63
  tinyllama_prompt_template_with_history = """
64
  <|im_start|>system
65
+ Assistant is an intelligent chatbot designed to help students with questions regarding the course. Only answer questions using the context below and if you're not sure of an answer, you can say "I don't know". Always give a brief and concise answer to the question. Output math equations in LaTeX format between $ signs. Use the history to answer the question if you can.
66
 
67
  Chat History:
68
  {chat_history}
code/modules/data_loader.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import bs4
3
+ from urllib.parse import urljoin
4
+ import requests
5
+ import pysrt
6
+ from langchain_community.document_loaders import (
7
+ PyMuPDFLoader,
8
+ Docx2txtLoader,
9
+ YoutubeLoader,
10
+ WebBaseLoader,
11
+ TextLoader,
12
+ )
13
+ import html2text
14
+ from langchain_community.document_loaders import UnstructuredMarkdownLoader
15
+ from llama_parse import LlamaParse
16
+ from langchain.schema import Document
17
+ import logging
18
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
19
+ from langchain_experimental.text_splitter import SemanticChunker
20
+ from langchain_openai.embeddings import OpenAIEmbeddings
21
+ from ragatouille import RAGPretrainedModel
22
+ from langchain.chains import LLMChain
23
+ from langchain.llms import OpenAI
24
+ from langchain import PromptTemplate
25
+
26
+ try:
27
+ from modules.helpers import get_lecture_metadata
28
+ from modules.constants import OPENAI_API_KEY, LLAMA_CLOUD_API_KEY
29
+ except:
30
+ from helpers import get_lecture_metadata
31
+ from constants import OPENAI_API_KEY, LLAMA_CLOUD_API_KEY
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ class PDFReader:
37
+ def __init__(self):
38
+ pass
39
+
40
+ def get_loader(self, pdf_path):
41
+ loader = PyMuPDFLoader(pdf_path)
42
+ return loader
43
+
44
+ def get_documents(self, loader):
45
+ return loader.load()
46
+
47
+
48
+ class LlamaParser:
49
+ def __init__(self):
50
+ self.parser = LlamaParse(
51
+ api_key=LLAMA_CLOUD_API_KEY,
52
+ result_type="markdown",
53
+ verbose=True,
54
+ language="en",
55
+ gpt4o_mode=True,
56
+ gpt4o_api_key=OPENAI_API_KEY,
57
+ parsing_instruction="The provided documents are PDFs of lecture slides of deep learning material. They contain LaTeX equations, images, and text. The goal is to extract the text and equations from the slides and convert them to markdown format. The markdown should be clean and easy to read, and any math equation should be converted to LaTeX, between $$."
58
+ )
59
+
60
+ def parse(self, pdf_path):
61
+ documents = self.parser.load_data(pdf_path)
62
+ documents = [document.to_langchain_format() for document in documents]
63
+ return documents
64
+
65
+
66
+ class HTMLReader:
67
+ def __init__(self):
68
+ pass
69
+
70
+ def read_url(self, url):
71
+ response = requests.get(url)
72
+ if response.status_code == 200:
73
+ return response.text
74
+ else:
75
+ logger.warning(f"Failed to download HTML from URL: {url}")
76
+ return None
77
+
78
+ def check_links(self, base_url, html_content):
79
+ soup = bs4.BeautifulSoup(html_content, "html.parser")
80
+ for link in soup.find_all("a"):
81
+ href = link.get("href")
82
+
83
+ if not href or href.startswith("#"):
84
+ continue
85
+ elif not href.startswith("https"):
86
+ href = href.replace("http", "https")
87
+
88
+ absolute_url = urljoin(base_url, href)
89
+ link['href'] = absolute_url
90
+
91
+ resp = requests.head(absolute_url)
92
+ if resp.status_code != 200:
93
+ logger.warning(f"Link {absolute_url} is broken")
94
+ logger.warning(f"Status code: {resp.status_code}")
95
+
96
+ return str(soup)
97
+
98
+ def html_to_md(self, url, html_content):
99
+ html_processed = self.check_links(url, html_content)
100
+ markdown_content = html2text.html2text(html_processed)
101
+ return markdown_content
102
+
103
+ def read_html(self, url):
104
+ html_content = self.read_url(url)
105
+ if html_content:
106
+ return self.html_to_md(url, html_content)
107
+ else:
108
+ return None
109
+
110
+
111
+ class FileReader:
112
+ def __init__(self, kind):
113
+ self.kind = kind
114
+ if kind == "llama":
115
+ self.pdf_reader = LlamaParser()
116
+ else:
117
+ self.pdf_reader = PDFReader()
118
+ self.web_reader = HTMLReader()
119
+
120
+ def extract_text_from_pdf(self, pdf_path):
121
+ text = ""
122
+ with open(pdf_path, "rb") as file:
123
+ reader = PyPDF2.PdfReader(file)
124
+ num_pages = len(reader.pages)
125
+ for page_num in range(num_pages):
126
+ page = reader.pages[page_num]
127
+ text += page.extract_text()
128
+ return text
129
+
130
+ def download_pdf_from_url(self, pdf_url):
131
+ response = requests.get(pdf_url)
132
+ if response.status_code == 200:
133
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
134
+ temp_file.write(response.content)
135
+ temp_file_path = temp_file.name
136
+ return temp_file_path
137
+ else:
138
+ print("Failed to download PDF from URL:", pdf_url)
139
+ return None
140
+
141
+ def read_pdf(self, temp_file_path: str):
142
+ if self.kind == "llama":
143
+ documents = self.pdf_reader.parse(temp_file_path)
144
+ else:
145
+ loader = self.pdf_reader.get_loader(temp_file_path)
146
+ documents = self.pdf_reader.get_documents(loader)
147
+ return documents
148
+
149
+ def read_txt(self, temp_file_path: str):
150
+ loader = TextLoader(temp_file_path, autodetect_encoding=True)
151
+ return loader.load()
152
+
153
+ def read_docx(self, temp_file_path: str):
154
+ loader = Docx2txtLoader(temp_file_path)
155
+ return loader.load()
156
+
157
+ def read_srt(self, temp_file_path: str):
158
+ subs = pysrt.open(temp_file_path)
159
+ text = ""
160
+ for sub in subs:
161
+ text += sub.text
162
+ return [Document(page_content=text)]
163
+
164
+ def read_youtube_transcript(self, url: str):
165
+ loader = YoutubeLoader.from_youtube_url(
166
+ url, add_video_info=True, language=["en"], translation="en"
167
+ )
168
+ return loader.load()
169
+
170
+ def read_html(self, url: str):
171
+ return [Document(page_content=self.web_reader.read_html(url))]
172
+
173
+
174
+ class ChunkProcessor:
175
+ def __init__(self, config):
176
+ self.config = config
177
+
178
+ if config["splitter_options"]["use_splitter"]:
179
+ if config["splitter_options"]["split_by_token"]:
180
+ self.splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
181
+ chunk_size=config["splitter_options"]["chunk_size"],
182
+ chunk_overlap=config["splitter_options"]["chunk_overlap"],
183
+ separators=config["splitter_options"]["chunk_separators"],
184
+ disallowed_special=(),
185
+ )
186
+ else:
187
+ self.splitter = RecursiveCharacterTextSplitter(
188
+ chunk_size=config["splitter_options"]["chunk_size"],
189
+ chunk_overlap=config["splitter_options"]["chunk_overlap"],
190
+ separators=config["splitter_options"]["chunk_separators"],
191
+ disallowed_special=(),
192
+ )
193
+ else:
194
+ self.splitter = None
195
+ logger.info("ChunkProcessor instance created")
196
+
197
+ def remove_delimiters(self, document_chunks: list):
198
+ for chunk in document_chunks:
199
+ for delimiter in self.config["splitter_options"]["delimiters_to_remove"]:
200
+ chunk.page_content = re.sub(delimiter, " ", chunk.page_content)
201
+ return document_chunks
202
+
203
+ def remove_chunks(self, document_chunks: list):
204
+ front = self.config["splitter_options"]["front_chunk_to_remove"]
205
+ end = self.config["splitter_options"]["last_chunks_to_remove"]
206
+ for _ in range(front):
207
+ del document_chunks[0]
208
+ for _ in range(end):
209
+ document_chunks.pop()
210
+ logger.info(f"\tNumber of pages after skipping: {len(document_chunks)}")
211
+ return document_chunks
212
+
213
+ def process_chunks(
214
+ self, documents, file_type="txt", source="", page=0, metadata={}
215
+ ):
216
+ documents = [Document(page_content=documents, source=source, page=page)]
217
+ if file_type == "txt":
218
+ document_chunks = self.splitter.split_documents(documents)
219
+ elif file_type == "pdf":
220
+ document_chunks = documents # Full page for now
221
+
222
+ # add the source and page number back to the metadata
223
+ for chunk in document_chunks:
224
+ chunk.metadata["source"] = source
225
+ chunk.metadata["page"] = page
226
+
227
+ # add the metadata extracted from the document
228
+ for key, value in metadata.items():
229
+ chunk.metadata[key] = value
230
+
231
+ if self.config["splitter_options"]["remove_leftover_delimiters"]:
232
+ document_chunks = self.remove_delimiters(document_chunks)
233
+ if self.config["splitter_options"]["remove_chunks"]:
234
+ document_chunks = self.remove_chunks(document_chunks)
235
+
236
+ return document_chunks
237
+
238
+ def get_chunks(self, file_reader, uploaded_files, weblinks):
239
+ self.document_chunks_full = []
240
+ self.parent_document_names = []
241
+ self.child_document_names = []
242
+ self.documents = []
243
+ self.document_metadata = []
244
+
245
+ lecture_metadata = get_lecture_metadata(
246
+ "https://dl4ds.github.io/sp2024/lectures/",
247
+ "https://dl4ds.github.io/sp2024/schedule/",
248
+ ) # TODO: Use more efficiently
249
+
250
+ for file_index, file_path in enumerate(uploaded_files):
251
+ file_name = os.path.basename(file_path)
252
+ file_type = file_name.split(".")[-1].lower()
253
+
254
+ # try:
255
+ if file_type == "pdf":
256
+ documents = file_reader.read_pdf(file_path)
257
+ elif file_type == "txt":
258
+ documents = file_reader.read_txt(file_path)
259
+ elif file_type == "docx":
260
+ documents = file_reader.read_docx(file_path)
261
+ elif file_type == "srt":
262
+ documents = file_reader.read_srt(file_path)
263
+ else:
264
+ logger.warning(f"Unsupported file type: {file_type}")
265
+ continue
266
+
267
+ # full_text = ""
268
+ # for doc in documents:
269
+ # full_text += doc.page_content
270
+ # break # getting only first page for now
271
+
272
+ # extracted_metadata = self.extract_metadata(full_text)
273
+
274
+ for doc in documents:
275
+ page_num = doc.metadata.get("page", 0)
276
+ self.documents.append(doc.page_content)
277
+ self.document_metadata.append({"source": file_path, "page": page_num})
278
+ if "lecture" in file_path.lower():
279
+ metadata = lecture_metadata.get(file_path, {})
280
+ metadata["source_type"] = "lecture"
281
+ self.document_metadata[-1].update(metadata)
282
+ else:
283
+ metadata = {"source_type": "other"}
284
+
285
+ self.child_document_names.append(f"{file_name}_{page_num}")
286
+
287
+ self.parent_document_names.append(file_name)
288
+ if self.config["embedding_options"]["db_option"] not in ["RAGatouille"]:
289
+ document_chunks = self.process_chunks(
290
+ self.documents[-1],
291
+ file_type,
292
+ source=file_path,
293
+ page=page_num,
294
+ metadata=metadata,
295
+ )
296
+ self.document_chunks_full.extend(document_chunks)
297
+
298
+ # except Exception as e:
299
+ # logger.error(f"Error processing file {file_name}: {str(e)}")
300
+
301
+ self.process_weblinks(file_reader, weblinks)
302
+
303
+ logger.info(
304
+ f"Total document chunks extracted: {len(self.document_chunks_full)}"
305
+ )
306
+ return (
307
+ self.document_chunks_full,
308
+ self.child_document_names,
309
+ self.documents,
310
+ self.document_metadata,
311
+ )
312
+
313
+ def process_weblinks(self, file_reader, weblinks):
314
+ if weblinks[0] != "":
315
+ logger.info(f"Splitting weblinks: total of {len(weblinks)}")
316
+
317
+ for link_index, link in enumerate(weblinks):
318
+ try:
319
+ logger.info(f"\tSplitting link {link_index + 1} : {link}")
320
+ if "youtube" in link:
321
+ documents = file_reader.read_youtube_transcript(link)
322
+ else:
323
+ documents = file_reader.read_html(link)
324
+ print(f"Link: {link}")
325
+ print(documents)
326
+ for doc in documents:
327
+ page_num = doc.metadata.get("page", 0)
328
+ self.documents.append(doc.page_content)
329
+ self.document_metadata.append(
330
+ {"source": link, "page": page_num}
331
+ )
332
+ self.child_document_names.append(f"{link}")
333
+
334
+ self.parent_document_names.append(link)
335
+ if self.config["embedding_options"]["db_option"] not in [
336
+ "RAGatouille"
337
+ ]:
338
+ document_chunks = self.process_chunks(
339
+ self.documents[-1],
340
+ "txt",
341
+ source=link,
342
+ page=0,
343
+ metadata={"source_type": "webpage"},
344
+ )
345
+ self.document_chunks_full.extend(document_chunks)
346
+ except Exception as e:
347
+ logger.error(
348
+ f"Error splitting link {link_index + 1} : {link}: {str(e)}"
349
+ )
350
+
351
+
352
+ class DataLoader:
353
+ def __init__(self, config):
354
+ if config["llm_params"]["pdf_reader"] == "llama":
355
+ if LLAMA_CLOUD_API_KEY == None or OPENAI_API_KEY == None:
356
+ raise ValueError(
357
+ "Please set the LLAMA_CLOUD_API_KEY and GPT4o_API_KEY environment variables"
358
+ )
359
+
360
+ self.file_reader = FileReader(kind=config["llm_params"]["pdf_reader"])
361
+ self.chunk_processor = ChunkProcessor(config)
362
+
363
+ def get_chunks(self, uploaded_files, weblinks):
364
+ return self.chunk_processor.get_chunks(
365
+ self.file_reader, uploaded_files, weblinks
366
+ )
367
+
368
+
369
+ if __name__ == "__main__":
370
+ # read config.yml file
371
+ import yaml
372
+ import os
373
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
374
+
375
+ with open(os.path.join(BASE_DIR, "../", "config.yml"), "r") as f:
376
+ config = yaml.safe_load(f)
377
+
378
+ # create DataLoader instance
379
+ chunk_processor = ChunkProcessor(config)
380
+ file_reader = FileReader(kind=config["llm_params"]["pdf_reader"])
381
+
382
+ weblinks = ["https://dl4ds.github.io/sp2024/"]
383
+
384
+ uploaded_files = []
385
+
386
+ # get document chunks
387
+ document_chunks, child_document_names, documents, document_metadata = chunk_processor.get_chunks(
388
+ file_reader, uploaded_files, weblinks
389
+ )
390
+
391
+
392
+ print(document_chunks)