First big push

This commit is contained in:
bsncubed committed 2025-03-18 22:46:53 +11:00
1 parent dbb6acf784
commit 699fc45de8
9 files changed
+325

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
FROM jbarlow83/ocrmypdf:latest
# Install packages, including tzdata for timezone support
RUN apt-get update && apt-get install -y python3-flask python3-pip zip tzdata
WORKDIR /app
# Copy application code and entrypoint script
COPY app /app
COPY entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh
# Install gunicorn using pip with the flag to override external management
RUN pip3 install --break-system-packages gunicorn
# Expose the application port
EXPOSE 5000
# Override the base image's ENTRYPOINT with our custom script
ENTRYPOINT ["/app/entrypoint.sh"]
CMD []
+120
View File
@@ -0,0 +1,120 @@
import os
import shutil
import subprocess
import uuid
from flask import Flask, request, render_template, send_file, jsonify
from werkzeug.utils import secure_filename
app = Flask(__name__)
BASE_UPLOAD_FOLDER = 'uploads'
BASE_OUTPUT_FOLDER = 'output'
os.makedirs(BASE_UPLOAD_FOLDER, exist_ok=True)
os.makedirs(BASE_OUTPUT_FOLDER, exist_ok=True)
def cleanup_session_folders(session_id):
"""Remove any existing session folders to ensure a clean slate."""
upload_folder = os.path.join(BASE_UPLOAD_FOLDER, session_id)
output_folder = os.path.join(BASE_OUTPUT_FOLDER, session_id)
if os.path.exists(upload_folder):
shutil.rmtree(upload_folder)
if os.path.exists(output_folder):
shutil.rmtree(output_folder)
def create_session_folders(session_id):
"""
Clears previous session folders if they exist and creates new ones.
This ensures that files from previous uploads won't mix with new ones.
"""
cleanup_session_folders(session_id)
upload_folder = os.path.join(BASE_UPLOAD_FOLDER, session_id)
output_folder = os.path.join(BASE_OUTPUT_FOLDER, session_id)
os.makedirs(upload_folder, exist_ok=True)
os.makedirs(output_folder, exist_ok=True)
return upload_folder, output_folder
def run_ocrmypdf(input_pdf, output_pdf):
cmd = [
'ocrmypdf',
'--rotate-pages',
'--deskew',
'--output-type', 'pdfa',
'--jobs', '4',
input_pdf,
output_pdf
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
if "PriorOcrFoundError" in result.stderr:
raise ValueError("This file already contains selectable text and was skipped.")
else:
raise RuntimeError(f"OCRmyPDF failed: {result.stderr}")
@app.route('/')
def index():
# Generate a new session id for each visitor.
session_id = str(uuid.uuid4())
return render_template('index.html', session_id=session_id)
@app.route('/upload/<session_id>', methods=['POST'])
def upload_files(session_id):
# Create fresh session folders, clearing any previous data.
upload_folder, output_folder = create_session_folders(session_id)
if 'files' not in request.files:
return jsonify({'error': 'No files were uploaded.'}), 400
files = request.files.getlist('files')
processed_files = []
skipped_files = []
for file in files:
if file.filename == '':
continue
filename = secure_filename(file.filename)
input_path = os.path.join(upload_folder, filename)
output_path = os.path.join(output_folder, filename)
file.save(input_path)
try:
run_ocrmypdf(input_path, output_path)
processed_files.append(filename)
except ValueError:
skipped_files.append(filename)
except Exception as e:
# If there's an error, cleanup the session folders
cleanup_session_folders(session_id)
return jsonify({'error': f"Failed to process {filename}: {str(e)}"}), 500
if not processed_files:
return jsonify({
'error': 'All files were skipped because they already contain selectable text.',
'skipped_files': skipped_files
})
# Create a zip file containing only the current upload's processed files.
zip_filename = os.path.join(output_folder, 'processed_files.zip')
subprocess.run(['zip', '-j', zip_filename] + [os.path.join(output_folder, f) for f in processed_files])
return jsonify({
'download_url': f'/download/{session_id}/processed_files.zip',
'processed_files': processed_files,
'skipped_files': skipped_files
})
@app.route('/download/<session_id>/<filename>')
def download_file(session_id, filename):
file_path = os.path.join(BASE_OUTPUT_FOLDER, session_id, filename)
return send_file(file_path, as_attachment=True)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=False)
+7
View File
@@ -0,0 +1,7 @@
/*!
* Bootstrap v4.5.2 (https://getbootstrap.com/)
* Copyright 2011-2020 The Bootstrap Authors
* Copyright 2011-2020 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
*/:root{--blue:#007bff;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#dc3545;--orange:#fd7e14;--yellow:#ffc107;--green:#28a745;--teal:#20c997;--cyan:#17a2b8;--white:#fff;--gray:#6c757d;--gray-dark:#343a40;--primary:#007bff;--secondary:#6c757d;--success:#28a745;--info:#17a2b8;--warning:#ffc107;--danger:#dc3545;--light:#f8f9fa;--dark:#343a40;--breakpoint-xs:0;--breakpoint-sm:576px;--breakpoint-md:768px;--breakpoint-lg:992px;--breakpoint-xl:1200px;--font-family-sans-serif:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-family-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff}[tabindex="-1"]:focus:not(:focus-visible){outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#007bff;text-decoration:none;background-color:transparent}a:hover{color:#0056b3;text-decoration:underline}a:not([href]):not([class]){color:inherit;text-decoration:none}a:not([href]):not([class]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto;-ms-overflow-style:scrollbar}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg{overflow:hidden;vertical-align:middle}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#6c757d;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}[role=button]{cursor:pointer}select{word-wrap:normal}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item;cursor:pointer}template{display:none}[hidden]{display:none!important}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{margin-bottom:.5rem;font-weight:500;line-height:1.2}.h1,h1{font-size:2.5rem}.h2,h2{font-size:2rem}.h3,h3{font-size:1.75rem}.h4,h4{font-size:1.5rem}.h5,h5{font-size:1.25rem}.h6,h6{font-size:1rem}.lead{font-size:1.25rem;font-weight:300}.display-1{font-size:6rem;font-weight:300;line-height:1.2}.display-2{font-size:5.5rem;font-weight:300;line-height:1.2}.display-3{font-size:4.5rem;font-weight:300;line-height:1.2}.display-4{font-size:3.5rem;font-weight:300;line-height:1.2}hr{margin-top:1rem;margin-bottom:1rem;border:0;border-top:1px solid rgba(0,0,0,.1)}.small,small{font-size:80%;font-weight:400}.mark,mark{padding:.2em;background-color:#fcf8e3}.list-unstyled{padding-left:0;lLine truncated
/*# sourceMappingURL=bootstrap.min.css.map */
+153
View File
@@ -0,0 +1,153 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OCRmyPDF WebUI</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Inline minimal CSS for styling (no external dependencies) -->
<style>
/* Basic reset */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: Arial, sans-serif;
background-color: #f8f9fa;
padding: 20px;
}
.container {
max-width: 800px;
margin: auto;
background: #fff;
padding: 20px;
border-radius: 0.3em;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
h2 {
margin-bottom: 20px;
}
input[type="file"] {
margin-bottom: 10px;
}
.btn {
display: inline-block;
padding: 0.5rem 1rem;
font-size: 1rem;
font-weight: bold;
text-align: center;
color: #fff;
background-color: #007bff;
border: none;
border-radius: 0.25rem;
cursor: pointer;
text-decoration: none;
}
.btn:disabled {
opacity: 0.65;
cursor: not-allowed;
}
.alert {
padding: 0.75rem 1.25rem;
margin: 1rem 0;
border: 1px solid transparent;
border-radius: 0.25rem;
}
.alert-info {
color: #055160;
background-color: #cff4fc;
border-color: #b6effb;
}
.alert-success {
color: #0f5132;
background-color: #d1e7dd;
border-color: #badbcc;
}
.alert-danger {
color: #842029;
background-color: #f8d7da;
border-color: #f5c2c7;
}
.mt-2 {
margin-top: 0.5rem;
}
.mt-3 {
margin-top: 1rem;
}
.mt-5 {
margin-top: 3rem;
}
.mb-4 {
margin-bottom: 1.5rem;
}
</style>
<!-- Inline JavaScript -->
<script>
async function uploadFiles(sessionId) {
const files = document.getElementById('fileInput').files;
const formData = new FormData();
const uploadBtn = document.getElementById('uploadBtn');
const status = document.getElementById('status');
const resultLink = document.getElementById('resultLink');
const processedList = document.getElementById('processedList');
const skippedList = document.getElementById('skippedList');
resultLink.style.display = 'none';
processedList.innerHTML = '';
skippedList.innerHTML = '';
status.innerHTML = '';
for (let i = 0; i < files.length; i++) {
formData.append('files', files[i]);
}
uploadBtn.disabled = true;
uploadBtn.innerHTML = 'Processing...';
status.innerHTML = '<div class="alert alert-info">Processing files, please wait...</div>';
try {
const response = await fetch(`/upload/${sessionId}`, {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.download_url) {
status.innerHTML = '<div class="alert alert-success">Processing complete! Download your files below.</div>';
resultLink.href = result.download_url;
resultLink.style.display = 'block';
if (result.processed_files && result.processed_files.length > 0) {
processedList.innerHTML = '<strong>Processed Files:</strong><br>' + result.processed_files.join('<br>');
}
if (result.skipped_files && result.skipped_files.length > 0) {
skippedList.innerHTML = '<strong>Skipped Files (Already Contain Text):</strong><br>' + result.skipped_files.join('<br>');
}
} else {
status.innerHTML = '<div class="alert alert-danger">' + (result.error || 'Unknown error occurred.') + '</div>';
}
} catch (error) {
status.innerHTML = '<div class="alert alert-danger">Error: ' + error.message + '</div>';
} finally {
uploadBtn.disabled = false;
uploadBtn.innerHTML = 'Upload and Process';
}
}
</script>
</head>
<body>
<div class="container mt-5">
<h2 class="mb-4">OCRmyPDF WebUI</h2>
<input type="file" id="fileInput" multiple>
<button id="uploadBtn" class="btn" onclick="uploadFiles('{{ session_id }}')">Upload and Process</button>
<div id="status" class="mt-3"></div>
<div id="processedList" class="mt-2"></div>
<div id="skippedList" class="mt-2"></div>
<a id="resultLink" class="btn mt-3" href="#" style="display:none;">Download Processed Files (ZIP)</a>
</div>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
services:
webui:
build: .
ports:
- "5000:5000"
# volumes:
# - ./uploads:/app/uploads
# - ./output:/app/output
environment:
- GUNICORN_TIMEOUT=300
- TZ=Australia/Sydney
Executable
+13
View File
@@ -0,0 +1,13 @@
#!/bin/bash
# Set timezone if TZ environment variable is provided
if [ -n "$TZ" ]; then
ln -snf /usr/share/zoneinfo/$TZ /etc/localtime
echo "$TZ" > /etc/timezone
fi
# Set a default Gunicorn timeout if not provided via environment variable
: ${GUNICORN_TIMEOUT:=30}
echo "Starting Gunicorn with timeout ${GUNICORN_TIMEOUT} seconds..."
# Start Gunicorn with the specified timeout
exec gunicorn --timeout "$GUNICORN_TIMEOUT" --workers 4 --bind 0.0.0.0:5000 app:app