import_references.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import requests
  2. import sys
  3. import os
  4. import re
  5. if __name__ == '__main__':
  6. if len(sys.argv) != 2:
  7. print(f"Usage: {sys.argv[0]} <reference file>.bib")
  8. if not os.path.isfile(sys.argv[1]):
  9. print(f"Not a valid file: {sys.argv[1]}")
  10. data = ''
  11. with open(sys.argv[1], 'r') as f:
  12. data = f.read()
  13. matches = re.findall(r'@([A-Z]+){([0-9]+)[},]', data, re.IGNORECASE | re.MULTILINE)
  14. if matches is None:
  15. print(f"Nothing to import")
  16. records = set()
  17. imports = set()
  18. for match in matches:
  19. record, label = match
  20. if record.lower() == 'import' and label.isdigit():
  21. imports.add(label)
  22. else:
  23. records.add(label)
  24. append = ''
  25. for label in imports:
  26. if label in records:
  27. continue
  28. req = requests.get(
  29. f"https://ieeexplore.ieee.org/rest/search/citation/format?recordIds={label}&download-format=download-bibtex",
  30. headers={
  31. 'Accept': 'application/json',
  32. 'Referer': 'https://ieeexplore.ieee.org/document/' + label
  33. }
  34. )
  35. req.raise_for_status()
  36. bibtex = req.json().get('data')
  37. if bibtex:
  38. append += bibtex + '\n'
  39. print(f"Imported {label} from IEEE Xplore")
  40. else:
  41. print(f"Failed to import {label} from IEEE Xplore")
  42. data = re.sub("@IMPORT{[0-9]+}", r'', data)
  43. data += append
  44. data = data.replace('\r\n', '\n')
  45. data = re.sub("@IMPORT{[0-9]+}", r'', data)
  46. data = re.sub(r"[\n]{3,}", r'\n\n', data)
  47. with open(sys.argv[1], 'w') as f:
  48. f.write(data)