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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from typing import Optional
4
+ import re
5
+ import requests
6
+ from requests.adapters import HTTPAdapter, Retry
7
+ import arxiv
8
+ import PyPDF2
9
+ import requests
10
+ import time
11
+ from operator import itemgetter
12
+ import fitz
13
+ from tqdm import tqdm
14
+ from langchain.text_splitter import CharacterTextSplitter
15
+ import chromadb
16
+ from chromadb.utils import embedding_functions
17
+ import os
18
+ import asyncio
19
+ import uuid
20
+ from langchain.text_splitter import CharacterTextSplitter
21
+
22
+ emmbedding_model = "text-embedding-3-large"
23
+ OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
24
+
25
+ dir = "arxiv-data/2023"
26
+ chunk_size = 20
27
+
28
+ openai_ef = embedding_functions.OpenAIEmbeddingFunction(model_name=emmbedding_model,api_key=OPENAI_API_KEY)
29
+ # chroma_client = chromadb.HttpClient(host='localhost', port=8000) # use this if you are using chroma server Docker
30
+ chroma_client = chromadb.PersistentClient(path="/home/ubuntu/research/data/emeddeings")
31
+
32
+ text_splitter = CharacterTextSplitter(
33
+ separator="\n",
34
+ chunk_size=3000, chunk_overlap=0
35
+ )
36
+
37
+ collection_doc = chroma_client.get_or_create_collection(name="2024_main_document_lvl")
38
+ collection_para = chroma_client.get_or_create_collection(name="2024_main_paragraph_lvl")
39
+
40
+
41
+ def background(f):
42
+ def wrapped(*args, **kwargs):
43
+ return asyncio.get_event_loop().run_in_executor(None, f, *args, **kwargs)
44
+
45
+ return wrapped
46
+
47
+ paper_id_re = re.compile(r'https://arxiv.org/abs/(\d+\.\d+)')
48
+
49
+ def retry_request_session(retries: Optional[int] = 5):
50
+ # we setup retry strategy to retry on common errors
51
+ retries = Retry(
52
+ total=retries,
53
+ backoff_factor=0.1,
54
+ status_forcelist=[
55
+ 408, # request timeout
56
+ 500, # internal server error
57
+ 502, # bad gateway
58
+ 503, # service unavailable
59
+ 504 # gateway timeout
60
+ ]
61
+ )
62
+ # we setup a session with the retry strategy
63
+ session = requests.Session()
64
+ session.mount('https://', HTTPAdapter(max_retries=retries))
65
+ return session
66
+
67
+ def get_paper_id(query: str, handle_not_found: bool = True):
68
+ """Get the paper ID from a query.
69
+
70
+ :param query: The query to search with
71
+ :type query: str
72
+ :param handle_not_found: Whether to return None if no paper is found,
73
+ defaults to True
74
+ :type handle_not_found: bool, optional
75
+ :return: The paper ID
76
+ :rtype: str
77
+ """
78
+ special_chars = {
79
+ ":": "%3A",
80
+ "|": "%7C",
81
+ ",": "%2C",
82
+ " ": "+"
83
+ }
84
+ # create a translation table from the special_chars dictionary
85
+ translation_table = query.maketrans(special_chars)
86
+ # use the translate method to replace the special characters
87
+ search_term = query.translate(translation_table)
88
+ # init requests search session
89
+ session = retry_request_session()
90
+ # get the search results
91
+ res = session.get(f"https://www.google.com/search?q={search_term}&sclient=gws-wiz-serp")
92
+ try:
93
+ # extract the paper id
94
+ paper_id = paper_id_re.findall(res.text)[0]
95
+ except IndexError:
96
+ if handle_not_found:
97
+ # if no paper is found, return None
98
+ return None
99
+ else:
100
+ # if no paper is found, raise an error
101
+ raise Exception(f'No paper found for query: {query}')
102
+ return paper_id
103
+
104
+
105
+ class Arxiv:
106
+ refs_re = re.compile(r'\n(References|REFERENCES)\n')
107
+ references = []
108
+
109
+ llm = None
110
+
111
+ def __init__(self, paper_id: str):
112
+ """Object to handle the extraction of an ArXiv paper and its
113
+ relevant information.
114
+
115
+ :param paper_id: The ID of the paper to extract
116
+ :type paper_id: str
117
+ """
118
+ self.id = paper_id
119
+ self.url = f"https://export.arxiv.org/pdf/{paper_id}.pdf"
120
+ # initialize the requests session
121
+ self.session = requests.Session()
122
+
123
+ def load(self, save: bool = False):
124
+ """Load the paper from the ArXiv API or from a local file
125
+ if it already exists. Stores the paper's text content and
126
+ meta data in self.content and other attributes.
127
+
128
+ :param save: Whether to save the paper to a local file,
129
+ defaults to False
130
+ :type save: bool, optional
131
+ """
132
+ try:
133
+ self._download_meta()
134
+ if save:
135
+ self.save()
136
+ except Exception as e:
137
+ print(f"Error while downloading paper {self.id}: {e}")
138
+ raise e
139
+
140
+ def get_refs(self, extractor, text_splitter):
141
+ """Get the references for the paper.
142
+
143
+ :param extractor: The LLMChain extractor model
144
+ :type extractor: LLMChain
145
+ :param text_splitter: The text splitter to use
146
+ :type text_splitter: TokenTextSplitter
147
+ :return: The references for the paper
148
+ :rtype: list
149
+ """
150
+ if len(self.references) == 0:
151
+ self._download_refs(extractor, text_splitter)
152
+ return self.references
153
+
154
+ def _download_refs(self, extractor, text_splitter):
155
+ """Download the references for the paper. Stores them in
156
+ the self.references attribute.
157
+
158
+ :param extractor: The LLMChain extractor model
159
+ :type extractor: LLMChain
160
+ :param text_splitter: The text splitter to use
161
+ :type text_splitter: TokenTextSplitter
162
+ """
163
+ # get references section of paper
164
+ refs = self.refs_re.split(self.content)[-1]
165
+ # we don't need the full thing, just the first page
166
+ refs_page = text_splitter.split_text(refs)[0]
167
+ # use LLM extractor to extract references
168
+ out = extractor.run(refs=refs_page)
169
+ out = out.split('\n')
170
+ out = [o for o in out if o != '']
171
+ # with list of references, find the paper IDs
172
+ ids = [get_paper_id(o) for o in out]
173
+ # clean up into JSONL type format
174
+ out = [o.split(' | ') for o in out]
175
+ # in case we're missing some fields
176
+ out = [o for o in out if len(o) == 3]
177
+ meta = [{
178
+ 'id': _id,
179
+ 'title': o[0],
180
+ 'authors': o[1],
181
+ 'year': o[2]
182
+ } for o, _id in zip(out, ids) if _id is not None]
183
+ logging.debug(f"Extracted {len(meta)} references")
184
+ self.references = meta
185
+
186
+ def _convert_pdf_to_text(self):
187
+ """Convert the PDF to text and store it in the self.content
188
+ attribute.
189
+ """
190
+ text = []
191
+ with open("temp.pdf", 'rb') as f:
192
+ # create a PDF object
193
+ pdf = PyPDF2.PdfReader(f)
194
+ # iterate over every page in the PDF
195
+ for page in range(len(pdf.pages)):
196
+ # get the page object
197
+ page_obj = pdf.pages[page]
198
+ # extract text from the page
199
+ text.append(page_obj.extract_text())
200
+ text = "\n".join(text)
201
+ self.content = text
202
+
203
+ def _download_meta(self):
204
+ """Download the meta information for the paper from the
205
+ ArXiv API and store it in the self attributes.
206
+ """
207
+ search = arxiv.Search(
208
+ query=f'id:{self.id}',
209
+ max_results=1,
210
+ sort_by=arxiv.SortCriterion.SubmittedDate
211
+ )
212
+ result = list(search.results())
213
+ if len(result) == 0:
214
+ raise ValueError(f"No paper found for paper '{self.id}'")
215
+ result = result[0]
216
+ # remove 'v1', 'v2', etc. from the end of the pdf_url
217
+ result.pdf_url = re.sub(r'v\d+$', '', result.pdf_url)
218
+ self.authors = " ".join([author.name for author in result.authors])
219
+ self.journal_ref = result.journal_ref
220
+ self.source = result.pdf_url
221
+ self.summary = result.summary
222
+ self.title = result.title
223
+ logging.debug(f"Downloaded metadata for paper '{self.id}'")
224
+
225
+ def save(self):
226
+ """Save the paper to a local JSON file.
227
+ """
228
+ with open(f'papers/{self.id}.json', 'w') as fp:
229
+ json.dump(self.__dict__(), fp, indent=4)
230
+
231
+ def save_chunks(
232
+ self,
233
+ include_metadata: bool = True,
234
+ path: str = "chunks"
235
+ ):
236
+ """Save the paper's chunks to a local JSONL file.
237
+
238
+ :param include_metadata: Whether to include the paper's
239
+ metadata in the chunks, defaults
240
+ to True
241
+ :type include_metadata: bool, optional
242
+ :param path: The path to save the file to, defaults to "papers"
243
+ :type path: str, optional
244
+ """
245
+ if not os.path.exists(path):
246
+ os.makedirs(path)
247
+ with open(f'{path}/{self.id}.jsonl', 'w') as fp:
248
+ for chunk in self.dataset:
249
+ if include_metadata:
250
+ chunk.update(self.get_meta())
251
+ fp.write(json.dumps(chunk) + '\n')
252
+ logging.debug(f"Saved paper to '{path}/{self.id}.jsonl'")
253
+
254
+ def get_meta(self):
255
+ """Returns the meta information for the paper.
256
+
257
+ :return: The meta information for the paper
258
+ :rtype: dict
259
+ """
260
+ fields = self.__dict__()
261
+ # drop content field because it's big
262
+ # fields.pop('content')
263
+ return fields
264
+
265
+ def chunker(self, chunk_size=300):
266
+ # Single Chunk is made for now
267
+ clean_paper = self._clean_text(self.content)
268
+ langchain_dataset = []
269
+ langchain_dataset.append({
270
+ 'doi': self.id,
271
+ 'chunk-id': 1,
272
+ 'chunk': clean_paper
273
+ })
274
+ self.dataset = langchain_dataset
275
+
276
+ def _clean_text(self, text):
277
+ text = re.sub(r'-\n', '', text)
278
+ return text
279
+
280
+ def __dict__(self):
281
+ return {
282
+ 'id': self.id,
283
+ 'title': self.title,
284
+ 'summary': self.summary,
285
+ 'source': self.source,
286
+ 'authors': self.authors,
287
+ 'references': " ".join(self.references)
288
+ }
289
+
290
+ def __repr__(self):
291
+ return f"Arxiv(paper_id='{self.id}')"
292
+
293
+ def fonts(doc, granularity=False):
294
+ """Extracts fonts and their usage in PDF documents.
295
+
296
+ :param doc: PDF document to iterate through
297
+ :type doc: <class 'fitz.fitz.Document'>
298
+ :param granularity: also use 'font', 'flags' and 'color' to discriminate text
299
+ :type granularity: bool
300
+
301
+ :rtype: [(font_size, count), (font_size, count}], dict
302
+ :return: most used fonts sorted by count, font style information
303
+ """
304
+ styles = {}
305
+ font_counts = {}
306
+
307
+ for page in doc:
308
+ blocks = page.get_text("dict")["blocks"]
309
+ for b in blocks: # iterate through the text blocks
310
+ if b['type'] == 0: # block contains text
311
+ for l in b["lines"]: # iterate through the text lines
312
+ for s in l["spans"]: # iterate through the text spans
313
+ if granularity:
314
+ identifier = "{0}_{1}_{2}_{3}".format(s['size'], s['flags'], s['font'], s['color'])
315
+ styles[identifier] = {'size': s['size'], 'flags': s['flags'], 'font': s['font'],
316
+ 'color': s['color']}
317
+ else:
318
+ identifier = "{0}".format(s['size'])
319
+ styles[identifier] = {'size': s['size'], 'font': s['font']}
320
+
321
+ font_counts[identifier] = font_counts.get(identifier, 0) + 1 # count the fonts usage
322
+
323
+ font_counts = sorted(font_counts.items(), key=itemgetter(1), reverse=True)
324
+
325
+ if len(font_counts) < 1:
326
+ raise ValueError("Zero discriminating fonts found!")
327
+
328
+ return font_counts, styles
329
+
330
+
331
+ def font_tags(font_counts, styles):
332
+ """Returns dictionary with font sizes as keys and tags as value.
333
+
334
+ :param font_counts: (font_size, count) for all fonts occuring in document
335
+ :type font_counts: list
336
+ :param styles: all styles found in the document
337
+ :type styles: dict
338
+
339
+ :rtype: dict
340
+ :return: all element tags based on font-sizes
341
+ """
342
+ p_style = styles[font_counts[0][0]] # get style for most used font by count (paragraph)
343
+ p_size = p_style['size'] # get the paragraph's size
344
+
345
+ # sorting the font sizes high to low, so that we can append the right integer to each tag
346
+ font_sizes = []
347
+ for (font_size, count) in font_counts:
348
+ font_sizes.append(float(font_size))
349
+ font_sizes.sort(reverse=True)
350
+
351
+ # aggregating the tags for each font size
352
+ idx = 0
353
+ size_tag = {}
354
+ for size in font_sizes:
355
+ idx += 1
356
+ if size == p_size:
357
+ idx = 0
358
+ size_tag[size] = '<p>'
359
+ if size > p_size:
360
+ size_tag[size] = '<h{0}>'.format(idx)
361
+ elif size < p_size:
362
+ size_tag[size] = '<s{0}>'.format(idx)
363
+
364
+ return size_tag
365
+
366
+
367
+ def headers_para(doc, size_tag):
368
+ """Scrapes headers & paragraphs from PDF and return texts with element tags.
369
+
370
+ :param doc: PDF document to iterate through
371
+ :type doc: <class 'fitz.fitz.Document'>
372
+ :param size_tag: textual element tags for each size
373
+ :type size_tag: dict
374
+
375
+ :rtype: list
376
+ :return: texts with pre-prended element tags
377
+ """
378
+ paragraphs = [] # list with paragraphs
379
+ first = True # boolean operator for first header
380
+ previous_s = {} # previous span
381
+
382
+ for page in doc:
383
+ blocks = page.get_text("dict")["blocks"]
384
+ for b in blocks: # iterate through the text blocks
385
+ if b['type'] == 0: # this block contains text
386
+
387
+ # REMEMBER: multiple fonts and sizes are possible IN one block
388
+
389
+ block_string = "" # text found in block
390
+ for l in b["lines"]: # iterate through the text lines
391
+ for s in l["spans"]: # iterate through the text spans
392
+ if s['text'].strip(): # removing whitespaces:
393
+ if first:
394
+ previous_s = s
395
+ first = False
396
+ block_string = s['text'] if size_tag[s['size']] == '<p>' else ''
397
+ else:
398
+ if s['size'] == previous_s['size']:
399
+ if block_string: # in the same block, so concatenate strings
400
+ block_string += " " + s['text']
401
+ else:
402
+ if block_string: # new block has started, so append the paragraph
403
+ paragraphs.append(block_string)
404
+ block_string = s['text'] if size_tag[s['size']] == '<p>' else ''
405
+
406
+ previous_s = s
407
+
408
+ if block_string: # append the last paragraph in the block
409
+ if len(block_string) > 80:
410
+ # print(len(block_string), block_string,'\n')
411
+ paragraphs.append(block_string)
412
+
413
+ return paragraphs
414
+
415
+ def get_pdf_info(document_path):
416
+ docs = fitz.open(document_path)
417
+ only_text = ""
418
+ for page in docs:
419
+ only_text += page.get_text() + " "
420
+ font_counts, styles = fonts(docs, granularity=False)
421
+ size_tag = font_tags(font_counts, styles)
422
+ elements = headers_para(docs, size_tag)
423
+ paragraphs = []
424
+ for element in elements:
425
+ if len(element) > 100:
426
+ paragraphs.append(element.lower())
427
+ pattern = r'\d+(\.\d+)?\n'
428
+ cleaned_text = re.sub(pattern, '', only_text)
429
+ return cleaned_text.lower(),paragraphs
430
+
431
+ def generate_uuid():
432
+ return str(uuid.uuid4())
433
+
434
+ def add_document_chroma_collection(collection_object, document_list, embedding_list, metadata):
435
+
436
+ metadata_list = [metadata for i in range(len(document_list))]
437
+ ids_gen = [generate_uuid() for i in range(len(document_list))]
438
+ collection_object.add(embeddings = embedding_list,documents = document_list,metadatas = metadata_list,ids = ids_gen)
439
+ if collection_object:
440
+ return True
441
+
442
+ def chunk_list(input_list, chunk_size):
443
+ return [input_list[i:i + chunk_size] for i in range(0, len(input_list), chunk_size)]
444
+
445
+ directories_2023 = [ os.path.join(dir, o) for o in os.listdir(dir) if os.path.isdir(os.path.join(dir,o)) ]
446
+
447
+
448
+ @background
449
+ def task(chunk):
450
+ chunked_files = [os.path.join(single_dir, file) for file in chunk]
451
+ # print("len of chunked_files", len(chunked_files))
452
+ for file_path in (chunked_files):
453
+ try:
454
+ paper_id = file_path.split("/")[-1].split(".pdf")[0].replace("v1", "").replace("v2", "").replace("v3", "").replace("v4", "").replace("v5", "")
455
+ # print("paper_id", paper_id)
456
+ paper = Arxiv(paper_id)
457
+ paper.load()
458
+ metadata = paper.get_meta()
459
+ only_text,paragraphs = get_pdf_info(file_path)
460
+ texts_list = text_splitter.split_text(only_text)
461
+ if len(texts_list) > 0:
462
+ doc_embed = openai_ef(texts_list)
463
+ add_document_chroma_collection(collection_doc, texts_list, doc_embed,metadata)
464
+ if len(paragraphs) > 0:
465
+ paragraphs_embed = openai_ef(paragraphs)
466
+ add_document_chroma_collection(collection_para, paragraphs, paragraphs_embed,metadata)
467
+ time.sleep(5)
468
+ except Exception as e:
469
+ print("Error", e)
470
+ with open("error.txt", "a") as f:
471
+ f.write(file_path)
472
+ continue
473
+
474
+ for single_dir in directories_2023:
475
+ print("len of files", len(os.listdir(single_dir)))
476
+ chunked_list = chunk_list(os.listdir(single_dir), 20)
477
+ print("len of chunked_list", len(chunked_list))
478
+ for chunk in tqdm(chunked_list):
479
+ task(chunk)
480
+ time.sleep(5)