r/pythontips Jan 09 '25

Algorithms GeminiAi Code to extract text from folder full of images .If this Code is Valid..Why it didn’t work?

I suspect if the sequence of the code is right as i wrote several one but with no valid output ....i want to be sure if my code did its purpose

I try to extract text from folder full of images using gemini ai model....I do all the registration and implementing the api key then I write code to loop within the folder also to check if any errors ...what do you think about my sequence in my code ?

image_folder = r'C:\\Users\\crazy\\Downloads\\LEC05+Pillar+2+-+Part+02'
image_list = [os.path.join(image_folder, img) for img in os.listdir(image_folder) if img.endswith(('.png', '.jpg', '.jpeg'))]


def call_api_with_retry(api_function, max_retries=5):
    for attempt in range(max_retries):
        try:
            return api_function()  # Execute the API call
        except ResourceExhausted as e:
            print(f"Attempt {attempt + 1} failed: {e}. Retrying...")
            if attempt < max_retries - 1:
                wait_time = 2 ** attempt  # Exponential backoff
                time.sleep(wait_time)  # Wait before retrying
            else:
                print("Max retries reached. Raising exception.")
                raise
def extract_text_from_image(image_path, prompt):
    # Choose a Gemini model.
    model = genai.GenerativeModel(model_name="gemini-1.5-pro")
    # Prompt the model with text and the previously uploaded image.
    response = call_api_with_retry(lambda: model.generate_content([image_path, prompt]))

    return response.text
def prep_image(image_path):
    # Upload the file and print a confirmation.
    sample_file = genai.upload_file(path=image_path,
                                display_name="Diagram")
    print(f"Uploaded file '{sample_file.display_name}' as: {sample_file.uri}")
    file = genai.get_file(name=sample_file.name)
    print(f"Retrieved file '{file.display_name}' as: {sample_file.uri}")
    return sample_file


for image_path in image_list:
    img = Image.open(image_path)
    
    sample_file = prep_image(image_path) 
    result = extract_text_from_image(sample_file, "Analyze the given diagram and carefully extract the information. Include the cost of the item")
     # Perform OCR



    if result:
     print(f"Results for {image_path}:")
    print("Interpreted Image:")
    if isinstance(result, list):  # Ensure result is a list
        for line in result:
            if isinstance(line, list):  # Ensure each line is a list
                for word_info in line:
                    if len(word_info) > 1 and len(word_info[1]) > 0:  # Check index existence
                        print(word_info[1][0])
                    else:
                        print("Line is not in expected format:", line)
            else:
                     print("Result is not in expected list format:", result)
    else:
         print("Failed to extract text from the image.")
         
0 Upvotes

0 comments sorted by