-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
191 lines (154 loc) Β· 7.29 KB
/
app.py
File metadata and controls
191 lines (154 loc) Β· 7.29 KB
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import streamlit as st
import pandas as pd
import os
import tempfile
from io import BytesIO
from pdf_generator import PDFGenerator
from data_processor import DataProcessor
from template_manager import TemplateManager
# Page configuration
st.set_page_config(
page_title="Automated PDF Export System",
page_icon="π",
layout="wide"
)
def main():
st.title("π Automated PDF Export System")
st.markdown("Upload your data files and generate professional BOV reports with preserved formatting.")
# Initialize session state
if 'processed_data' not in st.session_state:
st.session_state.processed_data = None
if 'template_loaded' not in st.session_state:
st.session_state.template_loaded = False
# Create two columns for layout
col1, col2 = st.columns([1, 1])
with col1:
st.header("π Data Upload")
# File uploader
uploaded_file = st.file_uploader(
"Choose a data file",
type=['csv', 'xlsx', 'xls'],
help="Upload CSV or Excel files containing your data"
)
if uploaded_file is not None:
try:
with st.spinner("Processing data file..."):
# Process the uploaded file
data_processor = DataProcessor()
df = data_processor.load_file(uploaded_file)
st.session_state.processed_data = df
st.success(f"β
File processed successfully! Found {len(df)} records.")
# Show data preview
st.subheader("Data Preview")
st.dataframe(df.head(10), use_container_width=True)
# Show column information
st.subheader("Column Information")
col_info = pd.DataFrame({
'Column': df.columns,
'Data Type': df.dtypes,
'Non-Null Count': df.count(),
'Sample Value': [str(df[col].iloc[0]) if len(df) > 0 else 'N/A' for col in df.columns]
})
st.dataframe(col_info, use_container_width=True)
except Exception as e:
st.error(f"β Error processing file: {str(e)}")
st.session_state.processed_data = None
with col2:
st.header("π Template Management")
# Template selection
template_manager = TemplateManager()
available_templates = template_manager.get_available_templates()
selected_template = st.selectbox(
"Select BOV Template",
available_templates,
help="Choose a pre-formatted template for your PDF export"
)
if selected_template:
try:
template_content = template_manager.load_template(selected_template)
st.session_state.template_loaded = True
st.success(f"β
Template '{selected_template}' loaded successfully!")
# Show template preview
st.subheader("Template Preview")
with st.expander("View Template Structure", expanded=False):
st.code(template_content[:500] + "..." if len(template_content) > 500 else template_content, language="html")
except Exception as e:
st.error(f"β Error loading template: {str(e)}")
st.session_state.template_loaded = False
# PDF Generation Section
st.header("π PDF Generation")
if st.session_state.processed_data is not None and st.session_state.template_loaded:
col1, col2, col3 = st.columns([1, 1, 1])
with col1:
# Generation options
st.subheader("Generation Options")
# Record selection
total_records = len(st.session_state.processed_data)
generate_all = st.checkbox(f"Generate PDF for all {total_records} records", value=True)
if not generate_all:
record_range = st.slider(
"Select record range",
min_value=1,
max_value=total_records,
value=(1, min(10, total_records)),
help="Select which records to include in the PDF"
)
else:
record_range = (1, total_records)
with col2:
st.subheader("PDF Settings")
# PDF options
include_images = st.checkbox("Include images", value=True)
preserve_formatting = st.checkbox("Preserve formatting", value=True)
page_size = st.selectbox("Page size", ["A4", "Letter", "Legal"], index=0)
with col3:
st.subheader("Output Options")
# Output filename
output_filename = st.text_input(
"Output filename",
value="BOV_Report.pdf",
help="Name for the generated PDF file"
)
if not output_filename.endswith('.pdf'):
output_filename += '.pdf'
# Generate PDF button
if st.button("π₯ Generate PDF", type="primary", use_container_width=True):
try:
with st.spinner("Generating PDF... This may take a moment."):
# Prepare data subset
start_idx, end_idx = record_range
data_subset = st.session_state.processed_data.iloc[start_idx-1:end_idx]
# Initialize PDF generator
pdf_generator = PDFGenerator(
template_name=selected_template,
include_images=include_images,
preserve_formatting=preserve_formatting,
page_size=page_size
)
# Generate PDF
pdf_buffer = pdf_generator.generate_pdf(data_subset)
# Show success message
st.success(f"β
PDF generated successfully! ({len(data_subset)} records processed)")
# Download button
st.download_button(
label="π₯ Download PDF",
data=pdf_buffer.getvalue(),
file_name=output_filename,
mime="application/pdf",
use_container_width=True
)
# Show PDF stats
st.info(f"π PDF Statistics:\n"
f"- Records processed: {len(data_subset)}\n"
f"- File size: {len(pdf_buffer.getvalue())} bytes\n"
f"- Template used: {selected_template}")
except Exception as e:
st.error(f"β Error generating PDF: {str(e)}")
st.exception(e)
else:
st.warning("β οΈ Please upload a data file and select a template to generate PDF.")
# Footer
st.markdown("---")
st.markdown("*Automated PDF Export System - Streamlit Application*")
if __name__ == "__main__":
main()