DSatishchandra commited on
Commit
0d31bb2
·
verified ·
1 Parent(s): 569416a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -61
app.py CHANGED
@@ -1,77 +1,73 @@
1
- import pdfplumber
2
- import pandas as pd
3
  import re
4
- import gradio as gr
5
-
6
- def extract_po_items(pdf_file):
7
- try:
8
- with pdfplumber.open(pdf_file.name) as pdf:
9
- text = ""
10
- for page in pdf.pages:
11
- text += page.extract_text()
12
 
13
- # Updated regex to capture items more reliably
14
- item_pattern = re.compile(
15
- r"(?P<Item>\d+)\s+(?P<Description>.+?)\s+(?P<Qty>\d+)\s+(?P<Unit>(Nos\.|Set))\s+"
16
- r"(?P<UnitPrice>[\d.]+)\s+(?P<TotalPrice>[\d.]+)",
17
- re.DOTALL
18
- )
19
 
20
- matches = item_pattern.finditer(text)
21
- data = []
 
 
 
 
 
 
22
 
23
- for match in matches:
24
- item = match.group("Item")
25
- description = match.group("Description").strip()
26
- qty = match.group("Qty")
27
- unit = match.group("Unit")
28
- unit_price = match.group("UnitPrice")
29
- total_price = match.group("TotalPrice")
 
 
 
 
30
 
31
- # Append item data
32
- data.append({
33
- "Item": item,
34
- "Description": description,
35
- "Qty": qty,
36
- "Unit": unit,
37
- "Unit Price": unit_price,
38
- "Total Price": total_price,
39
- })
40
 
41
- if not data:
42
- return None, "No items found. Please check the PDF file format."
43
 
44
- # Convert data to DataFrame
45
- df = pd.DataFrame(data)
 
 
46
 
47
- # Validate row count
48
- expected_items = 8 # Update this number based on the actual PO
49
- if len(df) < expected_items:
50
- missing_items = expected_items - len(df)
51
- return df, f"Data extracted, but {missing_items} items are missing."
52
 
53
- return df, "Data extracted successfully."
 
 
 
 
 
 
 
54
  except Exception as e:
55
- return None, f"Error during extraction: {str(e)}"
56
 
57
- def process_pdf(file):
58
- df, status = extract_po_items(file)
59
- if df is not None:
60
- output_path = "extracted_po_data.xlsx"
61
- df.to_excel(output_path, index=False)
62
- return output_path, status
63
- return None, status
64
 
65
  iface = gr.Interface(
66
  fn=process_pdf,
67
- inputs=gr.File(label="Upload PDF", file_types=[".pdf"]),
68
- outputs=[
69
- gr.File(label="Download Extracted Data"),
70
- gr.Textbox(label="Status"),
71
- ],
72
- title="PO Data Extraction",
73
- description="Upload a Purchase Order PDF to extract items into an Excel file.",
74
  )
75
 
76
- if __name__ == "__main__":
77
- iface.launch()
 
 
 
1
  import re
2
+ import pandas as pd
3
+ import pdfplumber
 
 
 
 
 
 
4
 
5
+ # Function to extract structured data from the PDF
6
+ def extract_al_nisf_data(pdf_path):
7
+ data = []
 
 
 
8
 
9
+ # Define regex patterns
10
+ item_pattern = re.compile(
11
+ r"(?P<Item>\d+)\s+(?P<Description>.+?)(?=\s+\d+\s+\w+\s+[\d.]+\s+[\d.]+)",
12
+ re.DOTALL
13
+ )
14
+ qty_unit_price_pattern = re.compile(
15
+ r"(?P<Qty>\d+)\s+(?P<Unit>\w+)\s+(?P<UnitPrice>[\d.]+)\s+(?P<TotalPrice>[\d.]+)"
16
+ )
17
 
18
+ # Extract text from PDF using pdfplumber
19
+ with pdfplumber.open(pdf_path) as pdf:
20
+ for page in pdf.pages:
21
+ text = page.extract_text()
22
+ # Match items using the regex pattern
23
+ item_matches = item_pattern.finditer(text)
24
+
25
+ for match in item_matches:
26
+ item_data = match.groupdict()
27
+ description_lines = item_data["Description"].strip().split("\n")
28
+ item_data["Description"] = " ".join(description_lines).strip()
29
 
30
+ # Look for quantity, unit, unit price, and total price after the item
31
+ qty_match = qty_unit_price_pattern.search(text[match.end():])
32
+ if qty_match:
33
+ item_data.update(qty_match.groupdict())
34
+ else:
35
+ # Default empty values if not found
36
+ item_data.update({"Qty": "", "Unit": "", "UnitPrice": "", "TotalPrice": ""})
 
 
37
 
38
+ data.append(item_data)
 
39
 
40
+ # Convert the data into a DataFrame
41
+ df = pd.DataFrame(data)
42
+ df.columns = ["Item", "Description", "Qty", "Unit", "Unit Price", "Total Price"]
43
+ return df
44
 
45
+ # Save the extracted data to an Excel file
46
+ def save_to_excel(df, output_path):
47
+ with pd.ExcelWriter(output_path) as writer:
48
+ df.to_excel(writer, index=False, sheet_name="Extracted Data")
 
49
 
50
+ # Gradio interface function
51
+ def process_pdf(file):
52
+ try:
53
+ # Extract data from the uploaded PDF
54
+ df = extract_al_nisf_data(file.name)
55
+ output_path = "extracted_data.xlsx"
56
+ save_to_excel(df, output_path)
57
+ return output_path # Return the file path for download
58
  except Exception as e:
59
+ return f"Error: {str(e)}"
60
 
61
+ # Gradio Interface
62
+ import gradio as gr
 
 
 
 
 
63
 
64
  iface = gr.Interface(
65
  fn=process_pdf,
66
+ inputs=gr.inputs.File(label="Upload PO PDF"),
67
+ outputs=gr.outputs.File(label="Download Extracted Data"),
68
+ title="AL-NISF PO Extraction",
69
+ description="Upload a PO PDF to extract tabular data and export to Excel."
 
 
 
70
  )
71
 
72
+ # Launch the Gradio app
73
+ iface.launch()