autoadder.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import json
  2. import base64
  3. import requests
  4. import googlesearch
  5. import google_images_search
  6. from .validator import barcode_validator
  7. from .exception import bad_request_exception
  8. from .exception import autoadder_exception
  9. class autoadder:
  10. def __init__(self, apikey: str, engine: str) -> None:
  11. self.__apikey = apikey
  12. self.__engine = engine
  13. def __images(self) -> object:
  14. return google_images_search.GoogleImagesSearch(
  15. self.__apikey,
  16. self.__engine
  17. )
  18. def __search(self, phrase: str) -> object:
  19. for count in googlesearch.search(phrase, advanced= True):
  20. return count
  21. return phrase
  22. def __check_barcode(self, barcode: str) -> None:
  23. if barcode_validator(barcode).invalid:
  24. raise bad_request_exception("Invalid barcode")
  25. def __image_request(self, source: str) -> str:
  26. request = requests.get(source)
  27. if not request.ok or not "Content-Type" in request.headers:
  28. raise bad_request_exception("Can nor fetch image")
  29. image = request.content
  30. encoded = base64.b64encode(image)
  31. extension = request.headers["Content-Type"]
  32. return encoded, extension
  33. def find(self, barcode: str) -> dict:
  34. self.__check_barcode(barcode)
  35. title = self.__search(barcode).title
  36. description = title
  37. author = "Somebody"
  38. image = ""
  39. image_type = ""
  40. try:
  41. image_search = self.__images()
  42. image_search.search(search_params = {
  43. "q": barcode,
  44. "num": 1,
  45. "filetype": "jpg"
  46. })
  47. images = image_search.results()
  48. except Exception as error:
  49. raise autoadder_exception("Google API not work. Check API key.")
  50. if len(images) > 0:
  51. image, image_type = self.__image_request(images[0].url)
  52. splited = title.split(" ")
  53. if len(splited) > 3:
  54. title = " ".join(splited[0:3])
  55. return {
  56. "title": title,
  57. "description": description,
  58. "author": author,
  59. "barcode": barcode,
  60. "image": image,
  61. "image_type": image_type
  62. }