archana2324 commited on
Commit
ab6d59c
·
verified ·
1 Parent(s): 528d6c5

Create backend.py

Browse files
Files changed (1) hide show
  1. backend.py +60 -0
backend.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import pandas as pd
4
+ from pypdf import PdfReader
5
+ from typing import List, Dict
6
+ from langchain.prompts import PromptTemplate
7
+ from langchain_google_genai import GoogleGenerativeAI
8
+
9
+ os.environ["GOOGLE_API_KEY"] = "AIzaSyCYGj5e2eAQbUi9HtuMaW0LDSnDuxLG54U"
10
+
11
+
12
+ class InvoicePipeline:
13
+
14
+ def __init__(self, paths):
15
+ self._paths = paths
16
+ self._llm = GoogleGenerativeAI(model="gemini-1.5-pro", google_api_key=api_key)
17
+ self._prompt_template = self._get_default_prompt_template()
18
+ # This funcition will help in extracting and run the code, and will produce a dataframe for us
19
+ def run(self) -> pd.DataFrame:
20
+ # We have defined the way the data has to be returned
21
+ df = pd.DataFrame(
22
+ "Invoice ID": pd.Series(dtype = "int"),
23
+ "DESCRIPTION": pd.Series(dtype = "str"),
24
+ "Issue Data": pd.Series(dtype = "str"),
25
+ "UNIT PRICE": pd.Series(dtype = "str"),
26
+ "AMOUNT": pd.Series(dtype = "int"),
27
+ "Bill For": pd.Series(dtype = "str"),
28
+ "From": pd.Series(dtype =" str"),
29
+ "Terms": pd.Series(dtype = "str")}
30
+ )
31
+
32
+ for path in self._paths:
33
+ raw_text = self._get_raw_text_from_pdf(path) # This function needs to be created
34
+ llm_resp = self._extract_data_from_llm(raw_text) #
35
+ data = self._parse_response(llm_resp)
36
+ df = pd.concat([df, pd.DataFrame([data])], ignore_index = True)
37
+
38
+ return df
39
+
40
+ # The default template that the machine will take
41
+ def _get_default_prompt_template(self) -> PromptTemplate:
42
+ template = """Extract all the following values: Invoice ID, DESCRIPTION, Issue Data,UNIT PRICE, AMOUNT, Bill for, From and Terms for: {pages}
43
+ Expected Outcome: remove any dollar symbols {{"Invoice ID":"12341234", "DESCRIPTION": "UNIT PRICE", "AMOUNT": "3", "Date": "2/1/2021", "AMOUNT": "100", "Bill For": "Dev", "From": "Coca Cola", "Terms" : "Net for 30 days"}}
44
+ """
45
+
46
+ prompt_template = PromptTemplate(input_variables = ["pages"], template = template)
47
+ return prompt_template
48
+
49
+
50
+ # We will try to extract the text from the PDF to a normal variable.
51
+ def _get_raw_text_from_pdf(self, path:str) -> str:
52
+ text = ""
53
+ pdf_reader = PdfReader(path)
54
+ for page in pdf_reader:
55
+ text += page.extract_text()
56
+ return text
57
+
58
+ def _extract_data_from_llm(self, raw_data:str) -> str:
59
+ resp = self._llm(self._prompt_template.format(pages = raw_data))
60
+ return resp