File size: 4,424 Bytes
b17d312
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os

import google.generativeai as genai
import gradio as gr
import pandas as pd
from gradio_pdf import PDF
from pdf2image import convert_from_path
from pypdf import PdfReader
from pathlib import Path
dir_ = Path(__file__).parent

genai.configure(api_key=os.environ.get("GOOGLE_API_KEY"))
headers=[
            "DUE DATE",
            "SERVICE ADDRESS",
            "SERVICE PERIOD",
            "ELECTRICITY USAGE (KWH)",
            "ELECTRICITY SPEND ($)",
            "GAS USAGE (THERMS)",
            "GAS SPEND ($)",
            "WATER USAGE (CCF)",
            "WATER SPEND ($)",
            "SEWER ($)",
            "REFUSE ($)",
            "STORM DRAIN ($)",
            "UTILITY USERS TAX ($)",
            "TOTAL CURRENT CHARGES ($)",
            "TOTAL AMOUNT DUE",
        ]


inputs = [PDF(label="Document")]

outputs = [
    gr.Dataframe(
        row_count=(1, "dynamic"),
        col_count=(15, "fixed"),
        label="Utility",
        headers=headers,
        datatype=[
            "str",
            "str",
            "str",
            "str",
            "str",
            "str",
            "str",
            "str",
            "str",
            "str",
            "str",
            "str",
            "str",
            "str",
            "str",
        ],
    )
]


def get_content_between_curly_braces(text):
    """
    This function extracts the content between the opening and closing curly braces of a string.

    Args:
        text: The string to extract content from.

    Returns:
        The extracted content as a string, or None if no curly braces are found.
    """
    start_index = text.find("{")
    end_index = text.rfind("}")

    if start_index != -1 and end_index > start_index:
        return text[start_index : end_index + 1]
    else:
        return None



def parse_utility_bill(filepath):
    print("FOUND PDF!")
    reader = PdfReader(filepath)
    number_of_pages = len(reader.pages)
    images = convert_from_path(filepath)
    assert number_of_pages == len(images)
    page = reader.pages[0]
    text = page.extract_text()
    image = images[0]

    print("---------------------------------------------------------------")
    print(f"We have the image at: ")
    print(image)
    print(f"Here is the text:")
    print(text)
    print("---------------------------------------------------------------")
    model = genai.GenerativeModel(
        "gemini-pro-vision",
    )
    promt_text = (
        f""" Please extract the following JSON object from the utility bill I give. Here is the noisy OCR extractio of the page {text}. Depending on the document, it may contain values for only a few keys such as SEWER. So, you have to be extra carefull."""
        + """This JSON schema:
{'type': 'object', 'properties': { 'DUE DATE': {'type': 'string'},'SERVICE ADDRESS': {'type': 'string'},'SERVICE PERIOD': {'type': 'string'}'ELECTRICITY USAGE (KWH)': {'type': 'string'},'ELECTRICITY SPEND ($)': {'type': 'string'},'GAS USAGE (THERMS)': {'type': 'string'},'GAS SPEND ($)': {'type': 'string'},'WATER USAGE (CCF)': {'type': 'string'},'WATER SPEND ($)': {'type': 'string'},'SEWER ($)': {'type': 'string'},'REFUSE ($)': {'type': 'string'},'STORM DRAIN ($)': {'type': 'string'},'UTILITY USERS TAX ($)': {'type': 'string'},'TOTAL CURRENT CHARGES ($)': {'type': 'string'},'TOTAL AMOUNT DUE ($)': {'type': 'string'}}."""
    )
    print(f"PROMPT: {promt_text}")
    response = model.generate_content(
        [
            promt_text,
            image,
        ],
        generation_config={"max_output_tokens": 2048, "temperature": 0.0},
    )
    json_response = get_content_between_curly_braces(response.text)
    respone_dict = json.loads(json_response)
    print(respone_dict)
    rectified_dict = {}
    for target_key in headers:
        
        for key, value in respone_dict.items():
            if key == target_key:
                rectified_dict[key] = value
                break
        else:
            rectified_dict[target_key] = None
    print(rectified_dict)
    example_data = [rectified_dict]
    

    return pd.DataFrame(example_data)

gr.Interface(
    fn=parse_utility_bill,
    inputs=inputs,
    outputs=outputs,
    examples=["utl-bill-sample.pdf", "nem-2-utility-bill-sample.pdf", "Sample_Utility_Bill.pdf", "Water Bill Sample.pdf", "canada.pdf", "water.pdf"],
    title="🌏⚡💧🔥PDF Utitlity Bill Parser",
).launch()