File size: 7,062 Bytes
cae67f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# import streamlit as st
# import pandas as pd
# import tempfile
# import os
# from PDFSectionExtractor import PDFSectionExtractor, convert_pdf_to_excel
# def main():
#     st.title("PDF Section and Table Extractor")
#     st.write("Upload a PDF file to extract sections and tables into an Excel workbook.")
#     # File uploader
#     uploaded_file = st.file_uploader("Choose a PDF file", type=['pdf'])
#     if uploaded_file is not None:
#         # Create a temporary directory to store the files
#         with tempfile.TemporaryDirectory() as temp_dir:
#             # Save the uploaded PDF
#             pdf_path = os.path.join(temp_dir, uploaded_file.name)
#             with open(pdf_path, "wb") as f:
#                 f.write(uploaded_file.getvalue())
#             # Create the Excel output path
#             excel_filename = os.path.splitext(uploaded_file.name)[0] + "_extracted.xlsx"
#             excel_path = os.path.join(temp_dir, excel_filename)
#             try:
#                 with st.spinner("Processing PDF..."):
#                     # Create extractor instance
#                     extractor = PDFSectionExtractor(pdf_path)
#                     # Get document info
#                     doc_name, doc_id = extractor.get_document_info()
#                     st.write(f"Document Name: {doc_name}")
#                     st.write(f"Document ID: {doc_id}")
#                     # Extract tables and sections
#                     tables = extractor.extract_tables()
#                     sections = extractor.extract_sections()
#                     # Create Excel file
#                     convert_pdf_to_excel(pdf_path, excel_path)
#                     # Show summary
#                     st.success(f"Successfully processed PDF!")
#                     st.write(f"Found {len(tables)} tables and {len(sections)} sections.")
#                     # Preview sections
#                     if sections:
#                         st.subheader("Sections Preview")
#                         df_sections = pd.DataFrame(sections)
#                         st.dataframe(df_sections)
#                     # Preview tables
#                     if tables:
#                         st.subheader("Tables Preview")
#                         for i, table in enumerate(tables, 1):
#                             with st.expander(f"Table {i}"):
#                                 st.dataframe(table)
#                     # Provide download button for Excel file
#                     with open(excel_path, "rb") as f:
#                         excel_data = f.read()
#                     st.download_button(
#                         label="Download Excel File",
#                         data=excel_data,
#                         file_name=excel_filename,
#                         mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
#                     )
#             except Exception as e:
#                 st.error(f"An error occurred: {str(e)}")
# if __name__ == "__main__":
#     main()

import streamlit as st
import pandas as pd
import tempfile
import os
from PDFSectionExtractor import PDFSectionExtractor, convert_pdf_to_excel
# Add page config
st.set_page_config(
    page_title="PDF Section and Table Extractor",
    page_icon=":page_facing_up:",
    layout="wide"
)
# Add custom CSS to improve the interface
st.markdown("""
    <style>
    .stButton>button {
        width: 100%;
    }
    .css-1v0mbdj.e115fcil1 {
        max-width: 100%;
    }
    </style>
    """, unsafe_allow_html=True)
def main():
    st.title(":page_facing_up: PDF Section and Table Extractor")
    st.write("Upload a PDF file to extract sections and tables into an Excel workbook.")
    # Add some usage instructions
    with st.expander(":information_source: How to use"):
        st.write("""
        1. Upload a PDF file using the file uploader below
        2. Wait for the processing to complete
        3. Preview the extracted sections
        4. Download the results as an Excel file
        """)
    # File uploader with additional information
    uploaded_file = st.file_uploader(
        "Choose a PDF file",
        type=['pdf'],
        help="Upload a PDF file containing sections and tables to extract"
    )
    if uploaded_file is not None:
        # Create a temporary directory to store the files
        with tempfile.TemporaryDirectory() as temp_dir:
            # Save the uploaded PDF
            pdf_path = os.path.join(temp_dir, uploaded_file.name)
            with open(pdf_path, "wb") as f:
                f.write(uploaded_file.getvalue())
            # Create the Excel output path
            excel_filename = os.path.splitext(uploaded_file.name)[0] + "_extracted.xlsx"
            excel_path = os.path.join(temp_dir, excel_filename)
            try:
                with st.spinner(":arrows_counterclockwise: Processing PDF... This may take a moment."):
                    # Create extractor instance
                    extractor = PDFSectionExtractor(pdf_path)
                    # Get document info
                    doc_name, doc_id = extractor.get_document_info()
                    # Display document info in a nice format
                    col1, col2 = st.columns(2)
                    with col1:
                        st.info(f":memo: Document Name: {doc_name}")
                    with col2:
                        st.info(f":key: Document ID: {doc_id}")
                    # Extract tables and sections
                    tables = extractor.extract_tables()
                    sections = extractor.extract_sections()
                    # Create Excel file
                    convert_pdf_to_excel(pdf_path, excel_path)
                    # Show summary
                    st.success(":white_check_mark: Successfully processed PDF!")
                    st.write(f":bar_chart: Found {len(tables)} tables and :bookmark_tabs: {len(sections)} sections.")
                    # Display sections preview
                    if sections:
                        st.subheader("Sections Preview")
                        df_sections = pd.DataFrame(sections)
                        st.dataframe(df_sections, use_container_width=True)
                    else:
                        st.warning("No sections found in the document.")
                    # Provide download button for Excel file
                    with open(excel_path, "rb") as f:
                        excel_data = f.read()
                    st.download_button(
                        label=":inbox_tray: Download Excel File",
                        data=excel_data,
                        file_name=excel_filename,
                        mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        key="download-excel"
                    )
            except Exception as e:
                st.error(f":x: An error occurred: {str(e)}")
                st.write("Please make sure your PDF file is valid and try again.")
if __name__ == "__main__":
    main()