File size: 4,290 Bytes
c65900d
4fb5761
 
 
 
 
 
ddb3950
4ba6e83
 
4fb5761
 
 
 
 
5566890
 
b7199be
5566890
4fb5761
ddb3950
4ba6e83
ddb3950
4fb5761
 
 
 
 
 
 
 
ddb3950
4ba6e83
ddb3950
4fb5761
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddb3950
 
 
5566890
 
 
f902817
5566890
ddb3950
 
 
4fb5761
 
5566890
4fb5761
b7199be
 
ddb3950
 
 
4ba6e83
b7199be
ddb3950
4ba6e83
 
 
 
 
ddb3950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7199be
 
 
 
 
ddb3950
 
 
 
b7199be
 
ddb3950
4ba6e83
ddb3950
b7199be
 
 
ddb3950
4ba6e83
ddb3950
b7199be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddb3950
f902817
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
import streamlit as st
from PIL import Image
import pytesseract
import pandas as pd
import re
import cv2
import numpy as np
from PyPDF2 import PdfReader
import tempfile
import os

st.set_page_config(page_title="CA Invoice Automation", layout="wide")

st.title("πŸ“‘ CA Invoice Automation App")

uploaded_file = st.file_uploader(
    "Upload Invoice (Image or PDF)",
    type=["jpg", "jpeg", "png", "pdf"]
)

# --------------------------------
# Classification
# --------------------------------
def classify_invoice(text):
    if "tax invoice" in text.lower():
        return "GST_PURCHASE"
    elif "credit note" in text.lower():
        return "CREDIT_NOTE"
    else:
        return "UNKNOWN"

# --------------------------------
# Extraction
# --------------------------------
def extract_data(text):
    gstin_pattern = r"\d{2}[A-Z]{5}\d{4}[A-Z]\dZ\d"
    date_pattern = r"\d{2}[-/]\d{2}[-/]\d{4}"
    amount_pattern = r"\d{1,3}(,\d{3})*(\.\d{2})?"

    gstin = re.search(gstin_pattern, text)
    date = re.search(date_pattern, text)
    amount = re.search(amount_pattern, text)

    return {
        "Date": date.group() if date else None,
        "GSTIN": gstin.group() if gstin else None,
        "Total Amount": amount.group() if amount else None
    }

# --------------------------------
# OCR for Images
# --------------------------------
def ocr_image(pil_image):
    image_np = np.array(pil_image)
    gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
    return pytesseract.image_to_string(gray)

# --------------------------------
# MAIN
# --------------------------------
if uploaded_file:

    full_text = ""

    try:

        # ================================
        # -------- PDF HANDLING ----------
        # ================================
        if uploaded_file.type == "application/pdf":

            st.info("Extracting text directly from PDF...")

            with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
                tmp.write(uploaded_file.getvalue())
                tmp_path = tmp.name

            reader = PdfReader(tmp_path)

            for page in reader.pages[:5]:  # Limit to first 5 pages
                extracted_text = page.extract_text()
                if extracted_text:
                    full_text += extracted_text + "\n"

            os.remove(tmp_path)

            if not full_text.strip():
                st.warning("No embedded text found in PDF (might be scanned).")

        # ================================
        # -------- IMAGE HANDLING --------
        # ================================
        else:
            image = Image.open(uploaded_file)
            st.image(image, caption="Uploaded Invoice", use_column_width=True)
            full_text = ocr_image(image)

        # --------------------------------
        # Show OCR / Extracted Text
        # --------------------------------
        st.subheader("πŸ“ Extracted Text")
        st.text(full_text)

        # --------------------------------
        # Classification
        # --------------------------------
        invoice_type = classify_invoice(full_text)
        st.success(f"Invoice Type: {invoice_type}")

        # --------------------------------
        # Extraction
        # --------------------------------
        data = extract_data(full_text)

        formatted_data = {
            "Date": data["Date"],
            "Voucher Type": "Purchase" if invoice_type=="GST_PURCHASE" else "Unknown",
            "Vendor": "To be detected",
            "GSTIN": data["GSTIN"],
            "Invoice No": "To be extracted",
            "Taxable": None,
            "CGST": None,
            "SGST": None,
            "Total": data["Total Amount"],
            "Debit Ledger": "Purchase A/c",
            "Credit Ledger": "Vendor A/c",
            "Narration": f"Being purchase invoice dated {data['Date']}",
        }

        df = pd.DataFrame([formatted_data])

        st.subheader("πŸ“Š Structured Voucher Data")
        st.dataframe(df, use_container_width=True)

        st.download_button(
            "⬇ Download CSV",
            df.to_csv(index=False),
            "voucher_output.csv",
            "text/csv"
        )

    except Exception as e:
        st.error("Processing failed.")
        st.write(str(e))