Spaces:
Sleeping

afueth commited on
Commit
835eeaa
·
0 Parent(s):

Malayalam OCR app

Browse files
Files changed (10) hide show
  1. .gitignore +6 -0
  2. Dockerfile +15 -0
  3. README.md +12 -0
  4. app.py +109 -0
  5. ocr/__init__.py +1 -0
  6. ocr/image_utils.py +33 -0
  7. ocr/ocr_engine.py +36 -0
  8. ocr/pdf_utils.py +21 -0
  9. packages.txt +2 -0
  10. requirements.txt +4 -0
.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ data/
5
+ output/
6
+ .DS_Store
Dockerfile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ RUN apt-get update && apt-get install -y \
4
+ tesseract-ocr tesseract-ocr-mal \
5
+ && rm -rf /var/lib/apt/lists/*
6
+
7
+ WORKDIR /app
8
+
9
+ COPY requirements.txt .
10
+ RUN pip install --no-cache-dir -r requirements.txt
11
+
12
+ COPY . .
13
+ EXPOSE 8501
14
+
15
+ CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ---
3
+ title: Malayalam OCR
4
+ sdk: docker
5
+ app_port: 8501
6
+
7
+ - Upload PDF or Image
8
+ - If PDF has selectable text: extracts via PyMuPDF (fast)
9
+ - If scanned/image: OCR using Tesseract Malayalam (`mal`)
10
+ - Copyable text + Download `.txt`
11
+ - Free hosting: Hugging Face Spaces (Streamlit)
12
+
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import io
3
+ import streamlit as st
4
+ import fitz # PyMuPDF
5
+ from PIL import Image
6
+
7
+ from ocr.ocr_engine import configure_tesseract, ocr_pil_image
8
+ from ocr.pdf_utils import pdf_has_native_text, extract_native_text, render_page_to_pil
9
+ from ocr.image_utils import preprocess_image
10
+
11
+ st.set_page_config(page_title="Malayalam OCR", layout="wide")
12
+ st.title("Malayalam OCR (Printed Text): PDF / Image → Copyable Text")
13
+
14
+ configure_tesseract()
15
+
16
+ with st.sidebar:
17
+ st.header("OCR Settings")
18
+ lang = st.selectbox("Language", ["mal", "mal+eng"], index=0)
19
+ psm = st.selectbox("PSM (layout mode)", [3, 4, 6, 11], index=2)
20
+ zoom = st.slider("PDF render zoom (OCR quality)", 1.0, 3.5, 2.0, 0.1)
21
+
22
+ st.divider()
23
+ st.header("Preprocessing")
24
+ grayscale = st.checkbox("Grayscale", value=True)
25
+ contrast = st.slider("Contrast", 1.0, 3.0, 2.0, 0.1)
26
+ use_threshold = st.checkbox("Threshold", value=True)
27
+ threshold = st.slider("Threshold value", 0, 255, 160, 5) if use_threshold else None
28
+ invert = st.checkbox("Invert colors", value=False)
29
+
30
+ st.divider()
31
+ st.header("PDF Behavior")
32
+ force_ocr = st.checkbox("Force OCR (use for scanned PDFs)", value=False)
33
+ max_pages = st.slider("Max pages to process", 1, 200, 20)
34
+
35
+ def do_ocr_on_pil(img: Image.Image) -> str:
36
+ img2 = preprocess_image(
37
+ img,
38
+ grayscale=grayscale,
39
+ contrast=contrast,
40
+ threshold=threshold,
41
+ invert=invert,
42
+ )
43
+ return ocr_pil_image(img2, lang=lang, psm=int(psm), oem=1)
44
+
45
+ @st.cache_data(show_spinner=False)
46
+ def process_image_bytes(img_bytes: bytes, settings_key: str) -> str:
47
+ img = Image.open(io.BytesIO(img_bytes))
48
+ return do_ocr_on_pil(img)
49
+
50
+ @st.cache_data(show_spinner=False)
51
+ def process_pdf_bytes(pdf_bytes: bytes, settings_key: str) -> str:
52
+ doc = fitz.open(stream=pdf_bytes, filetype="pdf")
53
+ out = []
54
+
55
+ total = min(doc.page_count, max_pages)
56
+ for i in range(total):
57
+ page = doc.load_page(i)
58
+
59
+ if (not force_ocr) and pdf_has_native_text(page, min_chars=50):
60
+ txt = extract_native_text(page)
61
+ out.append(f"\n\n--- Page {i+1} (native text) ---\n{txt}")
62
+ else:
63
+ pil_img = render_page_to_pil(page, zoom=zoom)
64
+ txt = do_ocr_on_pil(pil_img)
65
+ out.append(f"\n\n--- Page {i+1} (OCR) ---\n{txt}")
66
+
67
+ return "\n".join(out).strip()
68
+
69
+ uploaded = st.file_uploader("Upload PDF or Image", type=["pdf", "png", "jpg", "jpeg", "webp"])
70
+
71
+ if uploaded:
72
+ settings_key = f"{lang}|{psm}|{zoom}|{grayscale}|{contrast}|{threshold}|{invert}|{force_ocr}|{max_pages}"
73
+ file_bytes = uploaded.getvalue()
74
+ name = uploaded.name.lower()
75
+
76
+ col1, col2 = st.columns([1, 1])
77
+
78
+ with col1:
79
+ st.subheader("Input Preview")
80
+ if name.endswith(".pdf"):
81
+ st.info("PDF uploaded. Previewing first page as image.")
82
+ doc = fitz.open(stream=file_bytes, filetype="pdf")
83
+ page0 = doc.load_page(0)
84
+ img0 = render_page_to_pil(page0, zoom=1.5)
85
+ st.image(img0, use_container_width=True)
86
+ else:
87
+ img = Image.open(io.BytesIO(file_bytes))
88
+ st.image(img, use_container_width=True)
89
+
90
+ with col2:
91
+ st.subheader("Extracted Text")
92
+ with st.spinner("Extracting text..."):
93
+ if name.endswith(".pdf"):
94
+ text = process_pdf_bytes(file_bytes, settings_key)
95
+ else:
96
+ text = process_image_bytes(file_bytes, settings_key)
97
+
98
+ st.text_area("Copy text from here", value=text, height=420)
99
+
100
+ st.download_button(
101
+ "Download as .txt",
102
+ data=text.encode("utf-8"),
103
+ file_name=uploaded.name.rsplit(".", 1)[0] + "_ocr.txt",
104
+ mime="text/plain",
105
+ )
106
+
107
+ st.caption("Tip: If results are messy, try PSM=4 or PSM=3, increase Zoom to 2.5–3.0, or adjust Threshold.")
108
+ else:
109
+ st.write("Upload a PDF or image to extract Malayalam printed text.")
ocr/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # package marker
ocr/image_utils.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from PIL import Image, ImageOps, ImageEnhance
3
+
4
+ def preprocess_image(
5
+ img: Image.Image,
6
+ grayscale: bool = True,
7
+ contrast: float = 2.0,
8
+ threshold: int | None = 160,
9
+ invert: bool = False,
10
+ ) -> Image.Image:
11
+ """
12
+ Simple preprocessing for printed text.
13
+ - grayscale + boost contrast
14
+ - optional thresholding
15
+ - optional invert (useful if white text on dark bg)
16
+ """
17
+ img = ImageOps.exif_transpose(img) # fix phone rotation
18
+ if grayscale:
19
+ img = img.convert("L")
20
+ else:
21
+ img = img.convert("RGB")
22
+
23
+ if contrast and contrast != 1.0:
24
+ img = ImageEnhance.Contrast(img).enhance(float(contrast))
25
+
26
+ if threshold is not None:
27
+ t = int(threshold)
28
+ img = img.point(lambda p: 255 if p > t else 0)
29
+
30
+ if invert:
31
+ img = ImageOps.invert(img)
32
+
33
+ return img
ocr/ocr_engine.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import os
3
+ import pytesseract
4
+
5
+ def configure_tesseract() -> None:
6
+ cmd = os.environ.get("TESSERACT_CMD", "").strip()
7
+ if cmd:
8
+ pytesseract.pytesseract.tesseract_cmd = cmd
9
+ return
10
+
11
+ if os.name != "nt":
12
+ return # on Linux/macOS, tesseract should be in PATH
13
+
14
+ common = [
15
+ r"C:\Program Files\Tesseract-OCR\tesseract.exe",
16
+ r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe",
17
+ ]
18
+ for p in common:
19
+ if os.path.exists(p):
20
+ pytesseract.pytesseract.tesseract_cmd = p
21
+ return
22
+
23
+
24
+ def ocr_pil_image(img, lang: str = "mal", psm: int = 6, oem: int = 1) -> str:
25
+ """
26
+ psm:
27
+ 3 = fully automatic page segmentation
28
+ 4 = assume single column of text
29
+ 6 = assume a uniform block of text (often best for docs)
30
+ 11 = sparse text
31
+ oem:
32
+ 1 = LSTM engine
33
+ """
34
+ config = f"--oem {oem} --psm {psm}"
35
+ text = pytesseract.image_to_string(img, lang=lang, config=config)
36
+ return (text or "").strip()
ocr/pdf_utils.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import io
3
+ import fitz # PyMuPDF
4
+ from PIL import Image
5
+
6
+ def pdf_has_native_text(page: fitz.Page, min_chars: int = 50) -> bool:
7
+ txt = (page.get_text("text") or "").strip()
8
+ return len(txt) >= min_chars
9
+
10
+ def extract_native_text(page: fitz.Page) -> str:
11
+ return (page.get_text("text") or "").strip()
12
+
13
+ def render_page_to_pil(page: fitz.Page, zoom: float = 2.0) -> Image.Image:
14
+ """
15
+ Render PDF page to image for OCR. zoom ~2.0 is a good balance.
16
+ Higher zoom -> better OCR but slower.
17
+ """
18
+ mat = fitz.Matrix(zoom, zoom)
19
+ pix = page.get_pixmap(matrix=mat, alpha=False)
20
+ img = Image.open(io.BytesIO(pix.tobytes("png")))
21
+ return img
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ tesseract-ocr
2
+ tesseract-ocr-mal
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ streamlit
2
+ PyMuPDF
3
+ pytesseract
4
+ Pillow