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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import os
|
| 3 |
+
import requests
|
| 4 |
+
import mimetypes
|
| 5 |
+
from PyPDF2 import PdfReader, PdfWriter
|
| 6 |
+
import tempfile
|
| 7 |
+
import re
|
| 8 |
+
|
| 9 |
+
AZURE_ENDPOINT = os.environ.get("AZURE_ENDPOINT")
|
| 10 |
+
AZURE_KEY = os.environ.get("AZURE_KEY")
|
| 11 |
+
|
| 12 |
+
if not AZURE_ENDPOINT or not AZURE_KEY:
|
| 13 |
+
raise RuntimeError("Set AZURE_ENDPOINT and AZURE_KEY in .env")
|
| 14 |
+
|
| 15 |
+
AZURE_ENDPOINT = AZURE_ENDPOINT.rstrip("/")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def read_file_bytes(path):
|
| 19 |
+
with open(path, "rb") as f:
|
| 20 |
+
return f.read()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def detect_content_type(file_path: str):
|
| 24 |
+
mime, _ = mimetypes.guess_type(file_path)
|
| 25 |
+
return mime or "application/octet-stream"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def submit_read_api(file_path):
|
| 29 |
+
"""Submit file to Computer Vision Read API"""
|
| 30 |
+
url = f"{AZURE_ENDPOINT}/vision/v3.2/read/analyze"
|
| 31 |
+
headers = {
|
| 32 |
+
"Ocp-Apim-Subscription-Key": AZURE_KEY,
|
| 33 |
+
"Content-Type": "application/octet-stream"
|
| 34 |
+
}
|
| 35 |
+
data = read_file_bytes(file_path)
|
| 36 |
+
|
| 37 |
+
resp = requests.post(url, headers=headers, data=data)
|
| 38 |
+
print("Azure OCR request URL:", url)
|
| 39 |
+
print("Azure OCR response status:", resp.status_code)
|
| 40 |
+
print("Azure OCR response headers:", resp.headers)
|
| 41 |
+
|
| 42 |
+
resp.raise_for_status()
|
| 43 |
+
op_location = resp.headers.get("Operation-Location")
|
| 44 |
+
if not op_location:
|
| 45 |
+
raise RuntimeError(f"No Operation-Location header. Response: {resp.text}")
|
| 46 |
+
return op_location
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def poll_read_result(operation_location, timeout=180, interval=2.0):
|
| 50 |
+
"""Poll until Computer Vision OCR completes"""
|
| 51 |
+
headers = {"Ocp-Apim-Subscription-Key": AZURE_KEY}
|
| 52 |
+
deadline = time.time() + timeout
|
| 53 |
+
|
| 54 |
+
while time.time() < deadline:
|
| 55 |
+
r = requests.get(operation_location, headers=headers)
|
| 56 |
+
r.raise_for_status()
|
| 57 |
+
j = r.json()
|
| 58 |
+
status = j.get("status", "").lower()
|
| 59 |
+
if status in ("succeeded", "failed"):
|
| 60 |
+
break
|
| 61 |
+
time.sleep(interval)
|
| 62 |
+
|
| 63 |
+
if status != "succeeded":
|
| 64 |
+
raise RuntimeError(f"OCR failed. Status={status}, Response={j}")
|
| 65 |
+
|
| 66 |
+
analyze_result = j.get("analyzeResult", {})
|
| 67 |
+
lines = []
|
| 68 |
+
for read_result in analyze_result.get("readResults", []):
|
| 69 |
+
for line in read_result.get("lines", []):
|
| 70 |
+
lines.append(line["text"])
|
| 71 |
+
|
| 72 |
+
print(f"✅ Extracted {len(lines)} lines of text")
|
| 73 |
+
return "\n".join(lines)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def split_pdf_into_chunks(pdf_path, chunk_size=2):
|
| 78 |
+
reader = PdfReader(pdf_path)
|
| 79 |
+
total_pages = len(reader.pages)
|
| 80 |
+
chunk_files = []
|
| 81 |
+
|
| 82 |
+
for start in range(0, total_pages, chunk_size):
|
| 83 |
+
writer = PdfWriter()
|
| 84 |
+
for p in range(start, min(start + chunk_size, total_pages)):
|
| 85 |
+
writer.add_page(reader.pages[p])
|
| 86 |
+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
|
| 87 |
+
with open(tmp.name, "wb") as f:
|
| 88 |
+
writer.write(f)
|
| 89 |
+
chunk_files.append(tmp.name)
|
| 90 |
+
return chunk_files
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def clean_extracted_text(text: str) -> str:
|
| 94 |
+
# Remove page markers
|
| 95 |
+
text = re.sub(r"--- Page.*?---", "", text)
|
| 96 |
+
# Remove chunk markers
|
| 97 |
+
text = re.sub(r"\(chunk\)", "", text)
|
| 98 |
+
# Remove junk words
|
| 99 |
+
text = re.sub(r"\b(?:stone|Stegaumen|studystone\.in)\b", "", text, flags=re.IGNORECASE)
|
| 100 |
+
# Remove roll numbers and codes
|
| 101 |
+
text = re.sub(r"Z-\d+", "", text)
|
| 102 |
+
# Remove P.T.O
|
| 103 |
+
text = re.sub(r"P\.T\.O\.", "", text, flags=re.IGNORECASE)
|
| 104 |
+
|
| 105 |
+
# Normalize per-line spacing but preserve newlines
|
| 106 |
+
lines = [re.sub(r"\s+", " ", line).strip() for line in text.splitlines()]
|
| 107 |
+
return "\n".join([l for l in lines if l])
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def poll_read_result(operation_location, timeout=180, interval=2.0):
|
| 111 |
+
headers = {"Ocp-Apim-Subscription-Key": AZURE_KEY}
|
| 112 |
+
deadline = time.time() + timeout
|
| 113 |
+
|
| 114 |
+
while time.time() < deadline:
|
| 115 |
+
r = requests.get(operation_location, headers=headers)
|
| 116 |
+
r.raise_for_status()
|
| 117 |
+
j = r.json()
|
| 118 |
+
status = j.get("status", "").lower()
|
| 119 |
+
if status in ("succeeded", "failed"):
|
| 120 |
+
break
|
| 121 |
+
time.sleep(interval)
|
| 122 |
+
|
| 123 |
+
if status != "succeeded":
|
| 124 |
+
raise RuntimeError(f"OCR failed. Status={status}, Response={j}")
|
| 125 |
+
|
| 126 |
+
analyze_result = j.get("analyzeResult", {})
|
| 127 |
+
pages = analyze_result.get("pages", [])
|
| 128 |
+
content = analyze_result.get("content", "")
|
| 129 |
+
|
| 130 |
+
pages_text = []
|
| 131 |
+
for page in pages:
|
| 132 |
+
page_num = page.get("pageNumber", "?")
|
| 133 |
+
spans = page.get("spans", [])
|
| 134 |
+
text_parts = [content[s["offset"]: s["offset"] + s["length"]] for s in spans]
|
| 135 |
+
joined = "\n".join(text_parts).strip() or "(No text detected)"
|
| 136 |
+
pages_text.append(f"--- Page {page_num} ---\n{joined}")
|
| 137 |
+
|
| 138 |
+
print(f"✅ Processed {len(pages)} pages successfully")
|
| 139 |
+
return "\n\n".join(pages_text)
|
static/index.html
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8" />
|
| 5 |
+
<title>Studystone OCR Tool</title>
|
| 6 |
+
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
| 7 |
+
<style>
|
| 8 |
+
body {
|
| 9 |
+
font-family: "Segoe UI", Arial, sans-serif;
|
| 10 |
+
background:#f4f6f9;
|
| 11 |
+
margin:0; padding:20px;
|
| 12 |
+
color:#222;
|
| 13 |
+
}
|
| 14 |
+
.container {
|
| 15 |
+
max-width:800px;
|
| 16 |
+
margin:20px auto;
|
| 17 |
+
background:#fff;
|
| 18 |
+
padding:20px;
|
| 19 |
+
border-radius:10px;
|
| 20 |
+
box-shadow:0 4px 10px rgba(0,0,0,0.08);
|
| 21 |
+
}
|
| 22 |
+
h1 { color:#1a73e8; margin:0 0 10px }
|
| 23 |
+
input[type="file"] { margin-top:10px }
|
| 24 |
+
button {
|
| 25 |
+
background:#1a73e8;
|
| 26 |
+
color:#fff; border:none;
|
| 27 |
+
padding:10px 14px; border-radius:6px;
|
| 28 |
+
margin-top:10px; cursor:pointer;
|
| 29 |
+
}
|
| 30 |
+
button:hover { opacity:.9 }
|
| 31 |
+
textarea {
|
| 32 |
+
width:100%; min-height:250px;
|
| 33 |
+
margin-top:20px; padding:12px;
|
| 34 |
+
border:1px solid #ccc;
|
| 35 |
+
border-radius:8px;
|
| 36 |
+
font-family:inherit; font-size:14px;
|
| 37 |
+
line-height:1.5;
|
| 38 |
+
resize:vertical;
|
| 39 |
+
}
|
| 40 |
+
#buttons { display:flex; gap:10px; margin-top:10px }
|
| 41 |
+
</style>
|
| 42 |
+
</head>
|
| 43 |
+
<body>
|
| 44 |
+
<div class="container">
|
| 45 |
+
<h1>Azure OCR Extractor</h1>
|
| 46 |
+
<input id="fileInput" type="file" accept=".png,.jpg,.jpeg,.pdf" />
|
| 47 |
+
<div id="buttons">
|
| 48 |
+
<button id="uploadBtn">Upload & Extract</button>
|
| 49 |
+
<button id="copyBtn" style="background:#28a745">Copy Text</button>
|
| 50 |
+
<button id="downloadBtn" style="background:#6c63ff">Download TXT</button>
|
| 51 |
+
</div>
|
| 52 |
+
<div id="status"></div>
|
| 53 |
+
<textarea id="ocrTextarea" placeholder="Extracted OCR text will appear here..."></textarea>
|
| 54 |
+
</div>
|
| 55 |
+
|
| 56 |
+
<script>
|
| 57 |
+
const fileInput = document.getElementById("fileInput");
|
| 58 |
+
const uploadBtn = document.getElementById("uploadBtn");
|
| 59 |
+
const statusEl = document.getElementById("status");
|
| 60 |
+
const ocrTextarea = document.getElementById("ocrTextarea");
|
| 61 |
+
const copyBtn = document.getElementById("copyBtn");
|
| 62 |
+
const downloadBtn = document.getElementById("downloadBtn");
|
| 63 |
+
|
| 64 |
+
uploadBtn.addEventListener("click", async () => {
|
| 65 |
+
if (!fileInput.files.length) {
|
| 66 |
+
alert("Please choose a file.");
|
| 67 |
+
return;
|
| 68 |
+
}
|
| 69 |
+
statusEl.textContent = "Processing OCR...";
|
| 70 |
+
const fd = new FormData();
|
| 71 |
+
fd.append("file", fileInput.files[0]);
|
| 72 |
+
try {
|
| 73 |
+
const r = await fetch("/upload", { method:"POST", body: fd });
|
| 74 |
+
const j = await r.json();
|
| 75 |
+
if (!r.ok) {
|
| 76 |
+
statusEl.textContent = "OCR failed: " + (j.error || j.details);
|
| 77 |
+
return;
|
| 78 |
+
}
|
| 79 |
+
ocrTextarea.value = j.text || "";
|
| 80 |
+
statusEl.textContent = "Done.";
|
| 81 |
+
} catch (err) {
|
| 82 |
+
statusEl.textContent = "Error: " + err.message;
|
| 83 |
+
}
|
| 84 |
+
});
|
| 85 |
+
|
| 86 |
+
copyBtn.addEventListener("click", () => {
|
| 87 |
+
ocrTextarea.select();
|
| 88 |
+
document.execCommand("copy");
|
| 89 |
+
statusEl.textContent = "Text copied!";
|
| 90 |
+
});
|
| 91 |
+
|
| 92 |
+
downloadBtn.addEventListener("click", () => {
|
| 93 |
+
const text = ocrTextarea.value;
|
| 94 |
+
const blob = new Blob([text], { type: "text/plain" });
|
| 95 |
+
const link = document.createElement("a");
|
| 96 |
+
link.href = URL.createObjectURL(blob);
|
| 97 |
+
link.download = "ocr_text.txt";
|
| 98 |
+
link.click();
|
| 99 |
+
statusEl.textContent = "Text file downloaded.";
|
| 100 |
+
});
|
| 101 |
+
</script>
|
| 102 |
+
</body>
|
| 103 |
+
</html>
|