File size: 12,697 Bytes
79ac2cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82a6c52
79ac2cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82a6c52
79ac2cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
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