nithin81 commited on
Commit
3c0c2d6
·
verified ·
1 Parent(s): 6b16f67

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -121
app.py CHANGED
@@ -1,121 +1,147 @@
1
- import streamlit as st
2
- import pandas as pd
3
- from azure.core.credentials import AzureKeyCredential
4
- from azure.ai.formrecognizer import DocumentAnalysisClient
5
- import time
6
- from dotenv import load_dotenv
7
- import os
8
-
9
- load_dotenv()
10
-
11
- # Azure Form Recognizer credentials
12
- endpoint = st.secrets["endpoint"]
13
- key = st.secrets["key"]
14
-
15
- # Initialize DocumentAnalysisClient
16
- document_analysis_client = DocumentAnalysisClient(
17
- endpoint=endpoint, credential=AzureKeyCredential(key)
18
- )
19
-
20
- # Sidebar for document type selection
21
- document_type = st.sidebar.selectbox(
22
- "Select Document Type", ["Invoice", "Receipt", "Identity Document"]
23
- )
24
-
25
- # Center area for file upload
26
- uploaded_file = st.file_uploader("Choose or drag a file", type=["pdf", "png", "jpg", "jpeg"])
27
-
28
- # Initialize session state for processing results
29
- if "processed" not in st.session_state:
30
- st.session_state.processed = False
31
- st.session_state.tables = []
32
- st.session_state.kv_df = pd.DataFrame()
33
-
34
- # Process the uploaded file if the button is clicked
35
- if uploaded_file is not None:
36
- if st.button("Upload and Process"):
37
- with st.spinner("Processing..."):
38
- time.sleep(1) # Simulate some delay to show the spinner
39
-
40
- # Analyze the document
41
- poller = document_analysis_client.begin_analyze_document(
42
- "prebuilt-document", document=uploaded_file
43
- )
44
- result = poller.result()
45
-
46
- # Extract key-value pairs and store them in a dictionary
47
- kv_dict = {}
48
- for kv_pair in result.key_value_pairs:
49
- if kv_pair.key and kv_pair.value: # Ensure both key and value exist
50
- kv_dict[kv_pair.key.content] = kv_pair.value.content
51
-
52
- kv_df = pd.DataFrame(list(kv_dict.items()), columns=["Key", "Value"]).T
53
-
54
- # Set the first row as the header
55
- header = kv_df.iloc[0]
56
-
57
- # Create a new DataFrame with the header and the remaining rows
58
- kv_df = kv_df[1:].reset_index(drop=True)
59
-
60
- # Insert the new header row
61
- header_df = pd.DataFrame([header], columns=range(len(header)))
62
-
63
- # Concatenate the header row DataFrame with the original DataFrame
64
- kv_df = pd.concat([header_df, kv_df], ignore_index=True)
65
-
66
- st.session_state.kv_df = kv_df
67
- st.session_state.tables = []
68
-
69
- if result.tables:
70
- for table in result.tables:
71
- temp_kv_df = kv_df.copy()
72
-
73
- data = []
74
- for cell in table.cells:
75
- data.append([cell.row_index, cell.column_index, cell.content])
76
-
77
- table_df = pd.DataFrame(data, columns=["row_index", "column_index", "content"])
78
- table_df = table_df.pivot(index="row_index", columns="column_index", values="content")
79
-
80
- rows_to_add = len(table_df) - len(temp_kv_df)
81
- if rows_to_add > 0:
82
- last_row = temp_kv_df.iloc[-1]
83
- additional_rows = pd.DataFrame([last_row] * rows_to_add, columns=temp_kv_df.columns)
84
- temp_kv_df = pd.concat([temp_kv_df, additional_rows], ignore_index=True)
85
-
86
- table_with_kv = pd.concat([temp_kv_df, table_df], axis=1, ignore_index=True)
87
- st.session_state.tables.append(table_with_kv)
88
-
89
- st.session_state.processed = True
90
-
91
- # Display the results if processing is done
92
- if st.session_state.processed:
93
- st.write("Extracted Key-Value Pairs:")
94
- st.dataframe(st.session_state.kv_df)
95
-
96
- if st.session_state.tables:
97
- for i, table_with_kv in enumerate(st.session_state.tables):
98
- st.write(f"Table {i + 1} with Key-Value Pairs:")
99
- st.dataframe(table_with_kv)
100
-
101
- st.download_button(
102
- label=f"Download Table {i + 1} as CSV",
103
- data=table_with_kv.to_csv(index=False, header=False).encode('utf-8'),
104
- file_name=f"table_with_kv_{i + 1}.csv",
105
- mime='text/csv',
106
- )
107
- else:
108
- st.write("No tables found in the document.")
109
- st.download_button(
110
- label="Download Key-Value Pairs as CSV",
111
- data=st.session_state.kv_df.to_csv(index=False, header=False).encode('utf-8'),
112
- file_name="kv_df.csv",
113
- mime='text/csv',
114
- )
115
-
116
- # Option to remove the file and clear the session
117
- if st.session_state.processed and st.button("Remove File"):
118
- st.session_state.processed = False
119
- st.session_state.tables = []
120
- st.session_state.kv_df = pd.DataFrame()
121
- st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from azure.core.credentials import AzureKeyCredential
4
+ from azure.ai.formrecognizer import DocumentAnalysisClient
5
+ import time
6
+ from dotenv import load_dotenv
7
+ import os
8
+
9
+ load_dotenv()
10
+
11
+ # Azure Form Recognizer credentials
12
+ endpoint = st.secrets["endpoint"]
13
+ key = st.secrets["key"]
14
+
15
+ # Initialize DocumentAnalysisClient
16
+ document_analysis_client = DocumentAnalysisClient(
17
+ endpoint=endpoint, credential=AzureKeyCredential(key)
18
+ )
19
+
20
+ # Sidebar for document type selection
21
+ document_type = st.sidebar.selectbox(
22
+ "Select Document Type", ["Invoice", "Receipt", "Identity Document"]
23
+ )
24
+
25
+ # Center area for file upload
26
+ uploaded_file = st.file_uploader(f"Choose or drag an {document_type} file", type=["pdf", "png", "jpg", "jpeg"])
27
+
28
+ # Initialize session state for processing results
29
+ if "processed" not in st.session_state:
30
+ st.session_state.processed = False
31
+ st.session_state.tables = []
32
+ st.session_state.kv_df = pd.DataFrame()
33
+
34
+ # Process the uploaded file if the button is clicked
35
+ if uploaded_file is not None:
36
+ if st.button("Upload and Process"):
37
+ with st.spinner("Processing..."):
38
+ time.sleep(1) # Simulate some delay to show the spinner
39
+
40
+ # Analyze the document
41
+ poller = document_analysis_client.begin_analyze_document(
42
+ "prebuilt-document", document=uploaded_file
43
+ )
44
+ result = poller.result()
45
+
46
+ # Extract key-value pairs and store them in a dictionary
47
+ kv_dict = {}
48
+ for kv_pair in result.key_value_pairs:
49
+ if kv_pair.key and kv_pair.value: # Ensure both key and value exist
50
+ kv_dict[kv_pair.key.content] = kv_pair.value.content
51
+
52
+ kv_df = pd.DataFrame(list(kv_dict.items()), columns=["Key", "Value"]).T
53
+
54
+ # Set the first row as the header
55
+ header = kv_df.iloc[0]
56
+
57
+ # Create a new DataFrame with the header and the remaining rows
58
+ kv_df = kv_df[1:].reset_index(drop=True)
59
+
60
+ # Insert the new header row
61
+ header_df = pd.DataFrame([header], columns=range(len(header)))
62
+
63
+ # Concatenate the header row DataFrame with the original DataFrame
64
+ kv_df = pd.concat([header_df, kv_df], ignore_index=True)
65
+
66
+ st.session_state.kv_df = kv_df
67
+ st.session_state.tables = []
68
+
69
+ if result.tables:
70
+ for table in result.tables:
71
+ temp_kv_df = kv_df.copy()
72
+
73
+ data = []
74
+ for cell in table.cells:
75
+ data.append([cell.row_index, cell.column_index, cell.content])
76
+
77
+ table_df = pd.DataFrame(data, columns=["row_index", "column_index", "content"])
78
+ table_df = table_df.pivot(index="row_index", columns="column_index", values="content")
79
+
80
+ st.session_state.tables.append(table_df)
81
+
82
+ st.session_state.processed = True
83
+
84
+ # Display the results if processing is done
85
+ if st.session_state.processed:
86
+ if not st.session_state.kv_df.empty:
87
+ st.write("Extracted Key-Value Pairs:")
88
+ st.dataframe(st.session_state.kv_df)
89
+ st.download_button(
90
+ label="Download Key-Value Pairs as CSV",
91
+ data=st.session_state.kv_df.to_csv(index=False, header=False).encode('utf-8'),
92
+ file_name="kv_df.csv",
93
+ mime='text/csv',
94
+ )
95
+ else:
96
+ st.write("No Key-Value Pairs found in document.")
97
+
98
+
99
+ if st.session_state.tables:
100
+ if not st.session_state.kv_df.empty:
101
+ # Allow the user to select multiple columns
102
+ first_row_values = st.session_state.kv_df.iloc[0].values
103
+ selected_columns = st.multiselect(
104
+ "Select columns from Key-Value Pairs to add to tables:", first_row_values
105
+ )
106
+ for i, table_df in enumerate(st.session_state.tables):
107
+ st.write(f"Table {i + 1} with Selected Columns Added:")
108
+
109
+ # Find the column names corresponding to the selected first row values
110
+ column_indices = [list(first_row_values).index(val) for val in selected_columns]
111
+ column_names = st.session_state.kv_df.columns[column_indices]
112
+
113
+ # Add the selected columns to the table
114
+ if selected_columns:
115
+ # Create a new DataFrame for the selected columns
116
+ selected_columns_df = st.session_state.kv_df[column_names].copy()
117
+
118
+ # Align the length of selected_columns_df with the table_df rows
119
+ selected_columns_df = selected_columns_df.iloc[:len(table_df)].reset_index(drop=True)
120
+
121
+ rows_to_add = len(table_df) - len(selected_columns_df)
122
+ if rows_to_add > 0:
123
+ last_row = selected_columns_df.iloc[-1]
124
+ additional_rows = pd.DataFrame([last_row] * rows_to_add, columns=selected_columns_df.columns)
125
+ selected_columns_df = pd.concat([selected_columns_df, additional_rows], ignore_index=True)
126
+
127
+ # Concatenate the selected columns DataFrame with the table DataFrame
128
+ table_df = pd.concat([selected_columns_df, table_df.reset_index(drop=True)], axis=1, ignore_index=True)
129
+
130
+ st.dataframe(table_df)
131
+
132
+ st.download_button(
133
+ label=f"Download Table {i + 1} as CSV",
134
+ data=table_df.to_csv(index=False, header=False).encode('utf-8'),
135
+ file_name=f"table_with_kv_{i + 1}.csv",
136
+ mime='text/csv',
137
+ )
138
+ else:
139
+ st.write("No tables found in the document.")
140
+
141
+
142
+ # Option to remove the file and clear the session
143
+ if st.session_state.processed and st.button("Remove File"):
144
+ st.session_state.processed = False
145
+ st.session_state.tables = []
146
+ st.session_state.kv_df = pd.DataFrame()
147
+ st.rerun()