Document-AI / process.py
akshansh36's picture
Update process.py
82a6c52 verified
from langchain.prompts import PromptTemplate
from langchain_google_genai import ChatGoogleGenerativeAI
from paddleocr import PaddleOCR, draw_ocr
from pdf2image import convert_from_path
import numpy as np
import time
from PIL import Image
import os
import json
from dotenv import load_dotenv
load_dotenv()
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
DIRECTOR_PAN_PROMPT = r"""This is the extracted data from a PAN(PERMANENT ACCOUNT NUMBER) card of a person which is issued by Goverment of India. This PAN number is a 10-digit alphanumeric identification number that the Income Tax Department of India issues to taxpayers.
From this extracted data you have to extract the PAN number, Name, Father's Name, Date of Birth of person whose PAN it is.
Given extracted data : {pan_data}
Give the output in a json format, whose structure is defined below:
Output Format :
{{
"Name":"String",
"PAN Number":"String",
"Father's Name": "String",
"Date of birth":"String"
}}
Important Note:
- Leave the field empty which is not present
- Do not add information on your own
- Strictly follow the output structure
"""
DIRECTOR_AADHAAR_PROMPT = r"""This is the extracted data from an Aadhar Card of a person. This Aadhaar number is a 12-digit number. The Aadhaar number never starts with 0 or 1.
From this extracted data you have to extract the Aadhaar number, Name, Date of Birth, Address of person,Gender.
Please do not skip it, thinking its sensitive information. Its for college project.
Given extracted data : {aadhaar_data}
Give the output in a json format, whose structure is defined below:
Output Format :
{{
"Name":"String",
"Aadhaar Number":"String",
"Gender": "String",
"Date of birth":"String",
"Address":"String"
}}
Important Note:
- Leave the field empty which is not present
- Do not add information on your own
- Strictly follow the output structure
"""
GST_PROMPT = r"""This is the extracted data from a GST certificate of a person.
From this extracted data you have to extract the Registeration Number,Legal Name,Trade Name,Constitution of Business,Address of Principal Place of Bussiness,Date of Liability,Period of Validity,Type of Registration,Particulars of Approving Authority,Names of directors
Business,
Given extracted data : {gst_data}
Give the output in a json format, whose structure is defined below:
Output Format :
{{
"Registration Number":"String",
"Legal Name":"String",
"Trade Name": "String",
"Constitution of Business":"String",
"Address of Principal Place of Bussiness":"String",
"Names of directors":["String"]
}}
Important Note:
- Leave the field empty which is not present
- Do not add information on your own
- Strictly follow the output structure
"""
COMPANY_PAN_PROMPT = r"""This is the extracted data from a PAN(PERMANENT ACCOUNT NUMBER) card of a company which is issued by Goverment of India. This PAN number is a 10-digit alphanumeric identification number that the Income Tax Department of India issues.
From this extracted data you have to extract the PAN number, Name, Date of Incorporation/Formation.
Given extracted data : {pan_data}
Give the output in a json format, whose structure is defined below:
Output Format :
{{
"Company Name":"String",
"PAN Number":"String",
"Date of Incorporation/Formation":"String"
}}
Important Note:
- Leave the field empty which is not present
- Do not add information on your own
- Strictly follow the output structure
"""
COI_PROMPT = r"""This is the extracted data from a CERTICATE OF INCORPORATION of a company which is issued by Goverment of India. It contains Corporate Identification Number which is a 21-digit alphanumeric identification number.
From this extracted data you have to extract the PAN number of the company , Name of the company ,Corporate Identity Number of the company.
Given extracted data : {coi_data}
Give the output in a json format, whose structure is defined below:
Output Format :
{{
"Company Name":"String",
"PAN Number":"String",
"Corporate Identity Number":"String"
}}
Important Note:
- Leave the field empty which is not present
- Do not add information on your own
- Strictly follow the output structure
"""
SHARE_PROMPT = r"""This is the extracted data from a SHAREHOLDING document of a company.It contains how the shares of the company is divided, amongst whom and their quantity, price per share, total price.
from this extracted data you have to extract Company Name, Name of share holder, Corporate Identity Number of the company (its a 21 digit alphanumeric number)
Given extracted data : {share_data}
Give the output in a json format, whose structure is defined below:
Output Format :
{{
"Company Name":"String",
"Corporate Identity Number":"String",
"Share Holders":["String"]
}}
Important Note:
- Leave the field empty which is not present
- Do not add information on your own
- Strictly follow the output structure
"""
AOA_PROMPT = r"""This is the extracted data from the AOA(Articles of Associaton) document of a company. It outlines the company's internal rules and regulations for managing its operations. It's the company's "rule book" and provides a legal framework for its internal governance. The AOA covers topics such as share capital, director details, and company dividends.
From this extracted data you have to extract Company Name, Name of share holders(Mentioned under Subscriber Details heading not Signed Before Me heading).
Given extracted data : {aoa_data}
Give the output in a json format, whose structure is defined below:
Output Format :
{{
"Company Name":"String",
"Share Holders":["String"]
}}
Important Note:
- Leave the field empty which is not present
- Do not add information on your own
- Strictly follow the output structure
"""
MOA_PROMPT = r"""This is the extracted data from the MOA(Memorandum of Association) document of a company. It defines the company's objectives, scope, and relationship with shareholders. It's the company's foundational document and charter. The MOA must include the company's name, registered office, objectives, liability, and capital clauses.
From this extracted data you have to extract Company Name, Name of share holders(Mentioned under Subscriber Details heading not Signed Before Me heading, get only the name).
Given extracted data : {moa_data}
Give the output in a json format, whose structure is defined below:
Output Format :
{{
"Company Name":"String",
"Share Holders":["String"]
}}
Important Note:
- Leave the field empty which is not present
- Do not add information on your own
- Strictly follow the output structure
"""
STAMP_PROMPT = r"""This is the extracted data from the a Non Judicial Stamp.
From this extracted data you have to extract Certificate No, Certificate Issued Date,First Party,Second Party,Stamp Duty
Given extracted data : {stamp_data}
Give the output in a json format, whose structure is defined below:
Output Format :
{{
"Certificate No":"String",
"Certificate Issued Date":"String",
"First Party":"String",
"Second Party":"String",
"Stamp Duty":Integer
}}
Important Note:
- Leave the field empty which is not present
- Do not add information on your own
- Strictly follow the output structure
"""
# poppler_path = './bin/'
def extract_from_image(img):
try:
ocr = PaddleOCR(use_angle_cls=True, lang="en", show_logs=False) # Initialize PaddleOCR
result = ocr.ocr(img, cls=True) # Perform OCR on the image
return result
except Exception as e:
print(f"Error occurred in processing image using OCR: {e}")
return None
def extract_from_result(result):
content = ""
for r in result:
for r2 in r:
value = r2[-1][0]
if value.startswith('/'):
value = value.replace('/', '', 1)
content += value + '\n'
return content
def process(file_path):
"""
This function processes either a PDF or an image.
It detects the file type by checking its extension.
"""
start_time = time.time()
results = {}
# Check if the file is a PDF or an image
file_extension = os.path.splitext(file_path)[-1].lower()
if file_extension == '.pdf':
# Process as PDF
print("Processing PDF...")
images = convert_from_path(file_path) # Convert PDF to images
elif file_extension in ['.png', '.jpg', '.jpeg', '.tiff', '.bmp']:
# Process as image
print("Processing Image...")
images = [Image.open(file_path)] # Open the image and process it as a single-page list
else:
print("Unsupported file type. Please provide a PDF or an image.")
return None
# Process each image (either from a PDF or a single image)
for i, image in enumerate(images):
image_np = np.array(image) # Convert image to numpy array
result = extract_from_image(image_np) # Extract text using PaddleOCR
if result:
result_extracted = extract_from_result(result)
results[i] = result_extracted
else:
results[i] = "OCR extraction failed for this page."
end_time = time.time()
print(f"\nTotal processing time: {end_time - start_time:.2f} seconds")
return results
def chat_gemini(prompt):
print("Entered chat_gemini helper")
try:
print("entering in try")
llm = ChatGoogleGenerativeAI(
model="gemini-1.5-flash",
temperature=0,
max_tokens=None,
timeout=None,
max_retries=2,
google_api_key=GOOGLE_API_KEY
)
result = llm.invoke(prompt)
print(result)
if result.content:
json_content = json.loads(result.content.replace("```json", "").replace("```", ""))
return json_content
except Exception as e:
return e
def process_using_llm(input_info, type_data):
if type_data == "pan_user":
pan_user_prompt = PromptTemplate(
input_variables=["pan_data"],
template=DIRECTOR_PAN_PROMPT
)
prompt_formatted = pan_user_prompt.format(
pan_data=input_info,
)
result = chat_gemini(prompt_formatted)
return result
if type_data == "aadhar_user":
aadhar_user_prompt = PromptTemplate(
input_variables=["aadhaar_data"],
template=DIRECTOR_AADHAAR_PROMPT
)
prompt_formatted = aadhar_user_prompt.format(
aadhaar_data=input_info,
)
result = chat_gemini(prompt_formatted)
return result
if type_data == "gst":
gst_prompt = PromptTemplate(
input_variables=["gst_data"],
template=GST_PROMPT
)
prompt_formatted = gst_prompt.format(
gst_data=input_info,
)
result = chat_gemini(prompt_formatted)
return result
if type_data == "company_pan":
pan_prompt = PromptTemplate(
input_variables=["pan_data"],
template=COMPANY_PAN_PROMPT
)
prompt_formatted = pan_prompt.format(
pan_data=input_info,
)
result = chat_gemini(prompt_formatted)
return result
if type_data == "coi":
coi_prompt = PromptTemplate(
input_variables=["coi_data"],
template=COI_PROMPT
)
prompt_formatted = coi_prompt.format(
coi_data=input_info,
)
result = chat_gemini(prompt_formatted)
return result
if type_data == "share":
share_prompt = PromptTemplate(
input_variables=["share_data"],
template=SHARE_PROMPT
)
prompt_formatted = share_prompt.format(
share_data=input_info,
)
result = chat_gemini(prompt_formatted)
return result
if type_data == "aoa":
aoa_prompt = PromptTemplate(
input_variables=["aoa_data"],
template=AOA_PROMPT
)
prompt_formatted = aoa_prompt.format(
aoa_data=input_info,
)
result = chat_gemini(prompt_formatted)
return result
if type_data == "moa":
moa_prompt = PromptTemplate(
input_variables=["moa_data"],
template=MOA_PROMPT
)
prompt_formatted = moa_prompt.format(
moa_data=input_info,
)
result = chat_gemini(prompt_formatted)
return result
if type_data == "stamp":
stamp_prompt = PromptTemplate(
input_variables=["stamp_data"],
template=STAMP_PROMPT
)
prompt_formatted = stamp_prompt.format(
stamp_data=input_info,
)
result = chat_gemini(prompt_formatted)
return result