File size: 1,349 Bytes
772a5e0
 
 
 
 
 
44f6eb2
772a5e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44f6eb2
772a5e0
44f6eb2
 
772a5e0
44f6eb2
 
772a5e0
44f6eb2
772a5e0
 
44f6eb2
772a5e0
 
44f6eb2
772a5e0
 
44f6eb2
772a5e0
 
44f6eb2
772a5e0
 
44f6eb2
 
 
 
772a5e0
 
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
import re

GST_REGEX = r"\d{2}[A-Z]{5}\d{4}[A-Z]{1}[A-Z\d]{1}[Z]{1}[A-Z\d]{1}"

def extract_amount(line):
    nums = re.findall(r"\d+\.\d+|\d+", line.replace(",", ""))
    return float(nums[-1]) if nums else 0.0

def extract_fields(text):
    lines = text.split("\n")

    data = {
        "Vendor": None,
        "GSTIN": None,
        "Date": None,
        "Invoice No": None,
        "Taxable": 0.0,
        "CGST": 0.0,
        "SGST": 0.0,
        "IGST": 0.0,
        "Total": 0.0
    }

    gst_match = re.search(GST_REGEX, text)
    if gst_match:
        data["GSTIN"] = gst_match.group()

    for line in lines:
        l = line.lower()

        if "invoice" in l and not data["Invoice No"]:
            data["Invoice No"] = line.split()[-1]

        if "date" in l and not data["Date"]:
            data["Date"] = line.split()[-1]

        if "cgst" in l:
            data["CGST"] = extract_amount(line)

        if "sgst" in l:
            data["SGST"] = extract_amount(line)

        if "igst" in l:
            data["IGST"] = extract_amount(line)

        if "taxable" in l:
            data["Taxable"] = extract_amount(line)

        if "total" in l:
            data["Total"] = extract_amount(line)

    for line in lines:
        if len(line.strip()) > 5:
            data["Vendor"] = line.strip()
            break

    return data