VsinghiAssociates commited on
Commit
b0c5771
·
verified ·
1 Parent(s): 6debacf

Sync from GitHub via hub-sync

Browse files
Files changed (3) hide show
  1. README.md +14 -0
  2. app.py +246 -29
  3. requirements.txt +2 -0
README.md CHANGED
@@ -15,6 +15,7 @@ Document Converter Pro is a Flask web app for:
15
  - Excel to CSV conversion with `pandas` and `openpyxl`
16
  - Fast default OCR mode that skips pages that already contain text
17
  - Streaming `.xlsx` conversion to reduce memory use on large workbooks
 
18
 
19
  ## Important: GitHub Pages will not run this app
20
 
@@ -34,6 +35,19 @@ Use GitHub as the source repository, then deploy the app to a Python/container h
34
 
35
  The included `Dockerfile` installs the required OCR system packages and starts `app.py` on port `7860`.
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  ## Run locally
38
 
39
  Install system dependencies first:
 
15
  - Excel to CSV conversion with `pandas` and `openpyxl`
16
  - Fast default OCR mode that skips pages that already contain text
17
  - Streaming `.xlsx` conversion to reduce memory use on large workbooks
18
+ - Razorpay payment before PDF OCR processing at INR 0.50 per PDF page
19
 
20
  ## Important: GitHub Pages will not run this app
21
 
 
35
 
36
  The included `Dockerfile` installs the required OCR system packages and starts `app.py` on port `7860`.
37
 
38
+ ## Razorpay setup
39
+
40
+ PDF OCR processing is payment gated. The app counts PDF pages, creates a Razorpay order, waits for a successful Checkout payment, verifies the payment signature on the server, and only then starts OCR.
41
+
42
+ Set these environment variables in your deployment host or Hugging Face Space secrets:
43
+
44
+ ```bash
45
+ RAZORPAY_KEY_ID=rzp_test_or_live_key_id
46
+ RAZORPAY_KEY_SECRET=your_key_secret
47
+ ```
48
+
49
+ The OCR price is configured in `app.py` as `OCR_PRICE_PER_PAGE_PAISE = 50`, which is INR 0.50 per page.
50
+
51
  ## Run locally
52
 
53
  Install system dependencies first:
app.py CHANGED
@@ -1,18 +1,26 @@
1
  import csv
 
 
2
  import multiprocessing
3
  import os
4
  import tempfile
 
5
 
6
  import ocrmypdf
7
  import pandas as pd
8
- from flask import Flask, after_this_request, render_template_string, request, send_file
 
9
  from openpyxl import load_workbook
 
10
  from werkzeug.utils import secure_filename
11
 
12
 
13
  app = Flask(__name__)
14
  app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024
15
 
 
 
 
16
 
17
  PAGE = """
18
  <!doctype html>
@@ -225,6 +233,24 @@ PAGE = """
225
  .download-link.ready {
226
  display: flex;
227
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  .details {
229
  display: grid;
230
  gap: 8px;
@@ -271,13 +297,17 @@ PAGE = """
271
  <h2>PDF OCR Converter</h2>
272
  <p>Turn scanned PDFs into searchable documents. Fast mode skips pages that already contain selectable text.</p>
273
  </div>
274
- <form action="/ocr" method="post" enctype="multipart/form-data" data-download-form>
275
  <input type="file" name="pdf_file" accept="application/pdf,.pdf" required>
276
  <select name="mode" aria-label="OCR mode">
277
  <option value="fast" selected>Fast OCR - skip pages that already have text</option>
278
  <option value="accurate">High accuracy - slower full OCR</option>
279
  </select>
280
- <button type="submit">Process PDF</button>
 
 
 
 
281
  <div class="progress-wrap" aria-hidden="true">
282
  <div class="progress-label">
283
  <span>Processing document</span>
@@ -323,6 +353,7 @@ PAGE = """
323
  </section>
324
  </div>
325
  </main>
 
326
  <script>
327
  function filenameFromDisposition(disposition, fallback) {
328
  if (!disposition) return fallback;
@@ -330,6 +361,60 @@ PAGE = """
330
  return match ? match[1] : fallback;
331
  }
332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333
  document.querySelectorAll("[data-download-form]").forEach((form) => {
334
  let activeDownloadUrl = null;
335
 
@@ -342,8 +427,11 @@ PAGE = """
342
  const progressBar = form.querySelector(".progress-bar");
343
  const progressValue = form.querySelector("[data-progress-value]");
344
  const downloadLink = form.querySelector(".download-link");
 
 
345
  const originalText = button.textContent;
346
  const fallbackName = form.action.endsWith("/excel") ? "converted.csv" : "processed.pdf";
 
347
  let progress = 0;
348
  let progressTimer = null;
349
 
@@ -353,6 +441,9 @@ PAGE = """
353
  }
354
  downloadLink.classList.remove("ready");
355
  downloadLink.removeAttribute("href");
 
 
 
356
 
357
  const setProgress = (value) => {
358
  progress = Math.max(progress, Math.min(value, 100));
@@ -361,16 +452,38 @@ PAGE = """
361
  };
362
 
363
  button.disabled = true;
364
- button.textContent = "Processing...";
365
  progressWrap.classList.add("active");
366
  progressWrap.setAttribute("aria-hidden", "false");
367
  setProgress(8);
368
  status.classList.remove("error", "success");
369
- status.textContent = form.action.endsWith("/ocr")
370
- ? "Uploading and processing. Fast mode skips pages that already contain text."
371
  : "Uploading and converting. Large workbooks may take a moment.";
372
 
373
  try {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
  progressTimer = window.setInterval(() => {
375
  const next = progress < 55 ? progress + 7 : progress < 86 ? progress + 3 : progress + 0.6;
376
  setProgress(Math.min(next, 94));
@@ -378,12 +491,11 @@ PAGE = """
378
 
379
  const response = await fetch(form.action, {
380
  method: "POST",
381
- body: new FormData(form),
382
  });
383
 
384
  if (!response.ok) {
385
- const message = await response.text();
386
- throw new Error(message.replace(/<[^>]*>/g, " ").replace(/\\s+/g, " ").trim() || "Processing failed.");
387
  }
388
 
389
  const blob = await response.blob();
@@ -441,6 +553,40 @@ def remove_later(path):
441
  return response
442
 
443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
444
  def ocr_options(mode):
445
  workers = max(1, min(4, multiprocessing.cpu_count()))
446
  if mode == "accurate":
@@ -465,39 +611,110 @@ def ocr_options(mode):
465
  }
466
 
467
 
468
- @app.post("/ocr")
469
- def ocr_pdf():
470
- uploaded = request.files.get("pdf_file")
471
- if not uploaded or uploaded.filename == "":
472
- return render_page("Please upload a PDF file."), 400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473
 
474
- filename = secure_filename(uploaded.filename)
475
- if not filename.lower().endswith(".pdf"):
476
- return render_page("Please upload a valid PDF file."), 400
 
 
477
 
478
- input_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
479
  output_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
480
- input_file.close()
481
  output_file.close()
 
 
 
482
 
483
  try:
484
- uploaded.save(input_file.name)
485
- os.remove(output_file.name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486
  ocrmypdf.ocr(
487
- input_file.name,
488
- output_file.name,
489
  **ocr_options(request.form.get("mode", "fast")),
490
  )
491
  download_name = f"ocr_{filename}"
492
- remove_later(output_file.name)
493
- return send_file(output_file.name, as_attachment=True, download_name=download_name)
 
 
 
 
494
  except Exception as exc:
495
  return render_page(f"OCR failed: {exc}"), 500
496
  finally:
497
- try:
498
- os.remove(input_file.name)
499
- except OSError:
500
- pass
 
 
 
 
 
 
501
 
502
 
503
  def convert_xlsx_to_csv(input_path, output_path):
 
1
  import csv
2
+ import hmac
3
+ import hashlib
4
  import multiprocessing
5
  import os
6
  import tempfile
7
+ import uuid
8
 
9
  import ocrmypdf
10
  import pandas as pd
11
+ import razorpay
12
+ from flask import Flask, after_this_request, jsonify, render_template_string, request, send_file
13
  from openpyxl import load_workbook
14
+ from pypdf import PdfReader
15
  from werkzeug.utils import secure_filename
16
 
17
 
18
  app = Flask(__name__)
19
  app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024
20
 
21
+ OCR_PRICE_PER_PAGE_PAISE = 50
22
+ PENDING_ORDERS = {}
23
+
24
 
25
  PAGE = """
26
  <!doctype html>
 
233
  .download-link.ready {
234
  display: flex;
235
  }
236
+ .billing-summary {
237
+ display: none;
238
+ gap: 6px;
239
+ padding: 12px 14px;
240
+ border: 1px solid #bfdbfe;
241
+ border-radius: 6px;
242
+ background: #eff6ff;
243
+ color: #1e3a8a;
244
+ font-weight: 750;
245
+ }
246
+ .billing-summary.ready {
247
+ display: grid;
248
+ }
249
+ .billing-summary span:last-child {
250
+ color: #475569;
251
+ font-size: 0.9rem;
252
+ font-weight: 600;
253
+ }
254
  .details {
255
  display: grid;
256
  gap: 8px;
 
297
  <h2>PDF OCR Converter</h2>
298
  <p>Turn scanned PDFs into searchable documents. Fast mode skips pages that already contain selectable text.</p>
299
  </div>
300
+ <form action="/ocr" method="post" enctype="multipart/form-data" data-download-form data-payment-required>
301
  <input type="file" name="pdf_file" accept="application/pdf,.pdf" required>
302
  <select name="mode" aria-label="OCR mode">
303
  <option value="fast" selected>Fast OCR - skip pages that already have text</option>
304
  <option value="accurate">High accuracy - slower full OCR</option>
305
  </select>
306
+ <button type="submit">Pay and Process PDF</button>
307
+ <div class="billing-summary" aria-live="polite">
308
+ <span data-billing-total></span>
309
+ <span>Rate: INR 0.50 per PDF page. OCR starts only after payment succeeds.</span>
310
+ </div>
311
  <div class="progress-wrap" aria-hidden="true">
312
  <div class="progress-label">
313
  <span>Processing document</span>
 
353
  </section>
354
  </div>
355
  </main>
356
+ <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
357
  <script>
358
  function filenameFromDisposition(disposition, fallback) {
359
  if (!disposition) return fallback;
 
361
  return match ? match[1] : fallback;
362
  }
363
 
364
+ async function errorFromResponse(response, fallback) {
365
+ const contentType = response.headers.get("content-type") || "";
366
+ if (contentType.includes("application/json")) {
367
+ const payload = await response.json();
368
+ return payload.error || fallback;
369
+ }
370
+ const message = await response.text();
371
+ return message.replace(/<[^>]*>/g, " ").replace(/\\s+/g, " ").trim() || fallback;
372
+ }
373
+
374
+ async function createOcrOrder(form) {
375
+ const response = await fetch("/ocr/order", {
376
+ method: "POST",
377
+ body: new FormData(form),
378
+ });
379
+
380
+ if (!response.ok) {
381
+ throw new Error(await errorFromResponse(response, "Could not calculate OCR payment."));
382
+ }
383
+
384
+ return response.json();
385
+ }
386
+
387
+ function openRazorpayCheckout(order) {
388
+ return new Promise((resolve, reject) => {
389
+ if (!window.Razorpay) {
390
+ reject(new Error("Razorpay checkout could not load. Please refresh and try again."));
391
+ return;
392
+ }
393
+
394
+ const checkout = new Razorpay({
395
+ key: order.key,
396
+ amount: order.amount,
397
+ currency: order.currency,
398
+ name: "Document Converter Pro",
399
+ description: `OCR for ${order.pages} PDF page${order.pages === 1 ? "" : "s"}`,
400
+ order_id: order.order_id,
401
+ handler: resolve,
402
+ modal: {
403
+ ondismiss: () => reject(new Error("Payment was not completed.")),
404
+ },
405
+ theme: {
406
+ color: "#2563eb",
407
+ },
408
+ });
409
+
410
+ checkout.on("payment.failed", (response) => {
411
+ reject(new Error(response.error && response.error.description ? response.error.description : "Payment failed."));
412
+ });
413
+
414
+ checkout.open();
415
+ });
416
+ }
417
+
418
  document.querySelectorAll("[data-download-form]").forEach((form) => {
419
  let activeDownloadUrl = null;
420
 
 
427
  const progressBar = form.querySelector(".progress-bar");
428
  const progressValue = form.querySelector("[data-progress-value]");
429
  const downloadLink = form.querySelector(".download-link");
430
+ const billingSummary = form.querySelector(".billing-summary");
431
+ const billingTotal = form.querySelector("[data-billing-total]");
432
  const originalText = button.textContent;
433
  const fallbackName = form.action.endsWith("/excel") ? "converted.csv" : "processed.pdf";
434
+ const requiresPayment = form.hasAttribute("data-payment-required");
435
  let progress = 0;
436
  let progressTimer = null;
437
 
 
441
  }
442
  downloadLink.classList.remove("ready");
443
  downloadLink.removeAttribute("href");
444
+ if (billingSummary) {
445
+ billingSummary.classList.remove("ready");
446
+ }
447
 
448
  const setProgress = (value) => {
449
  progress = Math.max(progress, Math.min(value, 100));
 
452
  };
453
 
454
  button.disabled = true;
455
+ button.textContent = requiresPayment ? "Calculating..." : "Processing...";
456
  progressWrap.classList.add("active");
457
  progressWrap.setAttribute("aria-hidden", "false");
458
  setProgress(8);
459
  status.classList.remove("error", "success");
460
+ status.textContent = requiresPayment
461
+ ? "Uploading PDF to calculate page count and payment amount."
462
  : "Uploading and converting. Large workbooks may take a moment.";
463
 
464
  try {
465
+ const formData = new FormData(form);
466
+
467
+ if (requiresPayment) {
468
+ const order = await createOcrOrder(form);
469
+ if (billingSummary && billingTotal) {
470
+ billingTotal.textContent = `${order.pages} page${order.pages === 1 ? "" : "s"} x INR 0.50 = INR ${order.display_amount}`;
471
+ billingSummary.classList.add("ready");
472
+ }
473
+
474
+ setProgress(18);
475
+ button.textContent = "Waiting for payment...";
476
+ status.textContent = `Complete INR ${order.display_amount} payment to start OCR.`;
477
+ const payment = await openRazorpayCheckout(order);
478
+
479
+ formData.append("razorpay_payment_id", payment.razorpay_payment_id);
480
+ formData.append("razorpay_order_id", payment.razorpay_order_id);
481
+ formData.append("razorpay_signature", payment.razorpay_signature);
482
+ setProgress(26);
483
+ button.textContent = "Processing...";
484
+ status.textContent = "Payment verified by Razorpay. OCR is processing now.";
485
+ }
486
+
487
  progressTimer = window.setInterval(() => {
488
  const next = progress < 55 ? progress + 7 : progress < 86 ? progress + 3 : progress + 0.6;
489
  setProgress(Math.min(next, 94));
 
491
 
492
  const response = await fetch(form.action, {
493
  method: "POST",
494
+ body: formData,
495
  });
496
 
497
  if (!response.ok) {
498
+ throw new Error(await errorFromResponse(response, "Processing failed."));
 
499
  }
500
 
501
  const blob = await response.blob();
 
553
  return response
554
 
555
 
556
+ def razorpay_keys():
557
+ key_id = os.getenv("RAZORPAY_KEY_ID", "").strip()
558
+ key_secret = os.getenv("RAZORPAY_KEY_SECRET", "").strip()
559
+ if not key_id or not key_secret:
560
+ raise RuntimeError("Razorpay keys are not configured. Set RAZORPAY_KEY_ID and RAZORPAY_KEY_SECRET.")
561
+ return key_id, key_secret
562
+
563
+
564
+ def count_pdf_pages(path):
565
+ reader = PdfReader(path)
566
+ return len(reader.pages)
567
+
568
+
569
+ def save_pdf_upload(uploaded):
570
+ if not uploaded or uploaded.filename == "":
571
+ raise ValueError("Please upload a PDF file.")
572
+
573
+ filename = secure_filename(uploaded.filename)
574
+ if not filename.lower().endswith(".pdf"):
575
+ raise ValueError("Please upload a valid PDF file.")
576
+
577
+ input_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
578
+ input_file.close()
579
+ uploaded.save(input_file.name)
580
+ return filename, input_file.name
581
+
582
+
583
+ def verify_razorpay_signature(order_id, payment_id, signature):
584
+ _, key_secret = razorpay_keys()
585
+ message = f"{order_id}|{payment_id}".encode("utf-8")
586
+ expected = hmac.new(key_secret.encode("utf-8"), message, hashlib.sha256).hexdigest()
587
+ return hmac.compare_digest(expected, signature or "")
588
+
589
+
590
  def ocr_options(mode):
591
  workers = max(1, min(4, multiprocessing.cpu_count()))
592
  if mode == "accurate":
 
611
  }
612
 
613
 
614
+ @app.post("/ocr/order")
615
+ def create_ocr_order():
616
+ input_path = None
617
+ try:
618
+ _, input_path = save_pdf_upload(request.files.get("pdf_file"))
619
+ page_count = count_pdf_pages(input_path)
620
+ if page_count < 1:
621
+ return jsonify({"error": "This PDF does not contain any pages."}), 400
622
+
623
+ key_id, _ = razorpay_keys()
624
+ amount = page_count * OCR_PRICE_PER_PAGE_PAISE
625
+ client = razorpay.Client(auth=(key_id, key_secret))
626
+ order = client.order.create(
627
+ {
628
+ "amount": amount,
629
+ "currency": "INR",
630
+ "receipt": f"ocr_{uuid.uuid4().hex[:28]}",
631
+ "notes": {
632
+ "service": "pdf_ocr",
633
+ "pages": str(page_count),
634
+ "price_per_page": "0.50",
635
+ },
636
+ }
637
+ )
638
 
639
+ PENDING_ORDERS[order["id"]] = {
640
+ "amount": amount,
641
+ "pages": page_count,
642
+ "currency": "INR",
643
+ }
644
 
645
+ return jsonify(
646
+ {
647
+ "key": key_id,
648
+ "order_id": order["id"],
649
+ "amount": amount,
650
+ "currency": "INR",
651
+ "pages": page_count,
652
+ "display_amount": f"{amount / 100:.2f}",
653
+ }
654
+ )
655
+ except ValueError as exc:
656
+ return jsonify({"error": str(exc)}), 400
657
+ except Exception as exc:
658
+ return jsonify({"error": f"Could not create payment order: {exc}"}), 500
659
+ finally:
660
+ if input_path:
661
+ try:
662
+ os.remove(input_path)
663
+ except OSError:
664
+ pass
665
+
666
+
667
+ @app.post("/ocr")
668
+ def ocr_pdf():
669
  output_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
 
670
  output_file.close()
671
+ output_path = output_file.name
672
+ output_sent = False
673
+ input_path = None
674
 
675
  try:
676
+ filename, input_path = save_pdf_upload(request.files.get("pdf_file"))
677
+ page_count = count_pdf_pages(input_path)
678
+ order_id = request.form.get("razorpay_order_id", "")
679
+ payment_id = request.form.get("razorpay_payment_id", "")
680
+ signature = request.form.get("razorpay_signature", "")
681
+ order = PENDING_ORDERS.get(order_id)
682
+
683
+ if not order_id or not payment_id or not signature:
684
+ return render_page("Complete the Razorpay payment before OCR processing."), 402
685
+ if not order:
686
+ return render_page("Payment order expired. Please calculate payment and try again."), 402
687
+ if order["pages"] != page_count:
688
+ return render_page("Uploaded PDF page count changed after payment. Please pay again for this file."), 400
689
+ if not verify_razorpay_signature(order_id, payment_id, signature):
690
+ return render_page("Payment verification failed. Please try again."), 402
691
+
692
+ os.remove(output_path)
693
  ocrmypdf.ocr(
694
+ input_path,
695
+ output_path,
696
  **ocr_options(request.form.get("mode", "fast")),
697
  )
698
  download_name = f"ocr_{filename}"
699
+ remove_later(output_path)
700
+ PENDING_ORDERS.pop(order_id, None)
701
+ output_sent = True
702
+ return send_file(output_path, as_attachment=True, download_name=download_name)
703
+ except ValueError as exc:
704
+ return render_page(str(exc)), 400
705
  except Exception as exc:
706
  return render_page(f"OCR failed: {exc}"), 500
707
  finally:
708
+ if input_path:
709
+ try:
710
+ os.remove(input_path)
711
+ except OSError:
712
+ pass
713
+ if not output_sent:
714
+ try:
715
+ os.remove(output_path)
716
+ except OSError:
717
+ pass
718
 
719
 
720
  def convert_xlsx_to_csv(input_path, output_path):
requirements.txt CHANGED
@@ -4,3 +4,5 @@ Flask==3.0.3
4
  Werkzeug==3.0.6
5
  ocrmypdf==16.11.1
6
  xlrd==2.0.1
 
 
 
4
  Werkzeug==3.0.6
5
  ocrmypdf==16.11.1
6
  xlrd==2.0.1
7
+ razorpay==1.4.2
8
+ pypdf==4.3.1