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:
Assistant
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.
"""
To make the code capable of converting a PDF document into a multi-page PDF reading and text extraction using OCR, you need to first convert each page in the PDF into an image, then run OCR on each image, and finally consolidate the text data. Below is a revised version of your code to achieve this goal:
import json
import boto3
import os
from pdf2image import convert_from_path
import cv2
from idxp_ocr.ocr import TextractAgent
import pandas as pd
import base64
import logging
from botocore.exceptions import ClientError
# Setup logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
# AWS Clients
bedrock_runtime = boto3.client(
service_name='bedrock-runtime',
aws_access_key_id='AKIAQ6TT5',
aws_secret_access_key='dSm3oQUIOj8Hw',
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 convert_pdf_to_images(pdf_path):
# Convert PDF document to a list of images (one per page)
images = convert_from_path(pdf_path)
return images
def extract_text_from_images(images):
# Extract text from each image using OCR
text_data = []
for img in images:
textract_out = ocr_agent.detect(img, return_only_df=True)
text_data.append(' '.join([str(i) for i in textract_out.text]))
return text_data
def run_multi_modal_prompt(bedrock_runtime, model_id, messages, max_tokens, sys_prompt):
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_body = json.loads(response.get('body').read())
return response_body
def get_response(image_path, textract_out, system_prompt, prompt_template):
try:
model_id = 'anthropic.claude-3-5-sonnet-20240620-v1:0'
max_tokens = 3000
ocred_text = ' '.join([str(i) for i in textract_out.text])
input_text = prompt_template % {'invoice_txt': ocred_text}
with open(image_path, "rb") as image_file:
content_image = base64.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
)
return response
except ClientError as err:
message = err.response["Error"]["Message"]
logger.error("A client error occurred: %s", message)
def process_pdf(pdf_path, system_prompt, prompt_template):
images = convert_pdf_to_images(pdf_path)
all_extracted_data = []
for image in images:
# Save image to a temporary file
temp_image_path = 'temp_image.jpeg'
image.save(temp_image_path, 'JPEG')
textract_out = ocr_agent.detect(temp_image_path, return_only_df=True)
response = get_response(temp_image_path, textract_out, system_prompt, prompt_template)
if response:
try:
extracted_text = response['content'][0]['text']
json_data = json.loads(extracted_text)
all_extracted_data.append(json_data)
except Exception as e:
logger.error("Error processing page: %s", e)
return all_extracted_data
# Example usage
pdf_path = '/path/to/your/pdf_file.pdf'
system_prompt = "<your system prompt here>"
prompt_template = "<your prompt template here with %(invoice_txt)s>"
extracted_data = process_pdf(pdf_path, system_prompt, prompt_template)
print(extracted_data)
Explanation:
PDF to Image Conversion: The convert_pdf_to_images function converts each page of a PDF into an image.
OCR on Images: The extract_text_from_images function uses the OCR agent to extract text from each page image.
Handle Multiple Pages: In the process_pdf function, each PDF page is handled as an individual image, and the extracted text is processed together.
Save Temporary Images: A temporary image file is used to facilitate sending images for OCR processing.
Output JSON: Each page's OCR content is processed to extract structured data in JSON format.
Ensure you replace the placeholders with actual prompt text and other variable data according to your application's requirements.