bano1 commited on
Commit
ef3301e
·
verified ·
1 Parent(s): 74b7889

Update src/grobid.py

Browse files
Files changed (1) hide show
  1. src/grobid.py +92 -12
src/grobid.py CHANGED
@@ -1,29 +1,109 @@
1
  import requests
2
-
3
-
4
 
5
  GROBID_URL = (
6
- "https://grobid.science-miner.com/api/processFulltextDocument"
7
  )
8
 
9
 
 
 
 
 
 
10
 
11
- def process_pdf(pdf_file):
12
-
13
 
14
  response = requests.post(
15
-
16
  GROBID_URL,
17
-
18
  files={
19
- "input":pdf_file
20
  },
21
-
22
  headers={
23
- "Accept":"application/xml"
24
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  )
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- return response.text
 
1
  import requests
2
+ import xml.etree.ElementTree as ET
 
3
 
4
  GROBID_URL = (
5
+ "https://grobid.science-miner.com/api/processFulltextDocument"
6
  )
7
 
8
 
9
+ def extract_metadata_grobid(pdf_file):
10
+ """
11
+ Extract title, authors and abstract using GROBID.
12
+ Returns a dictionary.
13
+ """
14
 
15
+ pdf_file.seek(0)
 
16
 
17
  response = requests.post(
 
18
  GROBID_URL,
 
19
  files={
20
+ "input": pdf_file
21
  },
 
22
  headers={
23
+ "Accept": "application/xml"
24
+ },
25
+ timeout=60
26
+ )
27
+
28
+ if response.status_code != 200:
29
+ raise Exception("GROBID request failed")
30
+
31
+ root = ET.fromstring(response.text)
32
+
33
+ ns = {
34
+ "tei": "http://www.tei-c.org/ns/1.0"
35
+ }
36
+
37
+ # ------------------------
38
+ # Title
39
+ # ------------------------
40
+
41
+ title = ""
42
+
43
+ title_node = root.find(
44
+ ".//tei:titleStmt/tei:title",
45
+ ns
46
+ )
47
+
48
+ if title_node is not None and title_node.text:
49
+ title = title_node.text.strip()
50
 
51
+ # ------------------------
52
+ # Authors
53
+ # ------------------------
54
+
55
+ authors = []
56
+
57
+ for author in root.findall(".//tei:author", ns):
58
+
59
+ first = author.find(
60
+ ".//tei:forename",
61
+ ns
62
+ )
63
+
64
+ last = author.find(
65
+ ".//tei:surname",
66
+ ns
67
+ )
68
+
69
+ first_name = first.text.strip() if (
70
+ first is not None and first.text
71
+ ) else ""
72
+
73
+ last_name = last.text.strip() if (
74
+ last is not None and last.text
75
+ ) else ""
76
+
77
+ full_name = (
78
+ first_name + " " + last_name
79
+ ).strip()
80
+
81
+ if full_name:
82
+ authors.append(full_name)
83
+
84
+ # ------------------------
85
+ # Abstract
86
+ # ------------------------
87
+
88
+ abstract = ""
89
+
90
+ abs_node = root.find(
91
+ ".//tei:abstract",
92
+ ns
93
  )
94
 
95
+ if abs_node is not None:
96
+
97
+ abstract = " ".join(
98
+ abs_node.itertext()
99
+ ).strip()
100
+
101
+ return {
102
+
103
+ "title": title,
104
+
105
+ "authors": authors,
106
+
107
+ "abstract": abstract
108
 
109
+ }