import csv
import multiprocessing
import os
import tempfile
import ocrmypdf
import pandas as pd
from flask import Flask, after_this_request, render_template_string, request, send_file
from openpyxl import load_workbook
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024
PAGE = """
Document Converter Pro
Document Converter Pro
Fast OCR and spreadsheet conversion in one focused workspace. Upload your file, watch the process complete, then download only when the processed document is ready.
PDF OCR
Excel to CSV
Fast mode
Private processing
{% if message %}
{{ message }}
{% endif %}
OCR engine
PDF OCR Converter
Turn scanned PDFs into searchable documents. Fast mode skips pages that already contain selectable text.
Best for: scanned PDFs, contracts, reports, office paperwork.
Tip: use high accuracy only when fast mode misses text.
Spreadsheet export
Excel to CSV Converter
Convert the first worksheet into a clean CSV file using a memory-efficient streaming path for XLSX workbooks.
Best for: tables, exports, lead lists, accounting sheets.
Output: first worksheet saved as UTF-8 CSV.
"""
def render_page(message=None):
return render_template_string(PAGE, message=message)
@app.get("/")
def index():
return render_page()
@app.get("/health")
def health():
return {"status": "ok"}
def remove_later(path):
def cleanup():
try:
os.remove(path)
except OSError:
pass
@after_this_request
def schedule_cleanup(response):
response.call_on_close(cleanup)
return response
def save_pdf_upload(uploaded):
if not uploaded or uploaded.filename == "":
raise ValueError("Please upload a PDF file.")
filename = secure_filename(uploaded.filename)
if not filename.lower().endswith(".pdf"):
raise ValueError("Please upload a valid PDF file.")
input_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
input_file.close()
uploaded.save(input_file.name)
return filename, input_file.name
def ocr_options(mode):
workers = max(1, min(4, multiprocessing.cpu_count()))
if mode == "accurate":
return {
"force_ocr": True,
"deskew": True,
"rotate_pages": True,
"oversample": 300,
"optimize": 1,
"jobs": workers,
"progress_bar": False,
}
return {
"skip_text": True,
"deskew": False,
"rotate_pages": False,
"oversample": 150,
"optimize": 1,
"jobs": workers,
"progress_bar": False,
}
@app.post("/ocr")
def ocr_pdf():
output_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
output_file.close()
output_path = output_file.name
output_sent = False
input_path = None
try:
filename, input_path = save_pdf_upload(request.files.get("pdf_file"))
os.remove(output_path)
ocrmypdf.ocr(
input_path,
output_path,
**ocr_options(request.form.get("mode", "fast")),
)
download_name = f"ocr_{filename}"
remove_later(output_path)
output_sent = True
return send_file(output_path, as_attachment=True, download_name=download_name)
except ValueError as exc:
return render_page(str(exc)), 400
except Exception as exc:
return render_page(f"OCR failed: {exc}"), 500
finally:
if input_path:
try:
os.remove(input_path)
except OSError:
pass
if not output_sent:
try:
os.remove(output_path)
except OSError:
pass
def convert_xlsx_to_csv(input_path, output_path):
workbook = load_workbook(input_path, read_only=True, data_only=True)
try:
sheet = workbook.active
with open(output_path, "w", newline="", encoding="utf-8") as csv_file:
writer = csv.writer(csv_file)
for row in sheet.iter_rows(values_only=True):
writer.writerow(["" if value is None else value for value in row])
finally:
workbook.close()
def convert_excel_file(input_path, output_path, extension):
if extension == ".xlsx":
convert_xlsx_to_csv(input_path, output_path)
return
df = pd.read_excel(
input_path,
dtype=str,
parse_dates=False,
keep_default_na=False,
)
df.to_csv(output_path, index=False, encoding="utf-8")
@app.post("/excel")
def excel_to_csv():
uploaded = request.files.get("excel_file")
if not uploaded or uploaded.filename == "":
return render_page("Please upload an Excel file."), 400
filename = secure_filename(uploaded.filename)
if not filename.lower().endswith((".xlsx", ".xls")):
return render_page("Please upload a valid Excel file."), 400
extension = os.path.splitext(filename)[1].lower()
input_file = tempfile.NamedTemporaryFile(suffix=extension, delete=False)
output_file = tempfile.NamedTemporaryFile(suffix=".csv", delete=False)
input_file.close()
output_file.close()
try:
uploaded.save(input_file.name)
convert_excel_file(input_file.name, output_file.name, extension)
download_name = f"{os.path.splitext(filename)[0]}.csv"
remove_later(output_file.name)
return send_file(output_file.name, as_attachment=True, download_name=download_name)
except Exception as exc:
return render_page(f"Conversion failed: {exc}"), 500
finally:
try:
os.remove(input_file.name)
except OSError:
pass
if __name__ == "__main__":
app.run(
host=os.getenv("HOST", "0.0.0.0"),
port=int(os.getenv("PORT", "7860")),
)