import json import base64 import requests import googlesearch import google_images_search from .validator import barcode_validator from .exception import bad_request_exception from .exception import autoadder_exception class autoadder: def __init__(self, apikey: str, engine: str) -> None: self.__apikey = apikey self.__engine = engine def __images(self) -> object: return google_images_search.GoogleImagesSearch( self.__apikey, self.__engine ) def __search(self, phrase: str) -> object: for count in googlesearch.search(phrase, advanced= True): return count return phrase def __check_barcode(self, barcode: str) -> None: if barcode_validator(barcode).invalid: raise bad_request_exception("Invalid barcode") def __image_request(self, source: str) -> str: request = requests.get(source) if not request.ok or not "Content-Type" in request.headers: raise bad_request_exception("Can nor fetch image") image = request.content encoded = base64.b64encode(image) extension = request.headers["Content-Type"] return encoded, extension def find(self, barcode: str) -> dict: self.__check_barcode(barcode) title = self.__search(barcode).title description = title author = "Somebody" image = "" image_type = "" try: image_search = self.__images() image_search.search(search_params = { "q": barcode, "num": 1, "filetype": "jpg" }) images = image_search.results() except Exception as error: raise autoadder_exception("Google API not work. Check API key.") if len(images) > 0: image, image_type = self.__image_request(images[0].url) splited = title.split(" ") if len(splited) > 3: title = " ".join(splited[0:3]) return { "title": title, "description": description, "author": author, "barcode": barcode, "image": image, "image_type": image_type }