Scanlly / app.py
VsinghiAssociates's picture
Upload folder using huggingface_hub
2d875c8 verified
Raw History Blame Contribute Delete
84.8 kB
import json import os import secrets import hashlib import hmac import uuid import tempfile from io import BytesIO from queue import Queue from threading import Thread from dotenv import load_dotenv from flask import ( Flask, Response, render_template_string, request, send_file, stream_with_context, jsonify, ) from werkzeug.utils import secure_filename import razorpay from pypdf import PdfReader from openpyxl import load_workbook import pandas as pd from services import ( excel_to_csv_process, pdf_delete_pages_process, pdf_merge_process, pdf_split_process, pdf_to_word_process, summarize_process, pdf_ocr_process, bank_statement_process, ) from statement_parser import BANK_NAMES as STAT_BANK_NAMES from statement_parser import excel_bytes_from_df from statement_parser import parse_statement_pdf load_dotenv() OCR_PRICE_PER_PAGE_PAISE = 500 PDF_FREE_PAGES = 10 PDF_EXTRA_PAGE_PRICE_PAISE = 200 EXCEL_FREE_ROWS = 500 EXCEL_PRICE_PER_EXTRA_ROW_PAISE = 20 EXCEL_MAX_ROWS = 50000 PENDING_ORDERS = {} BYPASS_ACCESS_KEY = os.getenv("OCR_BYPASS_KEY", "215836").strip() PDF_SERVICES = { "pdf-ocr": "Searchable PDF OCR", "pdf-to-word": "PDF to Word", "pdf-split": "PDF Splitter", "pdf-merge": "PDF Merger", "pdf-delete-pages": "PDF Delete Pages", "summarize": "Document Summarizer", } EXCEL_SERVICE = "excel-to-csv" def razorpay_keys(): key_id = os.getenv("RAZORPAY_KEY_ID", "").strip() key_secret = os.getenv("RAZORPAY_KEY_SECRET", "").strip() if not key_id or not key_secret: raise RuntimeError("Razorpay keys are not configured. Set RAZORPAY_KEY_ID and RAZORPAY_KEY_SECRET.") return key_id, key_secret def verify_razorpay_signature(order_id, payment_id, signature): try: _, key_secret = razorpay_keys() except RuntimeError: return False message = f"{order_id}|{payment_id}".encode("utf-8") expected = hmac.new(key_secret.encode("utf-8"), message, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature or "") def has_valid_bypass_key(): access_key = request.form.get("access_key", "").strip() return bool(BYPASS_ACCESS_KEY and hmac.compare_digest(access_key, BYPASS_ACCESS_KEY)) def count_pdf_pages(path, password=None): reader = PdfReader(path) if reader.is_encrypted: if password: try: reader.decrypt(password) except Exception: raise ValueError("Incorrect password for protected PDF.") else: raise ValueError("This PDF is password-protected. Please enter the PDF password.") return len(reader.pages) def count_excel_rows(input_path, extension): if extension in (".xlsx", ".xlsm"): workbook = load_workbook(input_path, read_only=True, data_only=True) try: sheet = workbook.active rows = sum(1 for _ in sheet.iter_rows(values_only=True)) finally: workbook.close() return rows return len(pd.read_excel(input_path, header=None)) def order_amount_for(service, path=None, pages=None, num_pdfs=None, excel_rows=None, bank_entries=None, password=None): if path and pages is None: try: pages = count_pdf_pages(path, password=password) except Exception: pages = 0 if service == "pdf-ocr": if pages is None or pages < 1: raise ValueError("This PDF does not contain any pages.") amount = pages * 200 # 2 Rs per page return amount, pages, f"{pages} page{'s' if pages != 1 else ''} x INR 2.00 = INR {amount / 100:.2f}" elif service == "pdf-split": if pages is None or pages < 1: raise ValueError("This PDF does not contain any pages.") if pages <= 100: amount = 0 summary = f"{pages} page{'s' if pages != 1 else ''}. Free tier applied (up to 100 pages free)." else: extra = pages - 100 if extra < 51: amount = 0 summary = f"{pages} page{'s' if pages != 1 else ''}. Free tier applied (first 100 pages free + {extra} extra page{'s' if extra != 1 else ''} free, as extra is less than 51)." else: amount = extra * 2 # 2 paise per page summary = f"First 100 pages free + {extra} extra page{'s' if extra != 1 else ''} x INR 0.02 = INR {amount / 100:.2f}" return amount, pages, summary elif service == "pdf-merge": if num_pdfs is None: raise ValueError("Number of PDFs is required for merge calculation.") if num_pdfs <= 10: amount = 0 summary = f"{num_pdfs} PDF{'s' if num_pdfs != 1 else ''}. Free tier applied (up to 10 PDFs free)." else: extra = num_pdfs - 10 amount = extra * 2 # 2 paise per PDF summary = f"10 PDFs free + {extra} extra PDF{'s' if extra != 1 else ''} x INR 0.02 = INR {amount / 100:.2f}" return amount, num_pdfs, summary elif service == "pdf-to-word": if pages is None or pages < 1: raise ValueError("This PDF does not contain any pages.") if pages <= 100: amount = 0 summary = f"{pages} page{'s' if pages != 1 else ''}. Free tier applied (up to 100 pages free)." else: extra = pages - 100 amount = extra * 2 # 2 paise per page summary = f"100 pages free + {extra} extra page{'s' if extra != 1 else ''} x INR 0.02 = INR {amount / 100:.2f}" return amount, pages, summary elif service == "pdf-delete-pages": return 0, pages or 0, "Always free." elif service == "summarize": # Keep summarize free or default return 0, pages or 0, "Always free." elif service == "excel-to-csv": if excel_rows is None: raise ValueError("Excel row count is required.") if excel_rows > EXCEL_MAX_ROWS: raise ValueError("Excel files above 50,000 rows are not supported.") if excel_rows <= 10000: amount = 0 summary = f"{excel_rows} rows. Free tier applied (up to 10,000 entries free)." else: extra = excel_rows - 10000 groups = (extra + 9) // 10 amount = groups * 2 # 2 paise for each 10 entry summary = f"10,000 entries free + {extra} extra entries ({groups} groups of 10) x INR 0.02 = INR {amount / 100:.2f}" return amount, excel_rows, summary elif service.startswith("bank-"): if bank_entries is None: raise ValueError("Bank entry count is required.") amount = bank_entries * 8 # 8 paise per entry summary = f"{bank_entries} entries x INR 0.08 = INR {amount / 100:.2f}" return amount, bank_entries, summary raise ValueError("Unknown paid service.") def create_order(service, amount, pages_or_rows): if amount == 0: return "", None key_id, key_secret = razorpay_keys() client = razorpay.Client(auth=(key_id, key_secret)) order = client.order.create( { "amount": amount, "currency": "INR", "receipt": f"scanly_{uuid.uuid4().hex[:25]}", "notes": { "service": service, "pages_or_rows": str(pages_or_rows), "amount": str(amount), }, } ) PENDING_ORDERS[order["id"]] = { "amount": amount, "pages_or_rows": pages_or_rows, "service": service, "currency": "INR", } return key_id, order app = Flask(__name__) ROOT = os.path.dirname(__file__) INDEX_HTML = os.path.join(ROOT, "templatemo_622_clearwave", "index.html") # ── In-memory task store ────────────────────────────────────────────────── # task_id → {"queue": Queue, "result": bytes|None, "error": str|None, "fname": str, "mime": str} _pending: dict[str, dict] = {} def _run_task(task_id: str, fn, *args, **kwargs): entry = _pending[task_id] q: Queue = entry["queue"] def _progress(pct, msg): q.put({"type": "progress", "percent": pct, "message": msg}) try: result = fn(*args, progress_callback=_progress, **kwargs) entry["result"] = result if isinstance(result, bytes) else result.read() q.put({"type": "done"}) except Exception as exc: entry["error"] = str(exc) q.put({"type": "error", "message": str(exc)}) # ── Index ────────────────────────────────────────────────────────────────── @app.route("/") def index(): if not os.path.exists(INDEX_HTML): return "SCANLY home page not found.", 404 with open(INDEX_HTML, "r", encoding="utf-8") as fh: return fh.read() @app.route("/assets/<path:filename>") def assets(filename): from flask import send_from_directory return send_from_directory(ROOT, filename) # ── SSE progress endpoint ───────────────────────────────────────────────── @app.route("/progress/<task_id>") def progress_stream(task_id): entry = _pending.get(task_id) if not entry: return Response( "data: " + json.dumps({"type": "done"}) + "\n\n", mimetype="text/event-stream", ) q = entry["queue"] def generate(): while True: msg = q.get() yield "data: " + json.dumps(msg) + "\n\n" if msg["type"] in ("done", "error"): break return Response(stream_with_context(generate()), mimetype="text/event-stream") # ── Multi-purpose service page template ─────────────────────────────────── SERVICE_SHELL = r"""<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>{{ title }} | SCANLY</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&family=DM+Sans:wght@400;500;700&family=Fredoka:wght@500;600;700;800&display=swap" rel="stylesheet"> <style> :root { --bg: #0b0f19; --card-bg: rgba(20, 28, 48, 0.6); --border: rgba(255, 255, 255, 0.08); --border-hover: rgba(0, 242, 254, 0.4); --text: #f3f4f6; --text-muted: #9ca3af; --accent: #00f2fe; --accent-hover: #4facfe; --glow: rgba(0, 242, 254, 0.15); --font-body: 'Plus Jakarta Sans', sans-serif; --font-title: 'Plus Jakarta Sans', sans-serif; } body.light-theme { --bg: #fff9f0; --card-bg: #fff; --border: rgba(47, 42, 34, 0.12); --border-hover: #2f2a22; --text: #2f2a22; --text-muted: #756d61; --accent: #2fd0af; --accent-hover: #1e8f77; --glow: rgba(47, 42, 34, 0.08); --font-body: "DM Sans", sans-serif; --font-title: "Fredoka", sans-serif; background-color: var(--bg); background-image: radial-gradient(circle, rgba(47,42,34,0.16) 0.8px, transparent 0.9px); background-size: 28px 28px; } * { box-sizing: border-box; transition: transform 0.25s ease, box-shadow 0.25s ease, background 0.25s ease, border-color 0.25s ease, color 0.25s ease; } body { margin: 0; min-height: 100vh; font-family: var(--font-body); background: var(--bg); color: var(--text); background-image: radial-gradient(circle at 50% 50%, #1e293b 0%, #0b0f19 100%); display: flex; align-items: center; justify-content: center; padding: 40px 20px; } body.light-theme { background-image: radial-gradient(circle, rgba(47,42,34,0.16) 0.8px, transparent 0.9px); background-size: 28px 28px; } .page { width: 100%; max-width: 600px; background: var(--card-bg); border: 1px solid var(--border); border-radius: 20px; padding: 40px; backdrop-filter: blur(16px); box-shadow: 0 20px 50px rgba(0, 0, 0, 0.4); position: relative; } body.light-theme .page { border-radius: 8px; border: 2px solid var(--border); box-shadow: 0 12px 28px rgba(47, 42, 34, 0.1); backdrop-filter: none; } .brand { font-weight: 800; letter-spacing: .25em; color: var(--accent); text-transform: uppercase; font-size: 0.9rem; margin-bottom: 24px; font-family: var(--font-title); } body.light-theme .brand { color: var(--text-muted); } h1 { margin: 0 0 10px; font-size: clamp(1.8rem, 4vw, 2.5rem); font-weight: 800; background: linear-gradient(to right, #ffffff, #9ca3af); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-family: var(--font-title); } body.light-theme h1 { margin: 28px 0 8px; font-size: clamp(2rem, 4vw, 3.2rem); background: none; -webkit-background-clip: initial; -webkit-text-fill-color: initial; color: var(--text); } .sub { color: var(--text-muted); margin-bottom: 30px; font-size: 1rem; line-height: 1.6; } .privacy-badge { display: inline-flex; align-items: center; gap: 8px; background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.2); color: #34d399; padding: 12px 16px; border-radius: 12px; font-size: 0.85rem; font-weight: 600; margin-bottom: 24px; width: 100%; } body.light-theme .privacy-badge { background: rgba(16, 185, 129, 0.08); border: 2px solid rgba(47, 42, 34, 0.12); color: #0f766e; border-radius: 8px; } form { display: grid; gap: 20px; } body.light-theme form { gap: 16px; padding: 28px; border: 2px solid rgba(47, 42, 34, 0.12); border-radius: 8px; box-shadow: 0 12px 28px rgba(47, 42, 34, 0.1); } label { font-weight: 600; font-size: 0.9rem; color: var(--text); display: flex; flex-direction: column; gap: 8px; } input[type=file] { width: 100%; padding: 14px; border: 1px dashed var(--border); border-radius: 12px; background: rgba(255, 255, 255, 0.02); color: var(--text-muted); cursor: pointer; } input[type=file]:hover { border-color: var(--border-hover); background: rgba(0, 242, 254, 0.02); } body.light-theme input[type=file] { padding: 12px; border: 2px solid rgba(47, 42, 34, 0.14); border-radius: 8px; background: rgba(255, 255, 255, 0.8); } select, input[type=password], input[type=text], input[type=number] { width: 100%; padding: 14px; border: 1px solid var(--border); border-radius: 12px; background: rgba(255, 255, 255, 0.04); color: var(--text); font-size: 1rem; font-family: inherit; outline: none; } select:focus, input[type=password]:focus, input[type=text]:focus, input[type=number]:focus { border-color: var(--accent); box-shadow: 0 0 10px var(--glow); background: rgba(255, 255, 255, 0.06); } body.light-theme select, body.light-theme input[type=password], body.light-theme input[type=text], body.light-theme input[type=number] { padding: 12px; border: 2px solid rgba(47, 42, 34, 0.14); border-radius: 8px; background: rgba(255, 255, 255, 0.8); font-size: 1rem; } button { padding: 16px; border: none; border-radius: 12px; background: linear-gradient(135deg, var(--accent), var(--accent-hover)); color: #0b0f19; font-weight: 800; cursor: pointer; font-size: 1.05rem; box-shadow: 0 4px 15px rgba(0, 242, 254, 0.3); } button:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0, 242, 254, 0.4); } body.light-theme button { padding: 14px; border: 2px solid var(--border-hover); border-radius: 999px; background: var(--accent); box-shadow: 3px 4px 0 rgba(47, 42, 34, 0.12); color: #071915; font-weight: 800; font-size: 1rem; } body.light-theme button:hover { transform: translateY(-2px); box-shadow: 5px 6px 0 rgba(47, 42, 34, 0.12); } #progress-wrap { display: none; margin-top: 24px; background: rgba(255, 255, 255, 0.02); padding: 20px; border: 1px solid var(--border); border-radius: 12px; } body.light-theme #progress-wrap { background: #fff; padding: 18px; border: 2px solid rgba(47, 42, 34, 0.1); border-radius: 8px; } .pbar { height: 8px; background: rgba(255, 255, 255, 0.08); border-radius: 999px; overflow: hidden; } body.light-theme .pbar { height: 12px; background: #e8e2d8; } .pfill { height: 100%; width: 0%; background: linear-gradient(to right, var(--accent), var(--accent-hover)); border-radius: 999px; } body.light-theme .pfill { background: var(--accent); } #pmsg { margin-top: 12px; color: var(--text-muted); font-size: .9rem; } .back { display: inline-flex; align-items: center; color: var(--text-muted); text-decoration: none; font-size: 0.9rem; margin-bottom: 20px; gap: 6px; } .back:hover { color: var(--accent); } body.light-theme .back:hover { text-decoration: underline; color: var(--text); } .note { background: rgba(251, 191, 36, 0.05); border: 1px solid rgba(251, 191, 36, 0.2); color: #fbbf24; padding: 14px; border-radius: 12px; margin-top: 20px; font-size: 0.9rem; line-height: 1.5; } body.light-theme .note { background: #fff2b8; border: 2px solid rgba(47, 42, 34, 0.12); border-radius: 8px; color: var(--text); } /* Theme Toggle Button */ .theme-toggle-btn { position: absolute; top: 24px; right: 24px; width: 48px; height: 48px; border-radius: 12px; border: 1px solid var(--border); background: var(--card-bg); cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2); z-index: 100; } .theme-toggle-btn:hover { border-color: var(--accent); transform: scale(1.05); } body.light-theme .theme-toggle-btn { border: 2px solid var(--border-hover); background: #fff; box-shadow: 3px 4px 0 rgba(47,42,34,0.12); border-radius: 50%; } body.light-theme .theme-toggle-btn .sun-icon { display: none; } body.light-theme .theme-toggle-btn .moon-icon { display: block; } body:not(.light-theme) .theme-toggle-btn .sun-icon { display: block; } body:not(.light-theme) .theme-toggle-btn .moon-icon { display: none; } </style> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> </head> <body> <button id="theme-toggle" class="theme-toggle-btn" aria-label="Toggle theme"> <span class="sun-icon">☀️</span> <span class="moon-icon">🌙</span> </button> <div class="page"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;"> <a class="back" href="/" style="margin-bottom: 0;">&larr; Home</a> <a class="back" href="/pricing" style="margin-bottom: 0;">💰 Pricing</a> </div> <div class="brand">SCANLY</div> <h1>{{ title }}</h1> <p class="sub">{{ subtitle }}</p> <div class="privacy-badge">🔒 We don't save your data. All processing is done in-memory and immediately deleted.</div> {% if hint %} <div class="note">💡 {{ hint }}</div> {% endif %} <form id="upload-form" enctype="multipart/form-data"> <label> {{ field_label }} <input type="file" name="file"{% if accept %} accept="{{ accept }}"{% endif %} required{% if multiple %} multiple{% endif %}> </label> {% if select_input %} <label> {{ select_input.label }} <select name="{{ select_input.name }}"> {% for val, display in select_input.options %} <option value="{{ val }}">{{ display }}</option> {% endfor %} </select> </label> {% endif %} {% if extra_input %} <label> {{ extra_input.label }} <input type="{{ extra_input.type }}" name="{{ extra_input.name }}" placeholder="{{ extra_input.placeholder }}" required> </label> {% endif %} <label> PDF Password (Optional, if protected) <input type="password" name="pdf_password" autocomplete="off" placeholder="Password (if file is encrypted)"> </label> <label> Access Key (Optional) <input type="password" name="access_key" autocomplete="off" placeholder="Access key for free processing"> </label> <button type="submit">{{ btn_label }}</button> </form> <div id="progress-wrap"> <div class="pbar"><div class="pfill" id="pfill"></div></div> <p id="pmsg">Starting…</p> </div> </div> <script> // Theme Initialization const currentTheme = localStorage.getItem('theme') || 'dark'; if (currentTheme === 'light') { document.body.classList.add('light-theme'); } document.getElementById('theme-toggle').addEventListener('click', () => { document.body.classList.toggle('light-theme'); const theme = document.body.classList.contains('light-theme') ? 'light' : 'dark'; localStorage.setItem('theme', theme); }); const form = document.getElementById('upload-form'); const pw = document.getElementById('progress-wrap'); const pfill = document.getElementById('pfill'); const pmsg = document.getElementById('pmsg'); form.addEventListener('submit', async (e) => { e.preventDefault(); pw.style.display = 'block'; pfill.style.width = '0%'; pmsg.textContent = 'Uploading…'; const fd = new FormData(form); const accessKey = fd.get("access_key"); if (accessKey && accessKey.trim()) { pmsg.textContent = 'Access key provided, bypassing payment check...'; } else { pmsg.textContent = 'Calculating page/row count & cost...'; fd.append("service", "{{ slug }}"); try { const orderResp = await fetch("/payment/order", { method: "POST", body: fd }); if (!orderResp.ok) { const errText = await orderResp.text(); pmsg.textContent = '❌ ' + errText; return; } const order = await orderResp.json(); if (!order.free) { pmsg.textContent = `Calculated cost: INR ${order.display_amount}. Opening Razorpay...`; const payment = await new Promise((resolve, reject) => { const checkout = new Razorpay({ key: order.key, amount: order.amount, currency: order.currency, name: "SCANLY", description: order.description, order_id: order.order_id, handler: resolve, modal: { ondismiss: () => reject(new Error("Payment was not completed.")), }, theme: { color: document.body.classList.contains('light-theme') ? "#2fd0af" : "#00f2fe", }, }); checkout.on("payment.failed", (response) => { reject(new Error(response.error ? response.error.description : "Payment failed.")); }); checkout.open(); }); fd.append("razorpay_payment_id", payment.razorpay_payment_id); fd.append("razorpay_order_id", payment.razorpay_order_id); fd.append("razorpay_signature", payment.razorpay_signature); } } catch (err) { pmsg.textContent = '❌ ' + err.message; return; } } pmsg.textContent = 'Starting service task...'; const resp = await fetch('{{ action }}', { method:'POST', body:fd }); if (!resp.ok) { pmsg.textContent = 'Error: ' + (await resp.text()); return; } const taskId = resp.headers.get('X-Task-Id'); if (!taskId) { const blob = await resp.blob(); const disp = resp.headers.get('Content-Disposition') || ''; const m = disp.match(/filename="?(.+?)"?$/); const fname = m ? m[1] : 'download'; const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = fname; a.click(); pw.style.display = 'none'; return; } let startTime = Date.now(); const evt = new EventSource('/progress/' + taskId); evt.onmessage = (ev) => { const d = JSON.parse(ev.data); if (d.type === 'progress') { pfill.style.width = Math.min(d.percent, 100) + '%'; let elapsed = (Date.now() - startTime) / 1000; let timeRemainingStr = ""; if (d.percent > 5 && d.percent < 100) { let totalEstimatedTime = (elapsed / d.percent) * 100; let remaining = totalEstimatedTime - elapsed; if (remaining > 0) { let mins = Math.floor(remaining / 60); let secs = Math.ceil(remaining % 60); timeRemainingStr = ` (Estimated time remaining: ${mins > 0 ? mins + 'm ' : ''}${secs}s)`; } } pmsg.textContent = d.message + timeRemainingStr; } else if (d.type === 'done') { pfill.style.width = '100%'; pmsg.textContent = 'Downloading…'; evt.close(); fetch('/download/' + taskId).then(r => { const disp = r.headers.get('Content-Disposition') || ''; const m = disp.match(/filename="?(.+?)"?$/); const fname = m ? m[1] : 'result'; return r.blob().then(blob => ({ blob, fname })); }).then(({ blob, fname }) => { const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = fname; a.click(); pw.style.display = 'none'; }); } else if (d.type === 'error') { pmsg.textContent = '❌ ' + d.message; pw.style.display = 'none'; evt.close(); } }; }); </script> </body> </html>""" PRICING_TEMPLATE = r"""<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>Pricing Plans | SCANLY</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&family=DM+Sans:wght@400;500;700&family=Fredoka:wght@500;600;700;800&display=swap" rel="stylesheet"> <style> :root { --bg: #0b0f19; --card-bg: rgba(20, 28, 48, 0.6); --border: rgba(255, 255, 255, 0.08); --border-hover: rgba(0, 242, 254, 0.4); --text: #f3f4f6; --text-muted: #9ca3af; --accent: #00f2fe; --accent-hover: #4facfe; --glow: rgba(0, 242, 254, 0.15); --font-body: 'Plus Jakarta Sans', sans-serif; --font-title: 'Plus Jakarta Sans', sans-serif; --shadow: 0 20px 40px rgba(0, 0, 0, 0.3); } body.light-theme { --bg: #fff9f0; --card-bg: #fff; --border: rgba(47, 42, 34, 0.12); --border-hover: #2f2a22; --text: #2f2a22; --text-muted: #756d61; --accent: #2fd0af; --accent-hover: #1e8f77; --glow: rgba(47, 42, 34, 0.08); --font-body: "DM Sans", sans-serif; --font-title: "Fredoka", sans-serif; --shadow: 0 24px 48px rgba(47, 42, 34, 0.16); } * { box-sizing: border-box; transition: transform 0.25s ease, box-shadow 0.25s ease, background 0.25s ease, border-color 0.25s ease, color 0.25s ease; } body { margin: 0; min-height: 100vh; font-family: var(--font-body); background: var(--bg); color: var(--text); background-image: radial-gradient(circle at 50% 50%, #1e293b 0%, #0b0f19 100%); display: flex; align-items: center; justify-content: center; padding: 40px 20px; } body.light-theme { background-image: radial-gradient(circle, rgba(47,42,34,0.16) 0.8px, transparent 0.9px); background-size: 28px 28px; } .container { width: 100%; max-width: 1000px; margin: 0 auto; position: relative; } .back-link { display: inline-flex; align-items: center; color: var(--text-muted); text-decoration: none; font-size: 0.95rem; margin-bottom: 24px; gap: 8px; font-weight: 600; } .back-link:hover { color: var(--accent); } body.light-theme .back-link:hover { text-decoration: underline; color: var(--text); } header { text-align: center; margin-bottom: 48px; } .brand { font-weight: 800; letter-spacing: .25em; color: var(--accent); text-transform: uppercase; font-size: 0.9rem; margin-bottom: 16px; font-family: var(--font-title); } body.light-theme .brand { color: var(--text-muted); } h1 { margin: 0 0 12px; font-size: clamp(2rem, 5vw, 3.2rem); font-weight: 800; background: linear-gradient(to right, #ffffff, #9ca3af); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-family: var(--font-title); } body.light-theme h1 { background: none; -webkit-background-clip: initial; -webkit-text-fill-color: initial; color: var(--text); } .subtitle { color: var(--text-muted); font-size: 1.1rem; max-width: 600px; margin: 0 auto; line-height: 1.6; } .section-title { font-size: 1.6rem; font-weight: 800; margin: 40px 0 20px; color: var(--accent); font-family: var(--font-title); display: flex; align-items: center; gap: 10px; } body.light-theme .section-title { color: var(--text); } .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 24px; margin-bottom: 40px; } .card { background: var(--card-bg); border: 1px solid var(--border); border-radius: 16px; padding: 30px; backdrop-filter: blur(16px); box-shadow: var(--shadow); display: flex; flex-direction: column; position: relative; overflow: hidden; } .card:hover { border-color: var(--border-hover); box-shadow: 0 15px 35px var(--glow); transform: translateY(-5px); } body.light-theme .card { border-radius: 6px; border: 2px solid var(--border); box-shadow: 0 12px 28px rgba(47, 42, 34, 0.08); backdrop-filter: none; } body.light-theme .card:nth-child(even) { background: #fff2b8; } body.light-theme .card:nth-child(odd) { background: #d8f3e7; } body.light-theme .card:hover { transform: translateY(-5px) rotate(0.5deg); box-shadow: 0 20px 40px rgba(47, 42, 34, 0.15); } .card-badge { position: absolute; top: 16px; right: 16px; background: rgba(16, 185, 129, 0.15); border: 1px solid rgba(16, 185, 129, 0.3); color: #34d399; padding: 6px 12px; border-radius: 8px; font-size: 0.75rem; font-weight: 700; text-transform: uppercase; } body.light-theme .card-badge { background: #fff; border: 2px solid var(--border-hover); color: #0f766e; border-radius: 4px; } .card h3 { margin: 0 0 10px; font-size: 1.4rem; font-weight: 700; color: #ffffff; } body.light-theme .card h3 { color: var(--text); } .price { font-size: 2.2rem; font-weight: 800; color: var(--accent); margin: 16px 0; display: flex; align-items: baseline; gap: 4px; font-family: var(--font-title); } body.light-theme .price { color: var(--text); } .price span { font-size: 0.95rem; color: var(--text-muted); font-weight: 500; } .card p { color: var(--text-muted); font-size: 0.95rem; line-height: 1.6; margin: 0 0 20px; flex-grow: 1; } body.light-theme .card p { color: var(--text-muted); } .features-list { list-style: none; padding: 0; margin: 0; display: grid; gap: 12px; } .features-list li { font-size: 0.9rem; display: flex; align-items: center; gap: 8px; color: var(--text); } .features-list li::before { content: "✓"; color: #10b981; font-weight: 800; } body.light-theme .features-list li::before { color: #0f766e; } /* Theme Toggle Button */ .theme-toggle-btn { position: absolute; top: 0px; right: 0px; width: 48px; height: 48px; border-radius: 12px; border: 1px solid var(--border); background: var(--card-bg); cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; box-shadow: var(--shadow); z-index: 100; } .theme-toggle-btn:hover { border-color: var(--accent); transform: scale(1.05); } body.light-theme .theme-toggle-btn { border: 2px solid var(--border-hover); background: #fff; box-shadow: 3px 4px 0 rgba(47,42,34,0.12); border-radius: 50%; } body.light-theme .theme-toggle-btn .sun-icon { display: none; } body.light-theme .theme-toggle-btn .moon-icon { display: block; } body:not(.light-theme) .theme-toggle-btn .sun-icon { display: block; } body:not(.light-theme) .theme-toggle-btn .moon-icon { display: none; } @media (max-width: 600px) { .grid { grid-template-columns: 1fr; } .theme-toggle-btn { top: -20px; right: 0; } } </style> </head> <body> <div class="container"> <button id="theme-toggle" class="theme-toggle-btn" aria-label="Toggle theme"> <span class="sun-icon">☀️</span> <span class="moon-icon">🌙</span> </button> <a class="back-link" href="/">&larr; Back to Dashboard</a> <header> <div class="brand">SCANLY</div> <h1>Simple & Transparent Pricing</h1> <p class="subtitle">No subscriptions, no hidden fees. Generous free tiers on almost all services, and pay-as-you-go rates when you scale.</p> </header> <h2 class="section-title">🎁 What's Free for You</h2> <div class="grid"> <div class="card"> <div class="card-badge">Free Tier</div> <h3>Delete Pages</h3> <div class="price">₹0.00</div> <p>Permanently remove selected pages (e.g. `1,3-5`) from your PDF documents.</p> <ul class="features-list"> <li>100% Free always</li> <li>Unlimited files and pages</li> <li>In-memory local secure processing</li> </ul> </div> <div class="card"> <div class="card-badge">100 Pages Free</div> <h3>PDF Splitter</h3> <div class="price">₹0.00<span>/ up to 100 pages</span></div> <p>Extract single pages or split a PDF into range groups inside a downloadable ZIP.</p> <ul class="features-list"> <li>First 100 pages are completely free</li> <li>Next 50 pages are also free</li> <li>Only pays if extra pages exceed 50</li> </ul> </div> <div class="card"> <div class="card-badge">100 Pages Free</div> <h3>PDF to Word</h3> <div class="price">₹0.00<span>/ up to 100 pages</span></div> <p>Convert PDF text layout into an editable Microsoft Word document.</p> <ul class="features-list"> <li>First 100 pages are completely free</li> <li>Extracts all text structure</li> <li>Download as editable .docx</li> </ul> </div> <div class="card"> <div class="card-badge">10 PDFs Free</div> <h3>PDF Merger</h3> <div class="price">₹0.00<span>/ up to 10 PDFs</span></div> <p>Combine multiple PDF files into a single master document.</p> <ul class="features-list"> <li>First 10 PDFs merged are free</li> <li>Keep your pages in ordered structure</li> </ul> </div> <div class="card"> <div class="card-badge">10,000 Rows Free</div> <h3>Excel → CSV</h3> <div class="price">₹0.00<span>/ up to 10k entries</span></div> <p>Instantly convert large Excel spreadsheets into clean flat CSV files.</p> <ul class="features-list"> <li>First 10,000 entries (rows) are free</li> <li>Highly optimized conversion speed</li> </ul> </div> <div class="card"> <div class="card-badge">Always Free</div> <h3>Summarizer</h3> <div class="price">₹0.00</div> <p>Generate clean bullet-point document summaries using AI.</p> <ul class="features-list"> <li>AI-powered summaries</li> <li>Outputs formatted DOCX files</li> </ul> </div> </div> <h2 class="section-title">⚡ Pay As You Go (Beyond Free limits)</h2> <div class="grid"> <div class="card"> <div class="card-badge">Paid Service</div> <h3>Searchable PDF OCR</h3> <div class="price">₹2.00<span>/ page</span></div> <p>Run advanced ocrmypdf engines to overlay selectable text layers on scanned PDFs.</p> <ul class="features-list"> <li>Accurate deskew and rotation</li> <li>Runs local OCR models</li> <li>Make any image PDF selectable</li> </ul> </div> <div class="card"> <div class="card-badge">Paid Service</div> <h3>Bank Statement Parser</h3> <div class="price">₹0.08<span>/ entry</span></div> <p>Extract structured transactions from Axis, SBI, ICICI, Kotak, HDFC, and other PDF statements into Excel.</p> <ul class="features-list"> <li>Select specific pages to parse</li> <li>Pay only for extracted entries</li> <li>Highly accurate rule-based extraction</li> </ul> </div> <div class="card"> <div class="card-badge">Paid Service</div> <h3>Split PDF Extra</h3> <div class="price">₹0.02<span>/ extra page</span></div> <p>When splitting extremely large PDFs containing more than 150 pages.</p> <ul class="features-list"> <li>Applies only from page 151+</li> <li>₹0.02 per additional page</li> </ul> </div> <div class="card"> <div class="card-badge">Paid Service</div> <h3>Merge PDF Extra</h3> <div class="price">₹0.02<span>/ extra PDF</span></div> <p>When merging large batches containing more than 10 documents.</p> <ul class="features-list"> <li>Applies only from 11th PDF+</li> <li>₹0.02 per additional file</li> </ul> </div> <div class="card"> <div class="card-badge">Paid Service</div> <h3>PDF to Word Extra</h3> <div class="price">₹0.02<span>/ extra page</span></div> <p>When converting large PDFs containing more than 100 pages.</p> <ul class="features-list"> <li>Applies only from page 101+</li> <li>₹0.02 per additional page</li> </ul> </div> <div class="card"> <div class="card-badge">Paid Service</div> <h3>Excel → CSV Extra</h3> <div class="price">₹0.02<span>/ 10 extra entries</span></div> <p>When converting spreadsheets containing more than 10,000 entries (rows).</p> <ul class="features-list"> <li>Applies only from row 10,001+</li> <li>₹0.02 per group of 10 extra rows</li> </ul> </div> </div> </div> <script> // Theme Initialization const toggleBtn = document.getElementById('theme-toggle'); const currentTheme = localStorage.getItem('theme') || 'dark'; if (currentTheme === 'light') { document.body.classList.add('light-theme'); } toggleBtn.addEventListener('click', () => { document.body.classList.toggle('light-theme'); const theme = document.body.classList.contains('light-theme') ? 'light' : 'dark'; localStorage.setItem('theme', theme); }); </script> </body> </html> """ @app.route("/pricing") def pricing_page(): return render_template_string(PRICING_TEMPLATE) # ── Service definitions ─────────────────────────────────────────────────── SERVICE_ROUTES = { "pdf-ocr": { "title": "Searchable PDF OCR", "subtitle": "Convert scanned PDF documents into searchable PDFs with selectable text overlay.", "field_label": "Choose a scanned PDF", "accept": ".pdf", "btn_label": "Run OCR", "hint": "This service runs ocrmypdf locally to create a searchable text layer. Rate: INR 5.00 per PDF page.", "select_input": { "name": "mode", "label": "OCR Mode", "options": [ ("fast", "Fast OCR - skip pages that already have text"), ("accurate", "High accuracy - slower full OCR") ] } }, "pdf-split": { "title": "PDF Splitter", "subtitle": "Split a PDF into individual pages or groups of pages.", "field_label": "Choose a PDF", "accept": ".pdf", "btn_label": "Split PDF", "extra_input": {"name": "split_size", "type": "number", "placeholder": "Group size (e.g. 5, default: 1)", "label": "Pages per split group"}, "hint": "Default splits into individual pages. Enter a group size (e.g., 5) to split into groups of pages.", }, "pdf-merge": { "title": "PDF Merger", "subtitle": "Upload multiple PDFs and merge them into a single document.", "field_label": "Choose PDF files", "accept": ".pdf", "btn_label": "Merge PDFs", "multiple": True, "hint": "Select two or more PDFs. Order them correctly before uploading.", }, "pdf-to-word": { "title": "PDF to Word", "subtitle": "Convert a PDF document into an editable Word (.docx) file.", "field_label": "Choose a PDF", "accept": ".pdf", "btn_label": "Convert to Word", "hint": "Extracts selectable text from PDF pages and writes as a nicely formatted Word document.", }, "pdf-delete-pages": { "title": "PDF Delete Pages", "subtitle": "Remove specific pages from a PDF and download the cleaned version.", "field_label": "Choose a PDF", "accept": ".pdf", "btn_label": "Delete Pages", "extra_input": {"name": "pages", "type": "text", "placeholder": "Pages to delete, e.g. 1,3-5,7", "label": "Page numbers to remove"}, "hint": "Specify pages like '1,3-5,7' to remove. The PDF must have at least one page remaining.", }, "excel-to-csv": { "title": "Excel → CSV Converter", "subtitle": "Convert XLSX or XLS files to clean CSV format.", "field_label": "Choose a spreadsheet", "accept": ".xlsx,.xls,.csv", "btn_label": "Convert to CSV", "hint": "Supports .xlsx, .xls. Already-CSV files pass through.", }, "summarize": { "title": "Document Summarizer", "subtitle": "Upload a PDF, DOCX, or TXT file and get a bullet-point summary as a DOCX.", "field_label": "Choose a document", "accept": ".pdf,.docx,.txt", "btn_label": "Summarize", "hint": "Output is a clean bullet-point DOCX file.", }, } for slug, info in SERVICE_ROUTES.items(): action_url = f"/api/{slug}" def _make_route(_slug, _info, _action): @app.route(f"/service/{_slug}", methods=["GET"], endpoint=f"service_{_slug}") def service_page(): return render_template_string(SERVICE_SHELL, **_info, action=_action, slug=_slug) _make_route(slug, info, action_url) # ── API endpoints ───────────────────────────────────────────────────────── def verify_payment_before_processing(service, request_files_field="file"): if has_valid_bypass_key(): return None amount = 0 pages_or_rows = 0 if service in PDF_SERVICES: if service == "pdf-merge": files = request.files.getlist(request_files_field) num_pdfs = len([f for f in files if f and f.filename]) amount, pages_or_rows, _ = order_amount_for(service, num_pdfs=num_pdfs) else: f = request.files.get(request_files_field) if not f or not f.filename: return "No file uploaded", 400 temp = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) temp.write(f.read()) temp.close() f.seek(0) try: pages = count_pdf_pages(temp.name) amount, pages_or_rows, _ = order_amount_for(service, pages=pages) finally: try: os.remove(temp.name) except OSError: pass elif service == EXCEL_SERVICE: f = request.files.get(request_files_field) if not f or not f.filename: return "No file uploaded", 400 ext = os.path.splitext(secure_filename(f.filename))[1].lower() temp = tempfile.NamedTemporaryFile(suffix=ext, delete=False) temp.write(f.read()) temp.close() f.seek(0) try: rows = count_excel_rows(temp.name, ext) amount, pages_or_rows, _ = order_amount_for(service, excel_rows=rows) finally: try: os.remove(temp.name) except OSError: pass elif service.startswith("bank-"): bank_slug = service.split("bank-")[1] uploads = request.files.getlist(request_files_field) valid_files = [up for up in uploads if up and up.filename and up.filename.lower().endswith(".pdf") and not os.path.basename(up.filename).startswith(".")] if not valid_files: return "No PDF file uploaded", 400 total_entries = 0 page_numbers = request.form.get("pages", "").strip() pdf_password = request.form.get("pdf_password", "").strip() for up in valid_files: pdf_bytes = up.read() up.seek(0) df = parse_statement_pdf(pdf_bytes, bank_slug=bank_slug, page_numbers=page_numbers, password=pdf_password) total_entries += len(df) amount, pages_or_rows, _ = order_amount_for(service, bank_entries=total_entries) if amount == 0: return None order_id = request.form.get("razorpay_order_id", "") payment_id = request.form.get("razorpay_payment_id", "") signature = request.form.get("razorpay_signature", "") order = PENDING_ORDERS.get(order_id) if not order_id or not payment_id or not signature: return "Complete the Razorpay payment before processing.", 402 if not order: return "Payment order expired or invalid. Please pay again.", 402 if order["service"] != service or order["amount"] != amount or order["pages_or_rows"] != pages_or_rows: return "Uploaded file page/row count does not match the payment. Please calculate payment again.", 400 if not verify_razorpay_signature(order_id, payment_id, signature): return "Payment signature verification failed.", 402 PENDING_ORDERS.pop(order_id, None) return None @app.route("/payment/order", methods=["POST"]) def create_payment_order(): service = request.form.get("service", "").strip() try: if has_valid_bypass_key(): return jsonify({ "key": "", "order_id": "", "amount": 0, "currency": "INR", "pages_or_rows": 0, "display_amount": "0.00", "summary": "Bypass key validated.", "description": "Bypass access key entered.", "free": True }) if service in PDF_SERVICES: if service == "pdf-merge": files = request.files.getlist("file") if not files or len(files) < 2: return jsonify({"error": "Upload at least 2 PDF files"}), 400 num_pdfs = len([f for f in files if f and f.filename]) amount, pages_or_rows, summary = order_amount_for(service, num_pdfs=num_pdfs) else: uploaded = request.files.get("file") if not uploaded or uploaded.filename == "": return jsonify({"error": "Please upload a PDF file"}), 400 filename = secure_filename(uploaded.filename) ext = os.path.splitext(filename)[1].lower() if ext != ".pdf": return jsonify({"error": "Only PDFs are supported for this service"}), 400 temp = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) temp.close() uploaded.save(temp.name) try: amount, pages_or_rows, summary = order_amount_for(service, path=temp.name) finally: try: os.remove(temp.name) except OSError: pass description = PDF_SERVICES[service] elif service == EXCEL_SERVICE: uploaded = request.files.get("file") if not uploaded or uploaded.filename == "": return jsonify({"error": "Please upload an Excel file"}), 400 filename = secure_filename(uploaded.filename) ext = os.path.splitext(filename)[1].lower() if ext not in (".xlsx", ".xls", ".xlsm"): return jsonify({"error": "Please upload a valid Excel file"}), 400 temp = tempfile.NamedTemporaryFile(suffix=ext, delete=False) temp.close() uploaded.save(temp.name) try: rows = count_excel_rows(temp.name, ext) amount, pages_or_rows, summary = order_amount_for(service, excel_rows=rows) finally: try: os.remove(temp.name) except OSError: pass description = "Excel to CSV" elif service.startswith("bank-"): bank_slug = service.split("bank-")[1] if bank_slug not in STAT_BANK_NAMES: return jsonify({"error": "Unknown bank service"}), 400 uploads = request.files.getlist("file") valid_files = [up for up in uploads if up and up.filename and up.filename.lower().endswith(".pdf") and not os.path.basename(up.filename).startswith(".")] if not valid_files: return jsonify({"error": "Please upload one or more PDF statements"}), 400 total_entries = 0 page_numbers = request.form.get("pages", "").strip() pdf_password = request.form.get("pdf_password", "").strip() for up in valid_files: pdf_bytes = up.read() up.seek(0) df = parse_statement_pdf(pdf_bytes, bank_slug=bank_slug, page_numbers=page_numbers, password=pdf_password) total_entries += len(df) amount, pages_or_rows, summary = order_amount_for(service, bank_entries=total_entries) if len(valid_files) == 1: description = f"{STAT_BANK_NAMES[bank_slug]} Statement Parsing" else: description = f"{STAT_BANK_NAMES[bank_slug]} Batch Parsing ({len(valid_files)} statements)" else: return jsonify({"error": "Unknown service."}), 400 key_id, order = create_order(service, amount, pages_or_rows) order_id = order["id"] if order else "" return jsonify({ "key": key_id, "order_id": order_id, "amount": amount, "currency": "INR", "pages_or_rows": pages_or_rows, "display_amount": f"{amount / 100:.2f}", "summary": summary, "description": description, "free": amount == 0, }) except ValueError as exc: return jsonify({"error": str(exc)}), 400 except Exception as exc: return jsonify({"error": f"Could not create payment order: {exc}"}), 500 def _start_task(task_id: str, fn, *, fname: str, mime: str, **kw): entry = { "queue": Queue(), "result": None, "error": None, "fname": fname, "mime": mime, } _pending[task_id] = entry t = Thread(target=_run_task, args=(task_id, fn), kwargs=kw, daemon=True) t.start() @app.route("/api/pdf-ocr", methods=["POST"]) def api_pdf_ocr(): payment_err = verify_payment_before_processing("pdf-ocr") if payment_err: return payment_err f = request.files.get("file") if not f or not f.filename: return "No file uploaded", 400 data = f.read() filename = secure_filename(f.filename) or "scan.pdf" mode = request.form.get("mode", "fast") task_id = secrets.token_hex(8) base = os.path.splitext(filename)[0] def process(**kw): return pdf_ocr_process(data, filename, mode, **kw) _start_task(task_id, process, fname=f"{base}_ocr.pdf", mime="application/pdf") return _accepted(task_id) @app.route("/api/pdf-split", methods=["POST"]) def api_pdf_split(): payment_err = verify_payment_before_processing("pdf-split") if payment_err: return payment_err f = request.files.get("file") if not f or not f.filename: return "No file uploaded", 400 split_size_str = request.form.get("split_size", "1").strip() try: split_size = int(split_size_str) if split_size_str else 1 if split_size < 1: split_size = 1 except ValueError: split_size = 1 data = f.read() task_id = secrets.token_hex(8) base = os.path.splitext(secure_filename(f.filename))[0] _start_task(task_id, pdf_split_process, fname=f"{base}_pages.zip", mime="application/zip", file_bytes=data, split_size=split_size) return _accepted(task_id) @app.route("/api/pdf-merge", methods=["POST"]) def api_pdf_merge(): payment_err = verify_payment_before_processing("pdf-merge") if payment_err: return payment_err files = request.files.getlist("file") if len(files) < 2: return "Upload at least 2 PDF files", 400 task_id = secrets.token_hex(8) files_data = [(secure_filename(f.filename) or "doc.pdf", f.read()) for f in files] _start_task(task_id, pdf_merge_process, fname="merged.pdf", mime="application/pdf", files_data=files_data) return _accepted(task_id) @app.route("/api/excel-to-csv", methods=["POST"]) def api_excel_to_csv(): payment_err = verify_payment_before_processing(EXCEL_SERVICE) if payment_err: return payment_err f = request.files.get("file") if not f or not f.filename: return "No file uploaded", 400 data = f.read() filename = secure_filename(f.filename) or "sheet.xlsx" task_id = secrets.token_hex(8) base = os.path.splitext(filename)[0] def process(**kw): return excel_to_csv_process(data, filename, **kw) _start_task(task_id, process, fname=f"{base}.csv", mime="text/csv") return _accepted(task_id) @app.route("/api/summarize", methods=["POST"]) def api_summarize(): payment_err = verify_payment_before_processing("summarize") if payment_err: return payment_err f = request.files.get("file") if not f or not f.filename: return "No file uploaded", 400 data = f.read() filename = secure_filename(f.filename) or "doc.pdf" task_id = secrets.token_hex(8) base = os.path.splitext(filename)[0] def process(**kw): return summarize_process(data, filename, **kw) _start_task( task_id, process, fname=f"{base}_summary.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document", ) return _accepted(task_id) @app.route("/api/pdf-to-word", methods=["POST"]) def api_pdf_to_word(): payment_err = verify_payment_before_processing("pdf-to-word") if payment_err: return payment_err f = request.files.get("file") if not f or not f.filename: return "No file uploaded", 400 data = f.read() filename = secure_filename(f.filename) or "doc.pdf" task_id = secrets.token_hex(8) base = os.path.splitext(filename)[0] def process(**kw): return pdf_to_word_process(data, filename, **kw) _start_task( task_id, process, fname=f"{base}.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document", ) return _accepted(task_id) @app.route("/api/pdf-delete-pages", methods=["POST"]) def api_pdf_delete_pages(): payment_err = verify_payment_before_processing("pdf-delete-pages") if payment_err: return payment_err f = request.files.get("file") if not f or not f.filename: return "No file uploaded", 400 pages_to_delete = request.form.get("pages", "").strip() if not pages_to_delete: return "Please specify pages to delete (e.g., '1,3-5,7')", 400 data = f.read() filename = secure_filename(f.filename) or "doc.pdf" task_id = secrets.token_hex(8) base = os.path.splitext(filename)[0] def process(**kw): return pdf_delete_pages_process(data, pages_to_delete, **kw) _start_task( task_id, process, fname=f"{base}_cleaned.pdf", mime="application/pdf", ) return _accepted(task_id) def _accepted(task_id: str): resp = Response(status=202) resp.headers["X-Task-Id"] = task_id return resp @app.route("/download/<task_id>") def download_result(task_id): entry = _pending.pop(task_id, None) if entry is None: return "Task not found", 404 if entry["error"]: return entry["error"], 400 if entry["result"] is None: return "Result not ready", 202 return send_file( BytesIO(entry["result"]), mimetype=entry["mime"], as_attachment=True, download_name=entry["fname"], ) # ── Bank statements ─────────────────────────────────────────────────────── BANK_STATEMENT_TEMPLATE = """<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bank Statement Parser | SCANLY</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&family=DM+Sans:wght@400;500;700&family=Fredoka:wght@500;600;700;800&display=swap" rel="stylesheet"> <style> :root { --bg: #0b0f19; --card-bg: rgba(20, 28, 48, 0.6); --border: rgba(255, 255, 255, 0.08); --border-hover: rgba(0, 242, 254, 0.4); --text: #f3f4f6; --text-muted: #9ca3af; --accent: #00f2fe; --accent-hover: #4facfe; --glow: rgba(0, 242, 254, 0.15); --shadow: 0 20px 40px rgba(0, 0, 0, 0.3); --font-body: 'Plus Jakarta Sans', sans-serif; --font-title: 'Plus Jakarta Sans', sans-serif; } body.light-theme { --bg: #fff9f0; --card-bg: #fff; --border: rgba(47, 42, 34, 0.12); --border-hover: #2f2a22; --text: #2f2a22; --text-muted: #756d61; --accent: #2fd0af; --accent-hover: #1e8f77; --glow: rgba(47, 42, 34, 0.08); --shadow: 0 24px 48px rgba(47, 42, 34, 0.16); --font-body: "DM Sans", sans-serif; --font-title: "Fredoka", sans-serif; } * { box-sizing: border-box; transition: transform 0.25s ease, box-shadow 0.25s ease, background 0.25s ease, border-color 0.25s ease, color 0.25s ease; } body { margin: 0; min-height: 100vh; font-family: var(--font-body); background: var(--bg); color: var(--text); background-image: radial-gradient(circle at 50% 50%, #1e293b 0%, #0b0f19 100%); } body.light-theme { background-image: radial-gradient(circle, rgba(47,42,34,0.16) 0.8px, transparent 0.9px); background-size: 28px 28px; } a { color: inherit; text-decoration: none; } .page { max-width: 1200px; margin: 0 auto; padding: 40px 20px 80px; position: relative; } .topbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 40px; } .brand { font-weight: 800; letter-spacing: 0.3em; text-transform: uppercase; color: var(--accent); font-size: 1.1rem; font-family: var(--font-title); } body.light-theme .brand { color: var(--text-muted); } .button-row { display: flex; gap: 12px; } .button-row a { display: inline-flex; align-items: center; padding: 10px 20px; border-radius: 10px; border: 1px solid var(--border); background: rgba(255, 255, 255, 0.02); font-weight: 700; font-size: 0.9rem; } .button-row a:hover { border-color: var(--accent); background: rgba(0, 242, 254, 0.05); color: var(--accent); } body.light-theme .button-row a { padding: 11px 16px; border-radius: 999px; border: 2px solid var(--border-hover); background: #fff2b8; font-weight: 800; box-shadow: 3px 4px 0 rgba(47,42,34,0.12); } body.light-theme .button-row a:hover { transform: translateY(-2px) rotate(-1deg); background: #d8f3e7; } .eyebrow { text-transform: uppercase; letter-spacing: 0.18em; color: var(--accent); font-size: 0.8rem; font-weight: 800; margin-bottom: 12px; } body.light-theme .eyebrow { margin-top: 34px; color: var(--text-muted); font-size: 0.82rem; } h1 { max-width: 820px; margin: 0 0 16px; font-size: clamp(2rem, 5vw, 3rem); line-height: 1.1; font-weight: 800; background: linear-gradient(to right, #ffffff, #9ca3af); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-family: var(--font-title); } body.light-theme h1 { margin: 16px 0 12px; font-size: clamp(2.4rem, 5vw, 4.4rem); line-height: 1.02; background: none; -webkit-background-clip: initial; -webkit-text-fill-color: initial; color: var(--text); } .lead { max-width: 760px; color: var(--text-muted); line-height: 1.8; margin-bottom: 24px; font-size: 1.05rem; } .privacy-badge { display: inline-flex; align-items: center; gap: 8px; background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.2); color: #34d399; padding: 12px 16px; border-radius: 12px; font-size: 0.9rem; font-weight: 600; margin-bottom: 40px; max-width: 600px; } body.light-theme .privacy-badge { background: rgba(16, 185, 129, 0.08); border: 2px solid rgba(47, 42, 34, 0.12); color: #0f766e; border-radius: 8px; } .bank-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 24px; } body.light-theme .bank-grid { gap: 20px; } .bank-card { background: var(--card-bg); border: 1px solid var(--border); border-radius: 16px; padding: 28px; backdrop-filter: blur(16px); display: flex; flex-direction: column; gap: 16px; box-shadow: var(--shadow); } .bank-card:hover { border-color: var(--border-hover); box-shadow: 0 15px 35px var(--glow); transform: translateY(-4px); } body.light-theme .bank-card { position: relative; min-height: 230px; padding: 24px; border-radius: 6px; border: 2px solid rgba(47, 42, 34, 0.16); background: #fff; box-shadow: 0 20px 42px rgba(47, 42, 34, 0.14); transform: rotate(-0.8deg); backdrop-filter: none; } body.light-theme .bank-card:nth-child(even) { background: #d8f3e7; transform: rotate(1deg); } body.light-theme .bank-card:nth-child(3n) { background: #fff2b8; transform: rotate(-1.2deg); } body.light-theme .bank-card::before { content: ""; position: absolute; top: -8px; left: 22px; width: 64px; height: 20px; background: linear-gradient(135deg, rgba(135,206,235,0.64), rgba(135,206,235,0.24)); transform: rotate(-7deg); z-index: 2; } body.light-theme .bank-card:hover { transform: rotate(0deg) translateY(-7px) translateZ(18px); box-shadow: 0 28px 60px rgba(47, 42, 34, 0.2); } .bank-code { width: 48px; height: 48px; display: grid; place-items: center; border-radius: 10px; background: rgba(0, 242, 254, 0.1); color: var(--accent); border: 1px solid rgba(0, 242, 254, 0.2); font-weight: 800; font-size: 0.95rem; } body.light-theme .bank-code { width: 50px; height: 50px; border-radius: 12px; background: #fff; border: 2px solid rgba(47, 42, 34, 0.12); color: var(--text); font-weight: 900; } .bank-card h2 { margin: 0; font-size: 1.2rem; font-weight: 700; color: #ffffff; } body.light-theme .bank-card h2 { color: var(--text); font-size: 1.1rem; } .bank-card p { margin: 0; color: var(--text-muted); line-height: 1.5; font-size: 0.9rem; } .message { margin-bottom: 24px; padding: 14px 18px; border-radius: 12px; background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.2); color: #f87171; font-size: 0.95rem; } body.light-theme .message { background: #fff; border: 2px solid rgba(47,42,34,0.16); color: var(--text); } form { display: grid; gap: 14px; margin-top: auto; } input[type=file] { width: 100%; padding: 10px; border-radius: 8px; border: 1px dashed var(--border); background: rgba(255, 255, 255, 0.02); color: var(--text-muted); font-size: 0.85rem; cursor: pointer; } input[type=file]:hover { border-color: var(--border-hover); } body.light-theme input[type=file] { border: 2px solid rgba(47, 42, 34, 0.14); background: rgba(255, 255, 255, 0.78); color: var(--text); } button { padding: 12px; border: none; border-radius: 8px; background: linear-gradient(135deg, var(--accent), var(--accent-hover)); color: #0b0f19; font-weight: 700; cursor: pointer; font-size: 0.95rem; } button:hover { box-shadow: 0 4px 15px rgba(0, 242, 254, 0.3); transform: translateY(-1px); } body.light-theme button { border-radius: 999px; border: 2px solid var(--border-hover); background: var(--accent); color: #071915; font-weight: 900; box-shadow: 3px 4px 0 rgba(47,42,34,0.12); } body.light-theme button:hover { transform: translateY(-1px); box-shadow: 4px 5px 0 rgba(47,42,34,0.12); } .footer { margin-top: 50px; color: var(--text-muted); text-align: center; font-size: 0.9rem; } /* Theme Toggle Button */ .theme-toggle-btn { position: absolute; top: 24px; right: 24px; width: 48px; height: 48px; border-radius: 12px; border: 1px solid var(--border); background: var(--card-bg); cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2); z-index: 100; } .theme-toggle-btn:hover { border-color: var(--accent); transform: scale(1.05); } body.light-theme .theme-toggle-btn { border: 2px solid var(--border-hover); background: #fff; box-shadow: 3px 4px 0 rgba(47,42,34,0.12); border-radius: 50%; } body.light-theme .theme-toggle-btn .sun-icon { display: none; } body.light-theme .theme-toggle-btn .moon-icon { display: block; } body:not(.light-theme) .theme-toggle-btn .sun-icon { display: block; } body:not(.light-theme) .theme-toggle-btn .moon-icon { display: none; } @media (max-width: 900px) { .bank-grid { grid-template-columns: 1fr; } body.light-theme .bank-card { transform: rotate(0deg) !important; } } #progress-wrap { display: none; margin-bottom: 30px; background: var(--card-bg); padding: 24px; border: 1px solid var(--border); border-radius: 16px; } body.light-theme #progress-wrap { background: #fff; padding: 18px; border: 2px solid rgba(47, 42, 34, 0.1); border-radius: 8px; } .pbar { height: 8px; background: rgba(255, 255, 255, 0.08); border-radius: 999px; overflow: hidden; } body.light-theme .pbar { height: 12px; background: #e8e2d8; } .pfill { height: 100%; width: 0%; background: linear-gradient(to right, var(--accent), var(--accent-hover)); border-radius: 999px; transition: width 0.4s ease; } body.light-theme .pfill { background: var(--accent); } #pmsg { margin-top: 12px; color: var(--text-muted); font-size: .95rem; font-weight: 500; } </style> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> </head> <body> <button id="theme-toggle" class="theme-toggle-btn" aria-label="Toggle theme"> <span class="sun-icon">☀️</span> <span class="moon-icon">🌙</span> </button> <div class="page"> <div class="topbar"> <div class="brand">SCANLY</div> <div class="button-row"> <a href="/">Home</a> <a href="/pricing">Pricing</a> <a href="/#services">Services</a> <button onclick="clearCache()" style="padding: 6px 12px; border-radius: 8px; border: 1px solid var(--border); background: rgba(239,68,68,0.15); color: #f87171; cursor: pointer; font-weight: 600;">🧹 Reset Cache</button> </div> </div> <div class="eyebrow">Bank Parsers</div> <h1>Select the bank and upload the statement PDF.</h1> <p class="lead">Each sub-card runs its own parser. Supported options include Axis, SBI, ICICI, Kotak, HDFC, IDFC, IndusInd, Union Bank, PNB, IDBI, Credit Card Parser, and Other Bank (AI Parser).</p> <div class="privacy-badge">🔒 We don't save your data. All processing is done in-memory and immediately deleted.</div> <div id="progress-wrap"> <div class="pbar"><div class="pfill" id="pfill"></div></div> <p id="pmsg">Starting…</p> </div> <div class="bank-grid"> {% for slug, name in banks.items() %} <section class="bank-card"> <div class="bank-code">{% if slug == 'other' %}🤖 AI{% elif slug == 'creditcard' %}💳 CC{% elif slug == 'amex' %}💳 AMEX{% else %}{{ slug[:3].upper() }}{% endif %}</div> <h2>{{ name }}</h2> <p>{% if slug == 'other' %}Upload any bank PDF statement. Uses AI API parsing directly with zero hardcoded heuristics.{% elif slug == 'amex' %}Upload American Express (Amex) Credit Card PDF statement. Extracts Spends (Debits), Payments/Credits, Membership Fees, and Installments with running balances.{% elif slug == 'creditcard' %}Upload any Credit Card PDF statement (SBI Card, HDFC, ICICI, Axis, Amex, RBL). Parses Spends (Dr) and Refunds/Payments (Cr) into Excel.{% else %}Upload this bank's PDF statement and download parsed transactions as Excel.{% endif %}</p> <form class="bank-upload-form" data-bank="{{ slug }}"> <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; font-size: 0.8rem;"> <label style="cursor: pointer; display: inline-flex; align-items: center; gap: 4px; color: var(--text-muted); user-select: none;"> <input type="checkbox" class="folder-mode-checkbox" style="cursor: pointer; accent-color: var(--primary, #00f2fe);"> 📁 Folder Upload </label> <span class="file-count-badge" style="font-size: 0.78rem; font-weight: 600; color: #10b981; display: none;"></span> </div> <input type="file" name="file" accept=".pdf,application/pdf" multiple required style="width: 100%;"> <label style="display: flex; flex-direction: column; gap: 4px; font-size: 0.85rem; margin-top: 8px; text-align: left;"> PDF Password (if protected) <input type="password" name="pdf_password" placeholder="Password (if protected)" autocomplete="off" style="padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: rgba(255,255,255,0.02); color: var(--text);"> </label> <label style="display: flex; flex-direction: column; gap: 4px; font-size: 0.85rem; margin-top: 8px; text-align: left;"> Pages to Parse (e.g. 1, 3-5; leave blank for all) <input type="text" name="pages" placeholder="e.g. 1,3-5" style="padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: rgba(255,255,255,0.02); color: var(--text);"> </label> <label style="display: flex; flex-direction: column; gap: 4px; font-size: 0.85rem; margin-top: 8px; text-align: left;"> Access Key (Optional) <input type="password" name="access_key" autocomplete="off" placeholder="Access key for free processing" style="padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: rgba(255,255,255,0.02); color: var(--text);"> </label> <button type="submit" style="margin-top: 10px; width: 100%;">{% if slug == 'other' %}Parse with AI{% elif slug == 'amex' %}Parse AMEX{% elif slug == 'creditcard' %}Parse Credit Card{% else %}Parse {{ slug.upper() }}{% endif %}</button> </form> </section> {% endfor %} </div> <p class="footer">Choose the matching bank card for best extraction accuracy.</p> </div> <script> // Theme Initialization const toggleBtn = document.getElementById('theme-toggle'); const currentTheme = localStorage.getItem('theme') || 'dark'; if (currentTheme === 'light') { document.body.classList.add('light-theme'); } toggleBtn.addEventListener('click', () => { document.body.classList.toggle('light-theme'); const theme = document.body.classList.contains('light-theme') ? 'light' : 'dark'; localStorage.setItem('theme', theme); }); // Folder Upload & Multi-PDF toggle logic document.querySelectorAll('.bank-upload-form').forEach(form => { const chk = form.querySelector('.folder-mode-checkbox'); const fileInput = form.querySelector('input[type="file"]'); const badge = form.querySelector('.file-count-badge'); if (chk && fileInput) { chk.addEventListener('change', () => { if (chk.checked) { fileInput.setAttribute('webkitdirectory', ''); fileInput.setAttribute('directory', ''); fileInput.removeAttribute('multiple'); } else { fileInput.removeAttribute('webkitdirectory'); fileInput.removeAttribute('directory'); fileInput.setAttribute('multiple', ''); } fileInput.value = ''; if (badge) { badge.style.display = 'none'; } }); fileInput.addEventListener('change', () => { const validPdfs = Array.from(fileInput.files).filter(f => f.name.toLowerCase().endsWith('.pdf') && !f.name.startsWith('.')); if (badge) { if (validPdfs.length > 1) { badge.textContent = `📁 ${validPdfs.length} PDFs`; badge.style.display = 'inline'; } else if (validPdfs.length === 1) { badge.textContent = `📄 1 PDF`; badge.style.display = 'inline'; } else { badge.style.display = 'none'; } } }); } }); const forms = document.querySelectorAll('.bank-upload-form'); const pw = document.getElementById('progress-wrap'); const pfill = document.getElementById('pfill'); const pmsg = document.getElementById('pmsg'); forms.forEach(form => { form.addEventListener('submit', async (e) => { e.preventDefault(); const bankSlug = form.getAttribute('data-bank'); const fileInput = form.querySelector('input[type="file"]'); const validPdfs = Array.from(fileInput.files).filter(f => f.name.toLowerCase().endsWith('.pdf') && !f.name.startsWith('.')); if (validPdfs.length === 0) { alert('Please select at least one valid PDF statement file.'); return; } pw.style.display = 'block'; pfill.style.width = '0%'; pmsg.textContent = `Uploading ${validPdfs.length > 1 ? validPdfs.length + ' statement files…' : 'statement…'}`; pw.scrollIntoView({ behavior: 'smooth' }); const fd = new FormData(); for (const file of validPdfs) { fd.append('file', file, file.name); } for (const [key, val] of new FormData(form).entries()) { if (key !== 'file') { fd.append(key, val); } } const accessKey = fd.get("access_key"); if (accessKey && accessKey.trim()) { pmsg.textContent = 'Access key provided, bypassing payment check...'; } else { pmsg.textContent = 'Counting transactions & cost...'; fd.append("service", "bank-" + bankSlug); try { const orderResp = await fetch("/payment/order", { method: "POST", body: fd }); if (!orderResp.ok) { const errText = await orderResp.text(); let parsedErr; try { parsedErr = JSON.parse(errText).error; } catch(e) { parsedErr = errText; } pmsg.textContent = '❌ ' + parsedErr; return; } const order = await orderResp.json(); if (!order.free) { pmsg.textContent = `Calculated cost: INR ${order.display_amount}. Opening Razorpay...`; const payment = await new Promise((resolve, reject) => { const checkout = new Razorpay({ key: order.key, amount: order.amount, currency: order.currency, name: "SCANLY", description: order.description, order_id: order.order_id, handler: resolve, modal: { ondismiss: () => reject(new Error("Payment was not completed.")), }, theme: { color: document.body.classList.contains('light-theme') ? "#2fd0af" : "#00f2fe", }, }); checkout.on("payment.failed", (response) => { reject(new Error(response.error ? response.error.description : "Payment failed.")); }); checkout.open(); }); fd.append("razorpay_payment_id", payment.razorpay_payment_id); fd.append("razorpay_order_id", payment.razorpay_order_id); fd.append("razorpay_signature", payment.razorpay_signature); } } catch (err) { pmsg.textContent = '❌ ' + err.message; return; } } pmsg.textContent = 'Starting parsing task...'; const actionUrl = `/api/bank-statements/${bankSlug}`; const resp = await fetch(actionUrl, { method:'POST', body:fd }); if (!resp.ok) { pmsg.textContent = 'Error: ' + (await resp.text()); return; } const taskId = resp.headers.get('X-Task-Id'); if (!taskId) { pmsg.textContent = '❌ No task ID returned.'; return; } let startTime = Date.now(); const evt = new EventSource('/progress/' + taskId); evt.onmessage = (ev) => { const d = JSON.parse(ev.data); if (d.type === 'progress') { pfill.style.width = Math.min(d.percent, 100) + '%'; let elapsed = (Date.now() - startTime) / 1000; let timeRemainingStr = ""; if (d.percent > 5 && d.percent < 100) { let totalEstimatedTime = (elapsed / d.percent) * 100; let remaining = totalEstimatedTime - elapsed; if (remaining > 0) { let mins = Math.floor(remaining / 60); let secs = Math.ceil(remaining % 60); timeRemainingStr = ` (Estimated time remaining: ${mins > 0 ? mins + 'm ' : ''}${secs}s)`; } } pmsg.textContent = d.message + timeRemainingStr; } else if (d.type === 'done') { pfill.style.width = '100%'; pmsg.textContent = 'Downloading…'; evt.close(); fetch('/download/' + taskId).then(r => { const disp = r.headers.get('Content-Disposition') || ''; const m = disp.match(/filename="?(.+?)"?$/); const fname = m ? m[1] : 'result.xlsx'; return r.blob().then(blob => ({ blob, fname })); }).then(({ blob, fname }) => { const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = fname; a.click(); pmsg.textContent = '✅ Download complete!'; pfill.style.width = '100%'; }); } else if (d.type === 'error') { pmsg.textContent = '❌ ' + d.message; evt.close(); } }; }); }); async function clearCache() { if (confirm("Reset all learned parser memory and disk caches?")) { const res = await fetch("/api/clear-cache", { method: "POST" }); const data = await res.json(); alert("Parser cache cleared successfully! You can upload fresh files now."); } } </script> </body> </html> """ @app.route("/bank-statements", methods=["GET"]) def bank_statements(): return render_template_string(BANK_STATEMENT_TEMPLATE, banks=STAT_BANK_NAMES, message=None) @app.route("/api/clear-cache", methods=["GET", "POST"]) def api_clear_cache(): from statement_parser import clear_all_caches clear_all_caches() return jsonify({"status": "success", "message": "All statement parser caches cleared!"}) @app.route("/api/bank-statements/<bank_slug>", methods=["POST"]) def api_bank_statement_parser(bank_slug): if bank_slug not in STAT_BANK_NAMES: return "Unknown bank", 404 payment_err = verify_payment_before_processing(f"bank-{bank_slug}") if payment_err: return payment_err uploads = request.files.getlist("file") valid_files = [up for up in uploads if up and up.filename and up.filename.lower().endswith(".pdf") and not os.path.basename(up.filename).startswith(".")] if not valid_files: return "No PDF files uploaded", 400 page_numbers = request.form.get("pages", "").strip() pdf_password = request.form.get("pdf_password", "").strip() task_id = secrets.token_hex(8) if len(valid_files) == 1: upload = valid_files[0] data = upload.read() base_name = os.path.splitext(secure_filename(os.path.basename(upload.filename)))[0] or bank_slug def process(**kw): return bank_statement_process(data, bank_slug, page_numbers, password=pdf_password, **kw) out_fname = f"{base_name}_{bank_slug}_parsed.xlsx" else: valid_files.sort(key=lambda f: os.path.basename(f.filename).lower()) file_inputs = [(os.path.basename(f.filename), f.read()) for f in valid_files] def process(**kw): return bank_statement_process(file_inputs, bank_slug, page_numbers, password=pdf_password, **kw) out_fname = f"{bank_slug}_batch_{len(valid_files)}_statements_parsed.xlsx" _start_task( task_id, process, fname=out_fname, mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) return _accepted(task_id) if __name__ == "__main__": host = os.getenv("HOST", "0.0.0.0") port = int(os.getenv("PORT", 7860)) app.run(host=host, port=port, debug=False)
import json
import os
import secrets
import hashlib
import hmac
import uuid
import tempfile
from io import BytesIO
from queue import Queue
from threading import Thread
from dotenv import load_dotenv
from flask import (
Flask,
Response,
render_template_string,
request,
send_file,
stream_with_context,
jsonify,
)
from werkzeug.utils import secure_filename
import razorpay
from pypdf import PdfReader
from openpyxl import load_workbook
import pandas as pd
from services import (
excel_to_csv_process,
pdf_delete_pages_process,
pdf_merge_process,
pdf_split_process,
pdf_to_word_process,
summarize_process,
pdf_ocr_process,
bank_statement_process,
)
from statement_parser import BANK_NAMES as STAT_BANK_NAMES
from statement_parser import excel_bytes_from_df
from statement_parser import parse_statement_pdf
load_dotenv()
OCR_PRICE_PER_PAGE_PAISE = 500
PDF_FREE_PAGES = 10
PDF_EXTRA_PAGE_PRICE_PAISE = 200
EXCEL_FREE_ROWS = 500
EXCEL_PRICE_PER_EXTRA_ROW_PAISE = 20
EXCEL_MAX_ROWS = 50000
PENDING_ORDERS = {}
BYPASS_ACCESS_KEY = os.getenv("OCR_BYPASS_KEY", "215836").strip()
PDF_SERVICES = {
"pdf-ocr": "Searchable PDF OCR",
"pdf-to-word": "PDF to Word",
"pdf-split": "PDF Splitter",
"pdf-merge": "PDF Merger",
"pdf-delete-pages": "PDF Delete Pages",
"summarize": "Document Summarizer",
}
EXCEL_SERVICE = "excel-to-csv"
def razorpay_keys():
key_id = os.getenv("RAZORPAY_KEY_ID", "").strip()
key_secret = os.getenv("RAZORPAY_KEY_SECRET", "").strip()
if not key_id or not key_secret:
raise RuntimeError("Razorpay keys are not configured. Set RAZORPAY_KEY_ID and RAZORPAY_KEY_SECRET.")
return key_id, key_secret
def verify_razorpay_signature(order_id, payment_id, signature):
try:
_, key_secret = razorpay_keys()
except RuntimeError:
return False
message = f"{order_id}|{payment_id}".encode("utf-8")
expected = hmac.new(key_secret.encode("utf-8"), message, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature or "")
def has_valid_bypass_key():
access_key = request.form.get("access_key", "").strip()
return bool(BYPASS_ACCESS_KEY and hmac.compare_digest(access_key, BYPASS_ACCESS_KEY))
def count_pdf_pages(path, password=None):
reader = PdfReader(path)
if reader.is_encrypted:
if password:
try:
reader.decrypt(password)
except Exception:
raise ValueError("Incorrect password for protected PDF.")
else:
raise ValueError("This PDF is password-protected. Please enter the PDF password.")
return len(reader.pages)
def count_excel_rows(input_path, extension):