Jacob Petterle commited on
Commit
68e5c7e
·
unverified ·
2 Parent(s): 7cab8e3cab3aca

Merge pull request #3 from ai-for-u/feature/langchang-chunk

Browse files
Files changed (2) hide show
  1. plugin/pdf.py +62 -8
  2. scripts/extract_text.py +5 -3
plugin/pdf.py CHANGED
@@ -1,13 +1,67 @@
 
1
  from pathlib import Path
2
- import PyPDF2
 
 
 
3
 
 
 
 
4
 
5
- def extract_text(pdf: Path):
6
- text = []
7
- reader = PyPDF2.PdfReader(pdf)
8
- for page in reader.pages:
9
- print(page.items())
10
- text.append(page.extract_text())
11
- return "".join(text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
 
 
 
 
 
 
 
 
 
 
 
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TypedDict, Sequence
2
  from pathlib import Path
3
+ from langchain.document_loaders import PDFMinerPDFasHTMLLoader
4
+ from langchain.docstore.document import Document
5
+ from bs4 import BeautifulSoup
6
+ import re
7
 
8
+ class SemanticSnippet(TypedDict):
9
+ text: str
10
+ metadata: dict
11
 
12
+ def get_semantic_snippets(pdf: Path) -> Sequence[SemanticSnippet]:
13
+ loader = PDFMinerPDFasHTMLLoader(str(pdf))
14
+ data = loader.load()[0]
15
+ soup = BeautifulSoup(data.page_content, features="html.parser")
16
+ content = soup.find_all("div")
17
+ cur_fs = None
18
+ cur_text = ''
19
+ snippets = [] # first collect all snippets that have the same font size
20
+ for c in content:
21
+ sp = c.find('span')
22
+ if not sp:
23
+ continue
24
+ st = sp.get('style')
25
+ if not st:
26
+ continue
27
+ fs = re.findall('font-size:(\d+)px',st)
28
+ if not fs:
29
+ continue
30
+ fs = int(fs[0])
31
+ if not cur_fs:
32
+ cur_fs = fs
33
+ if fs == cur_fs:
34
+ cur_text += c.text
35
+ else:
36
+ snippets.append((cur_text,cur_fs))
37
+ cur_fs = fs
38
+ cur_text = c.text
39
+ snippets.append((cur_text,cur_fs))
40
 
41
+ cur_idx = -1
42
+ semantic_snippets = []
43
+ # Assumption: headings have higher font size than their respective content
44
+ for s in snippets:
45
+ # if current snippet's font size > previous section's heading => it is a new heading
46
+ if not semantic_snippets or s[1] > semantic_snippets[cur_idx].metadata['heading_font']:
47
+ metadata={'heading':s[0], 'content_font': 0, 'heading_font': s[1]}
48
+ metadata.update(data.metadata)
49
+ semantic_snippets.append(Document(page_content='',metadata=metadata))
50
+ cur_idx += 1
51
+ continue
52
 
53
+ # if current snippet's font size <= previous section's content => content belongs to the same section (one can also create
54
+ # a tree like structure for sub sections if needed but that may require some more thinking and may be data specific)
55
+ if not semantic_snippets[cur_idx].metadata['content_font'] or s[1] <= semantic_snippets[cur_idx].metadata['content_font']:
56
+ semantic_snippets[cur_idx].page_content += s[0]
57
+ semantic_snippets[cur_idx].metadata['content_font'] = max(s[1], semantic_snippets[cur_idx].metadata['content_font'])
58
+ continue
59
+
60
+ # if current snippet's font size > previous section's content but less tha previous section's heading than also make a new
61
+ # section (e.g. title of a pdf will have the highest font size but we don't want it to subsume all sections)
62
+ metadata={'heading':s[0], 'content_font': 0, 'heading_font': s[1]}
63
+ metadata.update(data.metadata)
64
+ semantic_snippets.append(Document(page_content='',metadata=metadata))
65
+ cur_idx += 1
66
+
67
+ return [{"text": doc.page_content, "metadata": doc.metadata} for doc in semantic_snippets]
scripts/extract_text.py CHANGED
@@ -1,10 +1,12 @@
1
  from pathlib import Path
2
- from plugin.pdf import extract_text
3
 
4
  def main():
5
  pdf = Path(__file__).parents[1] / "resources" / "statics.pdf"
6
- text = extract_text(pdf)
7
- # print(text)
 
 
8
 
9
  if __name__ == "__main__":
10
  main()
 
1
  from pathlib import Path
2
+ from plugin.pdf import get_semantic_snippets
3
 
4
  def main():
5
  pdf = Path(__file__).parents[1] / "resources" / "statics.pdf"
6
+ text = get_semantic_snippets(pdf)
7
+ for t in text:
8
+ print(len(t["text"]))
9
+
10
 
11
  if __name__ == "__main__":
12
  main()