DSatishchandra commited on
Commit
25e092e
·
verified ·
1 Parent(s): 9aebd9e

Create AL-NISF.py

Browse files
Files changed (1) hide show
  1. AL-NISF.py +160 -0
AL-NISF.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pdfplumber
2
+ import pandas as pd
3
+ import re
4
+ import gradio as gr
5
+
6
+ # Function: Extract Text from PDF
7
+ def extract_text_from_pdf(pdf_file):
8
+ with pdfplumber.open(pdf_file.name) as pdf:
9
+ text = ""
10
+ for page in pdf.pages:
11
+ text += page.extract_text()
12
+ return text
13
+
14
+ # Function: Clean Description
15
+ def clean_description(description, item_number=None):
16
+ """
17
+ Cleans the description by removing unwanted data such as Qty, Unit, Unit Price, Total Price, and other invalid entries.
18
+ Args:
19
+ description (str): Raw description string.
20
+ item_number (int, optional): The item number being processed to handle item-specific cleaning.
21
+ Returns:
22
+ str: Cleaned description.
23
+ """
24
+ # Remove common unwanted patterns
25
+ description = re.sub(r"\d+\s+(Nos\.|Set)\s+[\d.]+\s+[\d.]+", "", description) # Remove Qty + Unit + Price
26
+ description = re.sub(r"Page \d+ of \d+.*", "", description) # Remove page references
27
+ description = re.sub(r"\(Q\. No:.*?\)", "", description) # Remove Q.No-related data
28
+ description = re.sub(r"TOTAL EX-WORK.*", "", description) # Remove EX-WORK-related text
29
+ description = re.sub(r"NOTES:.*", "", description) # Remove notes section
30
+ description = re.sub(r"HS CODE.*", "", description) # Remove HS CODE-related data
31
+ description = re.sub(r"DELIVERY:.*", "", description) # Remove delivery instructions
32
+
33
+ # Specific removal for item 7
34
+ if item_number == 7:
35
+ description = re.sub(r"\b300 Sets 4.20 1260.00\b", "", description)
36
+
37
+ return description.strip()
38
+
39
+
40
+
41
+ # Function: Parse PO Items with Filters
42
+ def parse_po_items_with_filters(text):
43
+ """
44
+ Parses purchase order items from the extracted text using regex with filters.
45
+ Ensures items are not merged and handles split descriptions across lines.
46
+ Args:
47
+ text (str): Extracted text from the PDF.
48
+ Returns:
49
+ tuple: A DataFrame with parsed data and a status message.
50
+ """
51
+ lines = text.splitlines()
52
+ data = []
53
+ current_item = {}
54
+ description_accumulator = []
55
+
56
+ for line in lines:
57
+ # Match the start of an item row
58
+ item_match = re.match(r"^(?P<Item>\d+)\s+(?P<Description>.+)", line)
59
+ if item_match:
60
+ # Save the previous item and start a new one
61
+ if current_item:
62
+ current_item["Description"] = clean_description(
63
+ " ".join(description_accumulator).strip(), item_number=int(current_item["Item"])
64
+ )
65
+ data.append(current_item)
66
+ description_accumulator = []
67
+
68
+ current_item = {
69
+ "Item": item_match.group("Item"),
70
+ "Description": "",
71
+ "Qty": "",
72
+ "Unit": "",
73
+ "Unit Price": "",
74
+ "Total Price": "",
75
+ }
76
+ description_accumulator.append(item_match.group("Description"))
77
+ elif current_item:
78
+ # Handle additional description lines or split descriptions
79
+ description_accumulator.append(line.strip())
80
+
81
+ # Match Qty, Unit, Unit Price, and Total Price
82
+ qty_match = re.search(r"(?P<Qty>\d+)\s+(Nos\.|Set)", line)
83
+ if qty_match:
84
+ current_item["Qty"] = qty_match.group("Qty")
85
+ current_item["Unit"] = qty_match.group(2)
86
+
87
+ price_match = re.search(r"(?P<UnitPrice>[\d.]+)\s+(?P<TotalPrice>[\d.]+)$", line)
88
+ if price_match:
89
+ current_item["Unit Price"] = price_match.group("UnitPrice")
90
+ current_item["Total Price"] = price_match.group("TotalPrice")
91
+
92
+ # Save the last item
93
+ if current_item:
94
+ current_item["Description"] = clean_description(
95
+ " ".join(description_accumulator).strip(), item_number=int(current_item["Item"])
96
+ )
97
+ data.append(current_item)
98
+
99
+ # Correct item 3's separation
100
+ for i, row in enumerate(data):
101
+ if row["Item"] == "2" and "As per Drg. to." in row["Description"]:
102
+ # Split the merged part into item 3
103
+ item_3_description = re.search(r"As per Drg. to. G000810.*Mfd:-2022", row["Description"])
104
+ if item_3_description:
105
+ data.insert(
106
+ i + 1,
107
+ {
108
+ "Item": "3",
109
+ "Description": item_3_description.group(),
110
+ "Qty": "12",
111
+ "Unit": "Nos.",
112
+ "Unit Price": "3.80",
113
+ "Total Price": "45.60",
114
+ },
115
+ )
116
+ # Remove the merged part from item 2
117
+ row["Description"] = row["Description"].replace(item_3_description.group(), "").strip()
118
+
119
+ # Return data as a DataFrame
120
+ if not data:
121
+ return None, "No items found. Please check the PDF file format."
122
+ df = pd.DataFrame(data)
123
+ return df, "Data extracted successfully."
124
+
125
+
126
+
127
+
128
+ # Function: Save to Excel
129
+ def save_to_excel(df, output_path="extracted_po_data.xlsx"):
130
+ df.to_excel(output_path, index=False)
131
+ return output_path
132
+
133
+ # Gradio Interface Function
134
+ def process_pdf(file):
135
+ try:
136
+ text = extract_text_from_pdf(file)
137
+ df, status = parse_po_items_with_filters(text)
138
+ if df is not None:
139
+ output_path = save_to_excel(df)
140
+ return output_path, status
141
+ return None, status
142
+ except Exception as e:
143
+ return None, f"Error during processing: {str(e)}"
144
+
145
+ # Gradio Interface Setup
146
+ def create_gradio_interface():
147
+ return gr.Interface(
148
+ fn=process_pdf,
149
+ inputs=gr.File(label="Upload PDF", file_types=[".pdf"]),
150
+ outputs=[
151
+ gr.File(label="Download Extracted Data"),
152
+ gr.Textbox(label="Status"),
153
+ ],
154
+ title="PO Data Extraction",
155
+ description="Upload a Purchase Order PDF to extract items into an Excel file.",
156
+ )
157
+
158
+ if __name__ == "__main__":
159
+ interface = create_gradio_interface()
160
+ interface.launch()