Intermittent Authentication Issue with Google Cloud Vision API for Text Detection in Production Environment

I’m experiencing an intermittent authentication issue with the Google Cloud Vision API when running in production. The service, uses a service account json file for authentication and then perform text detection API via Python’s ImageAnnotatorClient. This works fine on both localhost and the development server. However, in production, it occasionally fails with an authentication error.

2024-08-18 07:16:35,315 - uvicorn - ERROR - Response Message: 401 Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project. [reason: "ACCESS_TOKEN_EXPIRED" domain: "googleapis.com" metadata {   key: "service"   value: "vision.googleapis.com" } metadata {   key: "method"   value: "google.cloud.vision.v1.ImageAnnotator.BatchAnnotateImages"

Details:

Service Environment: FastAPI service running on a production server (ubuntu vm, python 3.10)

Problem: The API sometimes returns authentication errors. The issue is intermittent but appears only in the production environment.

Working Conditions: The same service account JSON file works without issues on localhost and dev servers.

Additional Context:

  • I have validated that the service account credentials and API configurations are correct.
  • Network issues have been ruled out as the server is capable of making other network requests reliably.

CODE:
Relevant part of the code in the api.

def setup_client(self):
        main_key = Utils.main_key_compile(self.first_key_part_file,self.second_key_part_file,self.third_key_part_file)
        
        # Create a Fernet cipher using the main key
        cipher_suite = Fernet(main_key)

        with open(self.gvk_file_path, "rb") as file:
            encrypted_data = file.read()

        # Read the encrypted content from the JSON file you want to decrypt
        decrypted_data = cipher_suite.decrypt(encrypted_data)

        # client = vision.ImageAnnotatorClient()
        json_str = decrypted_data.decode("utf-8")  # Decode the bytes to a string
        api_key_dict = json.loads(json_str)  # Parse the JSON string into a Python dictionary
        my_credentials = service_account.Credentials.from_service_account_info(api_key_dict)
        self.client = vision.ImageAnnotatorClient(credentials=my_credentials)

    def extract_text_google(self, image):
        success, encoded_image = cv2.imencode('.png', image)
        content = encoded_image.tobytes()
        image = vision.Image(content=content)
        image_context = types.ImageContext(language_hints=["en"])
        max_retries = 2
        retry_delay = 2  # seconds
        for attempt in range(max_retries):
            try:
                response = self.client.text_detection(image=image,image_context=image_context)
                # check if response.text_annotations is empty   
                if len(response.text_annotations) == 0:
                    text_results = {}
                else:
                    text_results = response.text_annotations[0].description
                return text_results

            except google.api_core.exceptions.Unauthenticated as e:
                self.logger.error(f"Authentication error: {e}")
                # Optionally, reinitialize the client here if needed
                self.setup_client()

            except google.api_core.exceptions.GoogleAPIError as e:
                self.logger.error(f"API error: {e}")
                if attempt < max_retries:
                    time.sleep(retry_delay)
                else:
                    raise
            except Exception as e:
                self.logger.error(f"Unexpected error: {e}")
                if attempt < max_retries:
                    time.sleep(retry_delay)
                else:
                    raise

        return {}

Also rarely face the following issue as well

gunicorn[3784527]: google.api_core.exceptions.ServiceUnavailable: 503 failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.181.74:443: Failed to connect to remote host: FD Shutdown

Troubleshooting Steps Taken:

  • Verified that the service account JSON file is correctly configured.
  • Attempted to resolve the issue by creating multiple service accounts, but the problem persists.
  • Ran a simple test on the prod server, by creating a vision client on python and hitting the api with service account credentials, this time continuously received failed authentication.
    TroubleShooting_Simple_API_Hit_Client

I expected that direct call with client should work atleast sometime, since calls from within fastapi service sometimes worked, but this time got authentication issue every single time.

New contributor

Irtiza Yawar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật