utils.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import json
  2. from typing import Optional
  3. import requests
  4. import logging
  5. logger = logging.getLogger(__name__)
  6. SEARCH_URL = "https://openlibrary.org/search.json?title={title}"
  7. ISBN_URL = "https://openlibrary.org/isbn/{isbn}.json"
  8. def get_first(key: str, result: dict) -> str:
  9. obj = ""
  10. if obj_list := result.get(key):
  11. obj = obj_list[0]
  12. return obj
  13. def lookup_book_from_openlibrary(title: str, author: str = None) -> dict:
  14. search_url = SEARCH_URL.format(title=title)
  15. response = requests.get(search_url)
  16. if response.status_code != 200:
  17. logger.warn(f"Bad response from OL: {response.status_code}")
  18. return {}
  19. results = json.loads(response.content)
  20. if len(results.get('docs')) == 0:
  21. logger.warn(f"No results found from OL for {title}")
  22. return {}
  23. top = results.get('docs')[0]
  24. if author and author not in top['author_name']:
  25. logger.warn(
  26. f"Lookup for {title} found top result with mismatched author"
  27. )
  28. return {
  29. "title": top.get("title"),
  30. "isbn": top.get("isbn")[0],
  31. "openlibrary_id": top.get("cover_edition_key"),
  32. "author_name": get_first("author_name", top),
  33. "author_openlibrary_id": get_first("author_key", top),
  34. "goodreads_id": get_first("id_goodreads", top),
  35. "first_publish_year": top.get("first_publish_year"),
  36. }