bluenevus commited on
Commit
29ac6e4
·
1 Parent(s): 2a4a14f

Update app.py via AI Editor

Browse files
Files changed (1) hide show
  1. app.py +298 -1
app.py CHANGED
@@ -1 +1,298 @@
1
- -
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dash
2
+ import dash_bootstrap_components as dbc
3
+ from dash import html, dcc, Input, Output, State, ctx
4
+ import flask
5
+ import uuid
6
+ import os
7
+ import tempfile
8
+ import shutil
9
+ import logging
10
+ from flask import send_file, make_response
11
+ import threading
12
+ import pickle
13
+ from PyPDF2 import PdfReader, PdfWriter
14
+ import re
15
+
16
+ # Configure logging
17
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
18
+
19
+ # Session storage and lock management
20
+ SESSION_DATA = {}
21
+ SESSION_LOCKS = {}
22
+
23
+ def get_session_id():
24
+ session_id = flask.request.cookies.get('session-id')
25
+ if not session_id:
26
+ session_id = str(uuid.uuid4())
27
+ return session_id
28
+
29
+ def get_session_dir(session_id):
30
+ base_tmp = tempfile.gettempdir()
31
+ path = os.path.join(base_tmp, f'dash_pdfsplit_{session_id}')
32
+ os.makedirs(path, exist_ok=True)
33
+ return path
34
+
35
+ def clean_session(session_id):
36
+ try:
37
+ session_dir = get_session_dir(session_id)
38
+ if os.path.exists(session_dir):
39
+ shutil.rmtree(session_dir)
40
+ SESSION_DATA.pop(session_id, None)
41
+ SESSION_LOCKS.pop(session_id, None)
42
+ except Exception as e:
43
+ logging.error(f"Error cleaning session {session_id}: {e}")
44
+
45
+ def get_session_lock(session_id):
46
+ if session_id not in SESSION_LOCKS:
47
+ SESSION_LOCKS[session_id] = threading.Lock()
48
+ return SESSION_LOCKS[session_id]
49
+
50
+ def allowed_file(filename):
51
+ return '.' in filename and filename.lower().endswith('.pdf')
52
+
53
+ def extract_text_headers(reader, page_num):
54
+ try:
55
+ page = reader.pages[page_num]
56
+ text = page.extract_text() or ""
57
+ # Extract the first non-blank line as a potential header
58
+ lines = [line.strip() for line in text.split('\n') if line.strip()]
59
+ header = lines[0] if lines else ""
60
+ return header
61
+ except Exception as e:
62
+ logging.warning(f"Failed extracting header from page {page_num}: {e}")
63
+ return ""
64
+
65
+ def is_blank_page(reader, page_num):
66
+ try:
67
+ page = reader.pages[page_num]
68
+ text = (page.extract_text() or "").strip()
69
+ return len(text) == 0
70
+ except Exception as e:
71
+ logging.warning(f"Failed to check blank page at {page_num}: {e}")
72
+ return False
73
+
74
+ def is_chapter_header(header):
75
+ patterns = [
76
+ r'^\s*chapter\b', r'^\s*section\b', r'^\s*part\b', r'^\s*appendix\b',
77
+ r'^\s*[ivxlcdm]+\.', r'^\s*\d+(\.\d+)*\s', r'^\s*introduction\b'
78
+ ]
79
+ for pat in patterns:
80
+ if re.match(pat, header, re.IGNORECASE):
81
+ return True
82
+ return False
83
+
84
+ def estimate_writer_size(writer):
85
+ import io
86
+ f = io.BytesIO()
87
+ writer.write(f)
88
+ return f.tell()
89
+
90
+ def intelligent_pdf_split(input_path, session_dir, max_mb=5, min_split_mb=4):
91
+ reader = PdfReader(input_path)
92
+ n_pages = len(reader.pages)
93
+ splits = []
94
+ current_writer = PdfWriter()
95
+ split_points = []
96
+ last_header = None
97
+ last_split_at = 0
98
+ for i in range(n_pages):
99
+ page = reader.pages[i]
100
+ current_writer.add_page(page)
101
+ size = estimate_writer_size(current_writer) / (1024 * 1024)
102
+ header = extract_text_headers(reader, i)
103
+ blank = is_blank_page(reader, i)
104
+ chapter = is_chapter_header(header)
105
+ split_here = False
106
+
107
+ # Force split if over max size
108
+ if size >= max_mb:
109
+ split_here = True
110
+ # Prefer to split between min_split_mb and max_mb at logical points
111
+ elif size >= min_split_mb:
112
+ if blank or chapter or (header and header != last_header):
113
+ split_here = True
114
+
115
+ if split_here:
116
+ splits.append((last_split_at, i+1))
117
+ last_split_at = i+1
118
+ current_writer = PdfWriter()
119
+ last_header = header
120
+
121
+ # Add final split if not already
122
+ if last_split_at < n_pages:
123
+ splits.append((last_split_at, n_pages))
124
+
125
+ # Write split files
126
+ split_files = []
127
+ for idx, (start, end) in enumerate(splits):
128
+ writer = PdfWriter()
129
+ for i in range(start, end):
130
+ writer.add_page(reader.pages[i])
131
+ out_path = os.path.join(session_dir, f'split_part_{idx+1}.pdf')
132
+ with open(out_path, 'wb') as f:
133
+ writer.write(f)
134
+ size = os.path.getsize(out_path) / (1024 * 1024)
135
+ split_files.append({'filename': os.path.basename(out_path), 'size': size, 'path': out_path})
136
+ return split_files
137
+
138
+ # Dash app setup
139
+ external_stylesheets = [dbc.themes.BOOTSTRAP]
140
+ app = dash.Dash(__name__, external_stylesheets=external_stylesheets, suppress_callback_exceptions=True)
141
+ server = app.server
142
+
143
+ app.title = "Intelligent PDF Splitter"
144
+
145
+ app.layout = dbc.Container(
146
+ [
147
+ dcc.Store(id='session-store', storage_type='session'),
148
+ html.Div(id='dummy-div', style={'display': 'none'}),
149
+ dbc.Row(
150
+ [
151
+ dbc.Col(
152
+ dbc.Card(
153
+ [
154
+ dbc.CardHeader(html.H2("Intelligent PDF Splitter")),
155
+ dbc.CardBody(
156
+ [
157
+ html.P("Upload your PDF. The tool will split it into context-preserving sections, each under 5MB."),
158
+ dcc.Upload(
159
+ id='upload-pdf',
160
+ children=html.Div([
161
+ 'Drag and Drop or ',
162
+ html.A('Select PDF File')
163
+ ]),
164
+ style={
165
+ 'width': '100%', 'height': '80px', 'lineHeight': '80px',
166
+ 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px',
167
+ 'textAlign': 'center', 'margin': '10px 0'
168
+ },
169
+ multiple=False,
170
+ accept='.pdf'
171
+ ),
172
+ html.Div(id='file-info'),
173
+ dbc.Button("Clear Session", id='clear-session', color='secondary', className='mt-2'),
174
+ dcc.Loading(
175
+ id="loading", type="default",
176
+ children=[html.Div(id='split-results')]
177
+ )
178
+ ]
179
+ )
180
+ ],
181
+ className="mt-4"
182
+ ),
183
+ width=12
184
+ ),
185
+ ]
186
+ )
187
+ ],
188
+ fluid=True,
189
+ className="p-4"
190
+ )
191
+
192
+ @app.callback(
193
+ Output('file-info', 'children'),
194
+ Output('split-results', 'children'),
195
+ Output('session-store', 'data'),
196
+ Input('upload-pdf', 'contents'),
197
+ State('upload-pdf', 'filename'),
198
+ Input('clear-session', 'n_clicks'),
199
+ State('session-store', 'data'),
200
+ prevent_initial_call='initial_duplicate'
201
+ )
202
+ def handle_upload(contents, filename, clear_n, session_data):
203
+ trigger = ctx.triggered_id
204
+ session_id = get_session_id()
205
+ flask.g.session_id = session_id
206
+ session_dir = get_session_dir(session_id)
207
+ lock = get_session_lock(session_id)
208
+
209
+ if trigger == 'clear-session':
210
+ clean_session(session_id)
211
+ resp_data = {}
212
+ return "", "", resp_data
213
+
214
+ # If user returns, restore state
215
+ if not contents and session_data and 'split_files' in session_data:
216
+ split_files = session_data.get('split_files', [])
217
+ file_info = html.Div(f"Previous upload: {session_data.get('orig_filename', '')}")
218
+ results = [
219
+ html.H5("Split Files:"),
220
+ html.Ul([
221
+ html.Li([
222
+ f"{fi['filename']} ({fi['size']:.2f} MB) ",
223
+ dbc.Button("Download", id={'type': 'download-btn', 'index': idx}, href=f"/download/{session_id}/{fi['filename']}", color='primary', size='sm')
224
+ ]) for idx, fi in enumerate(split_files)
225
+ ])
226
+ ]
227
+ return file_info, results, session_data
228
+
229
+ if not contents:
230
+ return "", "", {}
231
+
232
+ if not allowed_file(filename):
233
+ return html.Div("Only .pdf files are allowed.", style={'color': 'red'}), "", {}
234
+
235
+ try:
236
+ # Save file
237
+ header, b64data = contents.split(',', 1)
238
+ import base64
239
+ pdf_bytes = base64.b64decode(b64data)
240
+ pdf_path = os.path.join(session_dir, filename)
241
+ with open(pdf_path, 'wb') as f:
242
+ f.write(pdf_bytes)
243
+ logging.info(f"PDF uploaded and saved to {pdf_path} for session {session_id}")
244
+
245
+ # Split PDF with lock
246
+ with lock:
247
+ split_files = intelligent_pdf_split(pdf_path, session_dir)
248
+ results = [
249
+ html.H5("Split Files:"),
250
+ html.Ul([
251
+ html.Li([
252
+ f"{fi['filename']} ({fi['size']:.2f} MB) ",
253
+ dbc.Button("Download", id={'type': 'download-btn', 'index': idx}, href=f"/download/{session_id}/{fi['filename']}", color='primary', size='sm')
254
+ ]) for idx, fi in enumerate(split_files)
255
+ ])
256
+ ]
257
+ file_info = html.Div(f"Uploaded: {filename} ({len(pdf_bytes)/1024/1024:.2f} MB)")
258
+ session_data = {
259
+ 'orig_filename': filename,
260
+ 'split_files': split_files,
261
+ }
262
+ logging.info(f"PDF split into {len(split_files)} chunks for session {session_id}")
263
+ return file_info, results, session_data
264
+ except Exception as e:
265
+ logging.error(f"Error processing PDF: {e}")
266
+ return html.Div(f"Error: {e}", style={'color': 'red'}), "", {}
267
+
268
+ @app.server.route('/download/<session_id>/<filename>')
269
+ def download_split_file(session_id, filename):
270
+ session_dir = get_session_dir(session_id)
271
+ file_path = os.path.join(session_dir, filename)
272
+ if os.path.exists(file_path):
273
+ logging.info(f"Serving file {file_path} for session {session_id}")
274
+ return send_file(file_path, mimetype='application/pdf', as_attachment=True, download_name=filename)
275
+ else:
276
+ logging.error(f"File not found for download: {file_path}")
277
+ return "File not found", 404
278
+
279
+ @app.callback(
280
+ Output('dummy-div', 'children'),
281
+ Input('session-store', 'data'),
282
+ prevent_initial_call=True
283
+ )
284
+ def set_cookie_on_load(session_data):
285
+ session_id = get_session_id()
286
+ resp = flask.make_response("")
287
+ resp.set_cookie('session-id', session_id, max_age=60*60*24*3)
288
+ return ""
289
+
290
+ @app.server.before_request
291
+ def persist_session_cookie():
292
+ session_id = get_session_id()
293
+ flask.g.session_id = session_id
294
+
295
+ if __name__ == '__main__':
296
+ print("Starting the Dash application...")
297
+ app.run(debug=True, host='0.0.0.0', port=7860, threaded=True)
298
+ print("Dash application has finished running.")