Coverage for src/crawler/by_source/bdim_crawler.py: 8%

232 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-23 14:47 +0000

1import re 

2 

3import lingua 

4import regex 

5from bs4 import BeautifulSoup, Tag 

6from lingua import LanguageDetectorBuilder 

7from ptf.cmds.xml.jats.builder.references import ( 

8 # ContribAuthor, 

9 get_all_authors_xml, 

10 get_article_title_xml, 

11 get_ext_link_xml, 

12 get_publisher_xml, 

13 get_source_xml, 

14 get_volume_xml, 

15 get_year_xml, 

16) 

17from ptf.cmds.xml.jats.jats_parser import parse_mixed_citation_into_ref 

18from ptf.cmds.xml.xml_utils import escape 

19from ptf.model_data import ( 

20 ArticleData, 

21 create_abstract, 

22 create_articledata, 

23 create_contributor, 

24 create_extid, 

25 create_issuedata, 

26) 

27 

28from crawler.abstract_crawlers.matching_crawler import MatchingCrawler 

29from crawler.utils import add_pdf_link_to_xarticle 

30 

31 

32class BdimCrawler(MatchingCrawler): 

33 source_name = "Biblioteca Digitale Italiana di Matematica" 

34 source_domain = "BDIM" 

35 source_website = "http://www.bdim.eu" 

36 headers = {"accept_encoding": "utf-8", "cookie": "lingua=en; matematica=tex"} 

37 

38 title_corrections = { 

39 "RLINA_1965_8_39_5_a17": "Eventi fasici nel midollo spinale quali prove di inibizione presinaptica durante il sonno desincronizzato", 

40 "RLINA_1973_8_55_6_a0": "Complementarity between nilpotent selfmappings and periodic autohomeomorphisms.", 

41 "RLINA_1973_8_55_6_a2": "Sur une extension du lemme de Green.", 

42 "RLINA_1979_8_67_1-2_a6": "On the existence o f an unbounded connected set of solutions for nonlinear equations in Banach spaces.", 

43 "RLINA_1972_8_52_2_a5": "Sul carattere proiettivo del rapporto plurisezionale.", 

44 "RLINA_1980_8_69_1-2_a6": "A note on a variational formulation of the Einstein equations for thermo-elastic materials.", 

45 } 

46 

47 issue_href = r"\?id=(?P<col>\w+)(?P<issue>_\d{1,4})" 

48 

49 _language_detector_builder = LanguageDetectorBuilder.from_languages( 

50 lingua.Language.ENGLISH, lingua.Language.FRENCH, lingua.Language.ITALIAN 

51 ) 

52 

53 def __init__(self, *args, **kwargs): 

54 super().__init__(*args, **kwargs) 

55 

56 def parse_collection_content(self, content): 

57 """ 

58 Parse the HTML page of Annals of Math and returns a list of xissue. 

59 Each xissue has its pid/volume/number/year metadata + its url 

60 """ 

61 soup = BeautifulSoup(content, "html.parser") 

62 xissues = [] 

63 

64 reg_issue = regex.compile(self.issue_href) 

65 

66 issue_nodes = [] 

67 for issue in soup.select("div.listafascicoli a"): 

68 href = issue.get("href") 

69 if isinstance(href, str) and reg_issue.search(href): 

70 issue_nodes.append(issue) 

71 

72 for issue_node in issue_nodes: 

73 # issue_text = issue_node.get_text() 

74 

75 part_issue = issue_node.get("href").split("_") 

76 volume = part_issue[-2] 

77 number = part_issue[-1] 

78 year = part_issue[1] 

79 serie = part_issue[2] 

80 link = "/item" + issue_node.get("href") 

81 xissue = self.create_bdim_xissue(link, serie, volume, number, year) 

82 if xissue: 

83 xissues.append(xissue) 

84 

85 return xissues 

86 

87 def get_year(self, year): 

88 if "/" in year: 

89 year = year.split("/")[0] 

90 

91 return year 

92 

93 def create_bdim_xissue(self, url, serie, volume, number, dates): 

94 year = dates.replace("/", "-") 

95 

96 xissue = create_issuedata() 

97 xissue.pid = f"{self.collection_id}_{year}_{serie}_{volume}_{number}" 

98 xissue.fyear = int(year) 

99 xissue.volume = volume 

100 xissue.number = number 

101 xissue.vseries = serie 

102 xissue.url = self.source_website + url 

103 

104 return xissue 

105 

106 def parse_issue_content(self, content, xissue): 

107 soup = BeautifulSoup(content, "html.parser") 

108 article_nodes = soup.find_all("div", {"class": "referenza"}) 

109 

110 for index_article, article_node in enumerate(article_nodes): 

111 article_link_node = article_node.find("a", text="full entry") 

112 if article_link_node: 

113 url = article_link_node.get("href") 

114 xarticle = create_articledata() 

115 xarticle.pid = "a" + str(index_article) 

116 xarticle.url = self.source_website + url 

117 

118 xissue.articles.append(xarticle) 

119 

120 def parse_article_content(self, content, xissue, xarticle, url): 

121 """ 

122 Parse the content with Beautifulsoup and returns an ArticleData 

123 """ 

124 soup = BeautifulSoup(content, "html.parser") 

125 # TITLE 

126 title_node = soup.select_one("span.titolo") 

127 if not title_node: 

128 raise ValueError("Couldn't find article title") 

129 xarticle.title_tex = title_node.get_text() 

130 

131 # Lang 

132 if "(Italian)" in title_node.parent.text: 

133 xarticle.lang = "it" 

134 elif "(English)" in title_node.parent.text: 

135 xarticle.lang = "en" 

136 # Authors 

137 reg_author_link = regex.compile(r"\?testo=\w+") 

138 text_author_bloc = soup.select_one("div.referenza p") 

139 if text_author_bloc: 

140 for link in text_author_bloc.select("a"): 

141 href = link.get("href") 

142 if isinstance(href, str) and reg_author_link.search(href): 

143 contrib_node = link.select_one("span.autore") 

144 if contrib_node is not None: 

145 surname_node = link.select_one("span.cognome") 

146 firstname_node = link.select_one("span.nome") 

147 author = create_contributor(role="author") 

148 

149 if surname_node is not None: 

150 surname = surname_node.get_text() 

151 author["last_name"] = surname 

152 

153 if firstname_node is not None: 

154 firstname = firstname_node.get_text() 

155 author["first_name"] = firstname 

156 

157 if not firstname_node or not surname_node: 

158 string_name = contrib_node.get_text() 

159 author["string_name"] = string_name 

160 

161 xarticle.contributors.append(author) 

162 

163 # ABSTRACT 

164 abstract_section_node = soup.select_one("div.sunto") 

165 if abstract_section_node: 

166 abstract = str(abstract_section_node.get_text()) 

167 

168 xarticle.abstracts.append( 

169 create_abstract(value_tex=abstract, lang=self.detect_language(abstract)) 

170 ) 

171 

172 # PDF 

173 pdf_url = soup.find_all("a", text="pdf") 

174 if len(pdf_url) > 0: 

175 pdf_url = self.source_website + pdf_url[0].get("href") 

176 add_pdf_link_to_xarticle(xarticle, pdf_url) 

177 

178 # PAGES 

179 pages = soup.select_one("span.pagine") 

180 if pages: 

181 pages_to = re.compile(r"(\(?\d+\)?)?-?(\(?\d+\)?)").search(pages.get_text()) 

182 if pages_to: 

183 parts = pages_to[0].split("-") 

184 first_page = parts[0].replace("(", "").replace(")", "") 

185 if len(parts) > 1: 

186 last_page = parts[1].replace("(", "").replace(")", "") 

187 xarticle.lpage = last_page 

188 xarticle.fpage = first_page 

189 

190 # Biblio 

191 bibitems_tags = soup.select("div.biblio div.bibitem") 

192 xarticle.bibitems = [self.parse_ref(item) for item in bibitems_tags] 

193 

194 # metadata 

195 bdim_mr_url = "http://www.ams.org/mathscinet-getitem?mr=" 

196 bdim_zbl_url = "https://zbmath.org/?q=an:" 

197 medata_bloc = soup.select_one("div.referenza > p") 

198 if not medata_bloc: 

199 raise ValueError("metadata_bloc cannot be found") 

200 

201 zbl_id = medata_bloc.select_one(f"a[href^='{bdim_zbl_url}']") 

202 

203 if zbl_id: 

204 extid_href = zbl_id.get("href") 

205 if isinstance(extid_href, str): 

206 extid = create_extid("zbl-item-id", extid_href.removeprefix(bdim_zbl_url)) 

207 xarticle.extids.append(extid) 

208 

209 mr_id = medata_bloc.select_one(f"a[href^='{bdim_mr_url}']") 

210 if mr_id: 

211 extid_href = mr_id.get("href") 

212 if isinstance(extid_href, str): 

213 extid = create_extid("mr-item-id", extid_href.removeprefix(bdim_mr_url)) 

214 xarticle.extids.append(extid) 

215 

216 if xarticle.pid in self.title_corrections: 

217 xarticle.title_tex = self.title_corrections[xarticle.pid] 

218 

219 content = self.download_file(url, headers={"cookie": "lingua=it; matematica=tex"}) 

220 xarticle = self.parse_article_content_bdim_it(content, xissue, xarticle, url) 

221 return xarticle 

222 

223 def parse_article_content_bdim_it(self, content, xissue, xarticle: ArticleData, url): 

224 soup = BeautifulSoup(content, "html.parser") 

225 

226 # trans abstract 

227 abstract_section_node = soup.select_one("div.sunto") 

228 if abstract_section_node: 

229 abstract = str(abstract_section_node.get_text()) 

230 if xarticle.abstracts[0]["value_tex"] != abstract: 

231 xarticle.abstracts.append( 

232 create_abstract(value_tex=abstract, lang=self.detect_language(abstract)) 

233 ) 

234 

235 # Trans_title 

236 

237 trans_title_node = soup.select_one("span.titolo_trad") 

238 if trans_title_node: 

239 trans_title = self.create_trans_title( 

240 resource_type="article", 

241 xresource_lang=xarticle.lang, 

242 lang="en" if xarticle.lang == "it" else "it", 

243 title_str=trans_title_node.get_text(), 

244 ) 

245 xarticle.titles.append(trans_title) 

246 return xarticle 

247 

248 def parse_ref(self, item: Tag): 

249 value_xml = "" 

250 # First pass : we create an semi-complete XML Jats string, except for the authors 

251 # that we store inside authors_list to be serialized at the end 

252 authors_list = [] 

253 for c in item.children: 

254 c_text = escape(c.text) 

255 if isinstance(c, str): 

256 value_xml += c_text 

257 continue 

258 

259 if not isinstance(c, Tag): 

260 raise NotImplementedError("bibitem_tag is not a Tag or a string") 

261 

262 if c.name == "a": 

263 a_xml, is_badge = self.parse_a_tag(c) 

264 if is_badge: 

265 value_xml = regex.sub(r" \| $", "", value_xml) 

266 value_xml += a_xml 

267 continue 

268 

269 child_class = c.get("class") 

270 if not child_class: 

271 value_xml += c_text 

272 elif "bautore" in child_class: 

273 # TODO : parse firstname and lastname 

274 author_data, author_xml = self.parse_biblio_author_tag(c, len(authors_list)) 

275 authors_list.append(author_data) 

276 value_xml += author_xml 

277 

278 elif "titolo" in child_class: 

279 value_xml += get_article_title_xml(c_text) 

280 elif "rivista" in child_class: 

281 value_xml += get_source_xml(c_text) 

282 elif "anno" in child_class: 

283 value_xml += get_year_xml(c_text) 

284 elif "volume" in child_class: 

285 value_xml += get_volume_xml(c_text) 

286 elif "publisher" in child_class: 

287 value_xml += get_publisher_xml(c_text) 

288 else: 

289 # booktitle 

290 value_xml += c_text 

291 

292 # In order to have a valid Jats xml, we have to group all authors into the person-group xml tag. 

293 authors_occurence = regex.compile(r"{author_\d}").findall(value_xml) 

294 if len(authors_occurence) > 0: 

295 first_author = value_xml.index(authors_occurence[0]) 

296 last_author = value_xml.index(authors_occurence[-1]) + len(authors_occurence[-1]) 

297 value_xml = ( 

298 value_xml[:first_author] 

299 + get_all_authors_xml(value_xml[first_author:last_author], authors_list) 

300 + value_xml[last_author:] 

301 ) 

302 

303 return parse_mixed_citation_into_ref(value_xml) 

304 # return self.create_crawled_bibitem([*bib_elements, *bib_link_elements]) 

305 

306 def parse_a_tag(self, a_tag: Tag): 

307 a_text = escape(a_tag.text) 

308 href = a_tag.get("href") 

309 if not href: 

310 return a_text, False 

311 elif isinstance(href, list): 

312 raise ValueError("a tag has multiple href values !") 

313 else: 

314 a_type = "uri" 

315 if a_text.startswith("MR "): 

316 a_type = "mr-item-id" 

317 a_text = a_text.removeprefix("MR ") 

318 elif a_text.startswith("Zbl "): 

319 a_type = "zbl-item-id" 

320 a_text = a_text.removeprefix("Zbl ") 

321 elif a_text == "fulltext (doi)": 

322 a_type = "doi" 

323 a_text = a_text.removeprefix("http://dx.doi.org/") 

324 return get_ext_link_xml(escape(href), a_text, a_type), a_type != "uri" 

325 

326 def parse_biblio_author_tag(self, author_tag: Tag, index: int = 0): 

327 value_xml = "" 

328 author_data = {"template_str": ""} 

329 for c in author_tag.children: 

330 c_text = escape(c.text) 

331 if isinstance(c, str): 

332 author_data["template_str"] += c_text 

333 continue 

334 

335 if not isinstance(c, Tag): 

336 raise NotImplementedError("author_tag is not a Tag or a string") 

337 # given name = cognome = prénom 

338 # surname = nome = nom de famille 

339 child_class = c.get("class") 

340 if not child_class: 

341 value_xml += c_text 

342 elif "cognome" in child_class: 

343 c.replace_with("{given_names}") 

344 author_data["given_names"] = c_text 

345 author_data["template_str"] += "{given_names}" 

346 elif "nome" in child_class: 

347 c.replace_with("{surname}") 

348 author_data["surname"] = c_text 

349 author_data["template_str"] += "{surname}" 

350 value_xml += "{author_" + str(index) + "}" 

351 

352 return author_data, value_xml