I have this code which reads images. I want you to make it pdf readable. Multipager pdf readable. Give me the completely correct code

import json
import boto3
import os
from pdf2image import convert_from_path
import cv2
from idxp_ocr.ocr import (
    TextractAgent,
    TextractFeatureType,
)
import pandas as pd
bedrock_runtime = boto3.client(
            service_name='bedrock-runtime',
            aws_access_key_id='AKIAQ6TT5',
            aws_secret_access_key='dSm3oQUIOj8Hw',
            # region_name='us-west-2'

            region_name="us-east-1"
        )

ocr_agent = TextractAgent(region_name='us-east-2',
                          aws_access_key_id='AKBNB',
                          aws_secret_access_key='W7qLTA',
                         ocr_image_decode_type="jpeg")

def fix_invalid_json(json_data):
    try:
        if not is_json(json_data):
            if can_parse_json(json_data):
                json_data = repair_json(json_data)
            else:
                json_data = repair_exquoted_json(json_data)
                json_data = repair_json(json_data)
        return json_data
    except Exception as e:
        json_data_new = json_data[:json_data.find('"line_items"')]+ '"line_items":"None"}'
        if can_parse_json(json_data_new):
            return repair_json(json_data_new)
        message = f"Exception in fix_invalid_json function, while standardizing the response content: {e}"


prompt_IN = """
Please take a moment to breathe deeply. Next, Analyze this invoice image and extract all the visible entities from the Invoice_Text. Return JSON in a single line without whitespaces, with all values as strings.
Invoice_Text: "%(invoice_txt)s"
The output should be formatted as a JSON instance that conforms to the JSON schema below.

Here is the output schema:
Objective: Extract detailed information about a vendor based on the specified categories and entities.

---

Instructions:

General Information:

	Vendor Name: Identify the official name of the vendor.
	Vendor Type: Classify the vendor as a supplier, contractor, consultant, etc.
	Vendor Category: Specify the category such as IT, facilities, logistics, etc.
	Business Address: Provide the complete address of the vendor.
	Contact Person(s): List the name, title, email, and phone number of the primary contact person(s).
	Website: Include the vendor's website URL if available.
	Year of Establishment: Note the year the vendor was established.
	Business Description: Provide a brief overview of the vendor's business operations.
	CIN Number: Extract the Corporate Identification Number.
	Constitution Type: Identify if the vendor is a Firm, Company, Proprietor, HUF, etc.
	Private or Public Limited: Specify if the vendor is a private or public limited company.
	If Public Limited, Average Share Price for the Month: Extract the average share price if applicable.
	PAN Number: Extract the Permanent Account Number.
	GSTIN Number: Extract the Goods and Services Tax Identification Number.
	Company Registration Numbers: List any relevant registration numbers.
	Registration Country: Identify the country where the vendor is registered.
	State: Specify the state of registration.
	
Business Information:

	Products/Services Offered: ""/List the main products or services provided by the vendor.
	Industry/Sector: ""/ Identify the industry or sector the vendor operates in.
	Business Model: ""/ Specify the business model (e.g., manufacturing, trading, service-based).
	Key Customers: ""/List significant customers of the vendor.
	Key Partnerships/Collaborations: ""/ Identify any notable partnerships or collaborations.
	Quality Certifications: ""/ List any quality certifications (e.g., ISO, Six Sigma).
	Awards/Recognition: ""/ Note any awards or recognitions received by the vendor.
	
Financial Information:
	
	Annual Turnover : ""/Provide the annual turnover for the last years.
	Profit/Loss Statement : ""/Summarize the profit/loss statements for the last years.
	Balance Sheet : ""/Extract key figures from the balance sheets for the last years.
	Cash Flow Statement : ""/Summarize the cash flow statements for the last years.
	Debt-to-Equity Ratio : ""/Extract the current debt-to-equity ratio.
	Current Ratio: ""/Provide the current ratio.
	Return on Investment (ROI): ""/Extract the ROI.
	Any other Relevant Business Ratio: ""/Include any other significant financial ratios.
	
Regulatory/Compliance Information:
	
	Licenses and Permits: ""/ List relevant licenses and permits held by the vendor.
	Compliance Certifications: ""/Identify any compliance certifications (e.g., GDPR, HIPAA).
	Industry-specific Regulations: ""/Note any industry-specific regulations (e.g., FDA, OSHA).
	Anti-Bribery and Corruption Policy: ""/Extract details of the policy if available.
	Code of Conduct Policy: ""/Provide information on the code of conduct.
	Data Protection Policy: ""/Extract details of the data protection policy.
	Information Security Policy: ""/Note the information security policy.
	Compliance Officer: ""/Provide the name, title, and contact information of the compliance officer.
	
ESG/CSR Environmental Policy:

	Sustainability Initiatives: ""/List initiatives related to sustainability (e.g., renewable energy, recycling).
	Social Responsibility Initiatives: ""/Identify social responsibility initiatives (e.g., community development, charitable donations).
	Governance Structure: ""/Describe the governance structure (e.g., board of directors, executive team).
	Diversity and Inclusion Policy: ""/Extract details of the diversity and inclusion policy.
	Human Rights Policy: ""/Note the human rights policy.
	Supply Chain Transparency: ""/Provide information on supply chain transparency.
	ESG/CSR Reporting: ""/Include details of ESG/CSR reporting if applicable.
	
Employee/Labour Information:

	Total Number of Employees: ""/Provide the total number of employees.
	Employee Turnover Rate: ""/Extract the employee turnover rate.
	Training and Development Programs: ""/List training and development programs offered.
	Diversity and Inclusion Metrics: ""/Provide metrics related to diversity and inclusion (e.g., gender, ethnicity).
	Labour Union Affiliation: ""/Note any labour union affiliations.
	Employee Benefits: ""/List employee benefits (e.g., health insurance, retirement plans).
	Workplace Safety Policy: ""/Extract details of the workplace safety policy.
	Labour Laws Compliance: ""/Provide information on compliance with labour laws (e.g., minimum wage, working hours).
	
Geographic Presence:

	Global Footprint: ""/List countries where the vendor has operations.
	Regional Offices and Distribution Centers: ""/Identify regional offices and distribution centers.
	
Others:

	Insurance Coverage: ""/Provide details of insurance coverage (e.g., liability, property).
	Business Continuity Plan: ""/Extract information on the business continuity plan.
	Disaster Recovery Plan: ""/Note the disaster recovery plan.
	Cybersecurity Measures: ""/Provide details of cybersecurity measures.
	Subcontracting Policy: ""/Extract the subcontracting policy.
	Conflict of Interest Policy: ""/Note the conflict of interest policy.
	Latest News Feed: ""/Include any relevant news updates.
	Awards and Recognition: ""/List any additional awards and recognitions.

"""



system_prompt="""You are an AI visual assistant that can analyze a single invoice image. You receive a block of text, which are Invoice_Text, describing the same invoice image you are observing. In addition, You must do the extraction for entites using Invoice_Text. 

The task is to use the provided Invoice_Text information, do the extraction using the image, and provide the output in pure JSON without any additional info or formatting like ```JSON, etc. Return JSON in a single line without whitespaces.

Importantly, while returning the data do not return partial answers or meaningless answers, and try to extract all visible entities available with the help of Invoice Text and the same image. additionally, do not repeat the line items. It is okay to not answer all the entities asked for.

To answer such questions, one should first understand the visual content, and Invoice_Text, then based on the background knowledge, answer the user's request. Always answer as if you are directly looking at the image. Do not repeat the answer while answering.

Extraction from Table is of paramount importance, you will be penalized if values are extracted from table headers that are not relevant.
"""

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to run a multimodal prompt with Anthropic Claude (on demand) and InvokeModel.
"""
from tqdm.autonotebook import tqdm
import json
import logging
import base64
import boto3
import time
import os
from botocore.exceptions import ClientError
# import pydantic_parser_IN
import pandas as pd
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
import re
import json
def     run_multi_modal_prompt(bedrock_runtime, model_id, messages, max_tokens, sys_prompt):
    """
    Invokes a model with a multimodal prompt.
    Args:
        bedrock_runtime: The Amazon Bedrock boto3 client.
        model_id (str): The model ID to use.
        messages (JSON) : The messages to send to the model.
        max_tokens (int) : The maximum  number of tokens to generate.
    Returns:
        None.
    """

    body = json.dumps(
        {
            "anthropic_version": "bedrock-2023-05-31",
            "max_tokens": max_tokens,
            "messages": messages,
            "temperature" : 0,
            "top_p" :0.1,
            "top_k": 1,
            "system": sys_prompt   
            }
    )

    response = bedrock_runtime.invoke_model(
        body=body, modelId=model_id)
    # response = bedrock_runtime.converse(
    # modelId=model_id,
    # body=body)
# )
#     response = bedrock_runtime.invoke_model (
#     modelId=model_id,
#     body=body
# )
    response_body = json.loads(response.get('body').read())

    return response_body


def get_response(image_path, textract_out):
    """
    Entrypoint for Anthropic Claude multimodal prompt example.
    """

    try:
        # model_id = 'anthropic.claude-3-sonnet-20240229-v1:0'
        model_id='anthropic.claude-3-5-sonnet-20240620-v1:0'
        max_tokens = 3000
        input_image = image_path
        
        ocred_text = ' '.join([str(i) for i in textract_out.text])
        input_text = prompt_IN%{'invoice_txt':ocred_text}
        # input_text= pydantic_parser_IN.get_prompt(prompt_IN)
 
        # Read reference image from file and encode as base64 strings.
        with open(input_image, "rb") as image_file:
            content_image = base64.b64encode(image_file.read()).decode('utf8')
            # content_image= base64.standard_b64encode(image_file.read()).decode('utf8')

        message = {"role": "user",
             "content": [
                {"type": "image", "source": {"type": "base64",
                    "media_type": "image/jpeg", "data": content_image}},
                {"type": "text", "text": input_text}
                ]}

    
        messages = [message]

        response =    run_multi_modal_prompt(
            bedrock_runtime, model_id, messages, max_tokens,system_prompt)

        # print(json.dumps(response, indent=4))
        return response

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))

def fix_invalid_json_claude(invalid_json,json_parse_error):
    try:
        # model_id = 'anthropic.claude-3-sonnet-20240229-v1:0'
        model_id='anthropic.claude-3-5-sonnet-20240620-v1:0'
        max_tokens = 3000

        input_text = invalidjson_prompt%{'invalid_json':invalid_json,'json_parse_error':json_parse_error}


        message = {"role": "user",
                "content": [
                {"type": "text", "text": input_text}
                ]}


        messages = [message]

        response =    run_multi_modal_prompt(
            bedrock_runtime, model_id, messages, max_tokens,system_prompt)

        # print(json.dumps(response, indent=4))
        return response

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))

              

file_name = []
response_usage_ip = []
response_usage_op = []
res_time = []
error_filename=[]
model_output=[]
df=pd.DataFrame()
base_path = '/home/ritik1s/Desktop/bbox_issues/temp_GPT/image/'
json_output='/home/ritik1s/Desktop/bbox_issues/temp_GPT/img/'
# images = convert_from_path('/home/vinothkumar/Data_Analysis/Book_My_show/pdf/I240118003 98_2_M_BO-IC518YNU_P_BO-IC518YNULWA12614.pdf')

for i,file_name in enumerate(os.listdir(base_path)):
        try:
            file_name = file_name.replace('.txt','')
            print('processing :',file_name,"  count : ",str(i))
            file_pth = os.path.join(base_path,file_name)
            textract_pth = os.path.join(base_path.replace('images','textract_output'),file_name+'.csv')
            if  os.path.exists(textract_pth):
                textract_out = pd.read_csv(textract_pth)
            else:
                # img = cv2.imread(file_pth)
                textract_out = ocr_agent.detect(file_pth, return_only_df=True)
            response = get_response(file_pth,textract_out)
            print(response['content'][0]['text'])
            responses=response['content'][0]['text']
            json_data = json.loads(responses)
            json_file_path = str(file_pth.split("/")[-1]) + ".json"
            with open(f'{json_output}/{json_file_path}', "w") as json_file:
                json.dump(json_data, json_file)    
        
        except Exception as e:
            pass
        # data={'file_name': file_name, 'Model_output': model_output, 'input_tokens': response_usage_ip, 'output_tokens': response_usage_ip, 'res_time':res_time}