autoadder.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import json
  2. import googlesearch
  3. import google_images_search
  4. from .validator import barcode_validator
  5. from .exception import bad_request_exception
  6. from .exception import autoadder_exception
  7. class autoadder:
  8. def __init__(self, apikey: str, engine: str) -> None:
  9. self.__apikey = apikey
  10. self.__engine = engine
  11. def __images(self) -> object:
  12. return google_images_search.GoogleImagesSearch(
  13. self.__apikey,
  14. self.__engine
  15. )
  16. def __search(self, phrase: str) -> object:
  17. for count in googlesearch.search(phrase, advanced= True):
  18. return count
  19. def __check_barcode(self, barcode: str) -> None:
  20. if barcode_validator(barcode).invalid:
  21. raise bad_request_exception("Invalid barcode")
  22. def find(self, barcode: str) -> dict:
  23. self.__check_barcode(barcode)
  24. title = self.__search(barcode).title
  25. description = title
  26. author = "Somebody"
  27. try:
  28. image_search = self.__images()
  29. image_search.search(search_params = {
  30. "q": barcode,
  31. "num": 1,
  32. "filetype": "jpg"
  33. })
  34. images = image_search.results()
  35. except Exception as error:
  36. raise autoadder_exception("Google API not work. Check API key.")
  37. if len(images) < 1:
  38. image = ""
  39. else:
  40. image = images[0].url
  41. return {
  42. "title": title,
  43. "description": description,
  44. "author": author,
  45. "barcode": barcode,
  46. "image": image
  47. }