import io, os
from google.cloud import vision
from PIL import Image

def crop_image(image, text_area):
    """Crops an image to a specified area."""
    return image.crop(text_area)

def detect_text(image_file, credentials_file, text_area):
    """Detects text in an image."""
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_file                 # Authenticates the client

    # Open the image file
    try:
        with open(image_file, 'rb') as f:
            image_data = f.read()
    except FileNotFoundError:
        print(f"Error: File not found: {image_file}")
        return None

    # Crop the image
    image = Image.open(io.BytesIO(image_data))
    cropped_image = crop_image(image, text_area)

    # Send the cropped image to the Google Cloud Vision API for text detection
    client = vision.ImageAnnotatorClient()
    content = io.BytesIO()
    cropped_image.save(content, format='JPEG')
    image = vision.Image(content=content.getvalue())
    response = client.text_detection(image=image)
    texts = response.text_annotations

    # Handle errors
    if response.error.message:
        raise Exception(response.error.message)

    # Return the first detected text as a float
    try:
        print(float(texts[0].description))                                          # Print the detected text
        return float(texts[0].description)
    except IndexError:
        print("No text detected in the image.")
        return None

detect_text('meter_digits.jpg', 'GoogleVisionKeys.json', (270, 195, 720, 280))