Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

feat: integrate GLM-OCR Pro local extraction dashboard

Tiioluwanie7e62651f8c2
diff --git a/glm-ocr-pro/.idea/.gitignore b/glm-ocr-pro/.idea/.gitignore
new file mode 100644
index 0000000..ab1f416
--- /dev/null
+++ b/glm-ocr-pro/.idea/.gitignore
@@ -0,0 +1,10 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Ignored default folder with query files
+/queries/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml
+# Editor-based HTTP Client requests
+/httpRequests/
diff --git a/glm-ocr-pro/.idea/glm-ocr-streamlit.iml b/glm-ocr-pro/.idea/glm-ocr-streamlit.iml
new file mode 100644
index 0000000..480a398
--- /dev/null
+++ b/glm-ocr-pro/.idea/glm-ocr-streamlit.iml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="PYTHON_MODULE" version="4">
+ <component name="NewModuleRootManager">
+ <content url="file://$MODULE_DIR$">
+ <excludeFolder url="file://$MODULE_DIR$/.venv" />
+ </content>
+ <orderEntry type="jdk" jdkName="Python 3.14 (glm-ocr-streamlit)" jdkType="Python SDK" />
+ <orderEntry type="sourceFolder" forTests="false" />
+ </component>
+</module>
\ No newline at end of file
diff --git a/glm-ocr-pro/.idea/inspectionProfiles/profiles_settings.xml b/glm-ocr-pro/.idea/inspectionProfiles/profiles_settings.xml
new file mode 100644
index 0000000..105ce2d
--- /dev/null
+++ b/glm-ocr-pro/.idea/inspectionProfiles/profiles_settings.xml
@@ -0,0 +1,6 @@
+<component name="InspectionProjectProfileManager">
+ <settings>
+ <option name="USE_PROJECT_PROFILE" value="false" />
+ <version value="1.0" />
+ </settings>
+</component>
\ No newline at end of file
diff --git a/glm-ocr-pro/.idea/misc.xml b/glm-ocr-pro/.idea/misc.xml
new file mode 100644
index 0000000..e69d5df
--- /dev/null
+++ b/glm-ocr-pro/.idea/misc.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+ <component name="Black">
+ <option name="sdkName" value="Python 3.14 (glm-ocr-streamlit)" />
+ </component>
+ <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.14 (glm-ocr-streamlit)" project-jdk-type="Python SDK" />
+</project>
\ No newline at end of file
diff --git a/glm-ocr-pro/.idea/modules.xml b/glm-ocr-pro/.idea/modules.xml
new file mode 100644
index 0000000..9050181
--- /dev/null
+++ b/glm-ocr-pro/.idea/modules.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+ <component name="ProjectModuleManager">
+ <modules>
+ <module fileurl="file://$PROJECT_DIR$/.idea/glm-ocr-streamlit.iml" filepath="$PROJECT_DIR$/.idea/glm-ocr-streamlit.iml" />
+ </modules>
+ </component>
+</project>
\ No newline at end of file
diff --git a/glm-ocr-pro/README.md b/glm-ocr-pro/README.md
new file mode 100644
index 0000000..92aa0e8
--- /dev/null
+++ b/glm-ocr-pro/README.md
@@ -0,0 +1,68 @@
+# GLM-OCR Pro 🧾
+
+**GLM-OCR Pro** is a high-performance, local-first Streamlit application designed for structured document extraction. It leverages the **GLM-OCR** model via Ollama to transform images and PDFs into cleanly formatted Markdown in real-time.
+
+---
+
+## ✨ Features
+
+- **100% Private & Local:** No data ever leaves your machine. Perfect for sensitive documents.
+- **Real-time Streaming:** Watch text populate your screen as the model identifies it.
+- **Premium UI:** A modern, glassmorphism-inspired dashboard with support for complex tables.
+- **Hardware Optimized:** Pre-configured performance profiles tailored for laptop and desktop GPUs.
+- **Multi-Format Support:** Seamlessly handles PNG, JPG, JPEG, and multi-page PDFs.
+
+---
+
+## πŸš€ Quick Start
+
+### 1. Install Ollama
+Download and install Ollama from [ollama.com](https://ollama.com).
+
+### 2. Pull the GLM-OCR Model
+Open your terminal and run:
+```bash
+ollama pull glm-ocr
+```
+
+### 3. Setup the Python Environment
+```bash
+# Optional: Create a virtual environment
+python -m venv .venv
+source .venv/bin/activate # Or `.venv\Scripts\activate` on Windows
+
+# Install dependencies
+pip install -r requirements.txt
+```
+
+### 4. Run the App
+```bash
+streamlit run app.py
+```
+
+---
+
+## βš™οΈ Performance Tuning
+
+GLM-OCR Pro includes three "Performance Profiles" to help you balance speed and accuracy based on your hardware:
+
+| Profile | Image Res. | Grayscale | Use Case |
+| :--- | :--- | :--- | :--- |
+| **Balanced** | 1300px | No | High-accuracy scanning on desktop GPUs. |
+| **Fast** | 1000px | Yes | Optimal for mid-range GPUs (e.g., 4GB VRAM). |
+| **Ultra Fast** | 800px | Yes | Lightning-fast extractions for simple text. |
+
+---
+
+## πŸ› οΈ Tech Stack
+
+- **UI Framework:** Streamlit
+- **PDF Engine:** PyPDFium2
+- **Image Processing:** Pillow
+- **Inference:** Ollama (`glm-ocr`)
+
+---
+
+## πŸ“ License
+
+This project is intended for personal and professional use. Ensure compliance with the GLM-OCR and Ollama licensing terms.
diff --git a/glm-ocr-pro/__pycache__/app.cpython-314.pyc b/glm-ocr-pro/__pycache__/app.cpython-314.pyc
new file mode 100644
index 0000000..64e0327
Binary files /dev/null and b/glm-ocr-pro/__pycache__/app.cpython-314.pyc differ
diff --git a/glm-ocr-pro/__pycache__/ocr_cloud.cpython-314.pyc b/glm-ocr-pro/__pycache__/ocr_cloud.cpython-314.pyc
new file mode 100644
index 0000000..60161f9
Binary files /dev/null and b/glm-ocr-pro/__pycache__/ocr_cloud.cpython-314.pyc differ
diff --git a/glm-ocr-pro/__pycache__/ocr_local.cpython-314.pyc b/glm-ocr-pro/__pycache__/ocr_local.cpython-314.pyc
new file mode 100644
index 0000000..06a9436
Binary files /dev/null and b/glm-ocr-pro/__pycache__/ocr_local.cpython-314.pyc differ
diff --git a/glm-ocr-pro/__pycache__/utils.cpython-314.pyc b/glm-ocr-pro/__pycache__/utils.cpython-314.pyc
new file mode 100644
index 0000000..aa1e227
Binary files /dev/null and b/glm-ocr-pro/__pycache__/utils.cpython-314.pyc differ
diff --git a/glm-ocr-pro/app.py b/glm-ocr-pro/app.py
new file mode 100644
index 0000000..7209c40
--- /dev/null
+++ b/glm-ocr-pro/app.py
@@ -0,0 +1,136 @@
+import streamlit as st
+import os
+
+# Only importing local mode now
+from ocr_local import check_ollama_status, extract_markdown_local_stream, warmup_local_model
+
+# Design System Injection
+if os.path.exists("style.css"):
+ with open("style.css") as f:
+ st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)
+
+def _looks_like_html_table(text: str) -> bool:
+ lowered = text.lower()
+ return "<table" in lowered and ("<tr" in lowered or "<td" in lowered)
+
+st.set_page_config(
+ page_title="GLM-OCR Pro",
+ page_icon="🧾",
+ layout="wide",
+)
+
+# Header Section
+st.title("GLM-OCR Pro")
+st.markdown("##### Modern Intelligence for Structured Document Extraction")
+st.divider()
+
+if "ocr_output" not in st.session_state:
+ st.session_state["ocr_output"] = ""
+
+# Layout
+col1, col2 = st.columns([1, 1.2], gap="large")
+
+with col1:
+ with st.container(border=True):
+ st.subheader("βš™οΈ Settings")
+
+ ok, status = check_ollama_status()
+ status_color = "green" if ok else "red"
+ st.markdown(f"**Ollama Status:** <span style='color:{status_color}'>{'●' if ok else 'β—‹'} {status}</span>", unsafe_allow_html=True)
+
+ if st.button("Warm Up Model", use_container_width=True, type="primary"):
+ with st.spinner("Loading GLM-OCR weights..."):
+ warmup_local_model()
+ st.toast("Model warmed up on GPU!")
+
+ st.divider()
+
+ uploaded_file = st.file_uploader(
+ "Drop your document here",
+ type=["png", "jpg", "jpeg", "pdf"],
+ help="Supported: PNG, JPG, JPEG, PDF",
+ )
+
+ with st.expander("Advanced Tuning", expanded=True):
+ speed_profile = st.selectbox(
+ "Performance Profile",
+ ["Balanced", "Fast", "Ultra Fast"],
+ index=2,
+ help="Profiles adjust resolution and grayscale for optimal VRAM usage.",
+ )
+
+ if speed_profile == "Balanced":
+ default_side, default_render, default_gray = 1300, 1.8, False
+ elif speed_profile == "Fast":
+ default_side, default_render, default_gray = 1000, 1.5, True
+ else: # Ultra Fast
+ default_side, default_render, default_gray = 800, 1.2, True
+
+ max_pdf_pages = st.slider("Max PDF Pages", 1, 20, 3)
+ use_grayscale = st.checkbox("Enable Grayscale (Recommended)", value=default_gray)
+ max_side = st.number_input("Max Side (px)", 400, 2400, default_side, step=100)
+ pdf_render_scale = st.number_input("PDF Rendering Scale", 1.0, 3.0, float(default_render), step=0.1)
+
+ if st.button("πŸš€ Extract Knowledge", type="primary", use_container_width=True):
+ if uploaded_file is None:
+ st.error("Please provide an image or PDF to start.")
+ else:
+ file_bytes = uploaded_file.getvalue()
+ mime_type = uploaded_file.type or "application/octet-stream"
+
+ st.session_state["ocr_output"] = ""
+ # Placeholder for streaming output
+ output_placeholder = st.empty()
+ full_text = ""
+
+ try:
+ for chunk in extract_markdown_local_stream(
+ file_bytes=file_bytes,
+ mime_type=mime_type,
+ max_pdf_pages=max_pdf_pages,
+ optimize_images=True,
+ max_side=max_side,
+ grayscale=use_grayscale,
+ pdf_render_scale=pdf_render_scale,
+ ):
+ full_text += chunk
+ # Prettify rendering during stream
+ output_placeholder.markdown(full_text)
+
+ st.session_state["ocr_output"] = full_text
+ st.balloons()
+ except Exception as exc:
+ st.error(f"Extraction Pipeline Error: {exc}")
+
+with col2:
+ if st.session_state["ocr_output"]:
+ with st.container(border=True):
+ st.subheader("🧾 Extracted Results")
+
+ # Action Row
+ btn_col1, btn_col2 = st.columns(2)
+ with btn_col1:
+ st.download_button(
+ label="πŸ’Ύ Download .md",
+ data=st.session_state["ocr_output"],
+ file_name="extraction.md",
+ mime="text/markdown",
+ use_container_width=True
+ )
+ with btn_col2:
+ # Built-in Copy strategy via st.code
+ st.info("πŸ’‘ Copy button is built into the viewer below.")
+
+ st.divider()
+
+ # The Viewer
+ if _looks_like_html_table(st.session_state["ocr_output"]):
+ st.markdown(st.session_state["ocr_output"], unsafe_allow_html=True)
+ else:
+ st.markdown(st.session_state["ocr_output"])
+
+ st.divider()
+ st.caption("Raw Markdown Source (Safe Copying)")
+ st.code(st.session_state["ocr_output"], language="markdown")
+ else:
+ st.info("Upload a document and initiate extraction to see structured data here.")
diff --git a/glm-ocr-pro/ocr_local.py b/glm-ocr-pro/ocr_local.py
new file mode 100644
index 0000000..5f7de25
--- /dev/null
+++ b/glm-ocr-pro/ocr_local.py
@@ -0,0 +1,152 @@
+import json
+from io import BytesIO
+from urllib import error, request
+from typing import Generator
+
+import pypdfium2 as pdfium
+from PIL import Image
+
+from utils import image_bytes_to_base64
+
+
+OLLAMA_BASE_URL = "http://localhost:11434"
+
+
+def check_ollama_status() -> tuple[bool, str]:
+ try:
+ req = request.Request(f"{OLLAMA_BASE_URL}/api/tags", method="GET")
+ with request.urlopen(req, timeout=5) as resp:
+ if resp.status == 200:
+ return True, "Ollama is running."
+ return False, "Ollama is not responding as expected."
+ except Exception as exc:
+ return False, f"Ollama not reachable: {exc}"
+
+
+def _pdf_to_image_bytes_list(pdf_bytes: bytes, max_pages: int, render_scale: float = 2.0) -> list[bytes]:
+ doc = pdfium.PdfDocument(pdf_bytes)
+ page_count = min(len(doc), max_pages)
+ out: list[bytes] = []
+ for i in range(page_count):
+ page = doc[i]
+ bitmap = page.render(scale=render_scale)
+ pil_image = bitmap.to_pil()
+ if pil_image.mode not in ("RGB", "L"):
+ pil_image = pil_image.convert("RGB")
+ buf = BytesIO()
+ pil_image.save(buf, format="PNG")
+ out.append(buf.getvalue())
+ return out
+
+
+def _optimize_image_bytes(image_bytes: bytes, max_side: int = 1400, quality: int = 75, grayscale: bool = False) -> bytes:
+ """Optimize image for local LLM consumption."""
+ image = Image.open(BytesIO(image_bytes))
+
+ # Convert to RGB if needed, or Grayscale (L) for speed/memory savings
+ if grayscale:
+ image = image.convert("L")
+ elif image.mode not in ("RGB", "L"):
+ image = image.convert("RGB")
+
+ w, h = image.size
+ longest = max(w, h)
+ if longest > max_side:
+ scale = max_side / float(longest)
+ image = image.resize((max(1, int(w * scale)), max(1, int(h * scale))), Image.Resampling.LANCZOS)
+
+ buf = BytesIO()
+ # JPEG format for smaller size, or PNG if quality is paramount
+ image.save(buf, format="JPEG", quality=quality, optimize=True)
+ return buf.getvalue()
+
+
+def warmup_local_model(timeout_seconds: int = 120) -> str:
+ payload = {"model": "glm-ocr", "prompt": "ready", "stream": False, "keep_alive": "10m"}
+ req = request.Request(
+ f"{OLLAMA_BASE_URL}/api/generate",
+ method="POST",
+ headers={"Content-Type": "application/json"},
+ data=json.dumps(payload).encode("utf-8"),
+ )
+ try:
+ with request.urlopen(req, timeout=timeout_seconds) as resp:
+ _ = resp.read()
+ return "Warm-up completed. Model is loaded."
+ except Exception as exc:
+ return f"Warm-up failed: {exc}"
+
+
+def _run_single_image_local_stream(image_bytes: bytes, timeout_seconds: int) -> Generator[str, None, None]:
+ """Calls Ollama chat endpoint with streaming enabled."""
+ prompt = (
+ "Extract all readable text from this image and return structured Markdown. "
+ "Maintain layout accuracy: preserve headings, lists, tables, and formulas. "
+ "Do not apologize or explain. Just return the extraction."
+ )
+ payload = {
+ "model": "glm-ocr",
+ "stream": True,
+ "keep_alive": "10m",
+ "options": {
+ "temperature": 0.0,
+ "num_predict": 2048,
+ },
+ "messages": [
+ {
+ "role": "user",
+ "content": prompt,
+ "images": [image_bytes_to_base64(image_bytes)],
+ }
+ ],
+ }
+
+ req = request.Request(
+ f"{OLLAMA_BASE_URL}/api/chat",
+ method="POST",
+ headers={"Content-Type": "application/json"},
+ data=json.dumps(payload).encode("utf-8"),
+ )
+
+ try:
+ # We manually iterate over response lines for streaming
+ with request.urlopen(req, timeout=timeout_seconds) as resp:
+ for line in resp:
+ if not line:
+ continue
+ try:
+ chunk = json.loads(line.decode("utf-8"))
+ content = chunk.get("message", {}).get("content", "")
+ if content:
+ yield content
+ if chunk.get("done"):
+ break
+ except json.JSONDecodeError:
+ continue
+ except Exception as exc:
+ yield f"\n[Error calling local Ollama: {exc}]\n"
+
+
+def extract_markdown_local_stream(
+ file_bytes: bytes,
+ mime_type: str,
+ max_pdf_pages: int = 5,
+ timeout_seconds: int = 600,
+ optimize_images: bool = True,
+ max_side: int = 1400,
+ grayscale: bool = False,
+ pdf_render_scale: float = 2.0,
+) -> Generator[str, None, None]:
+ """Main entry point for local extraction, yielding chunks of text."""
+ if mime_type == "application/pdf":
+ pages = _pdf_to_image_bytes_list(file_bytes, max_pages=max_pdf_pages, render_scale=pdf_render_scale)
+ for idx, page_bytes in enumerate(pages, start=1):
+ yield f"## Page {idx}\n\n"
+ if optimize_images:
+ page_bytes = _optimize_image_bytes(page_bytes, max_side=max_side, grayscale=grayscale)
+ yield from _run_single_image_local_stream(page_bytes, timeout_seconds=timeout_seconds)
+ yield "\n\n---\n\n"
+ else:
+ if optimize_images:
+ file_bytes = _optimize_image_bytes(file_bytes, max_side=max_side, grayscale=grayscale)
+ yield from _run_single_image_local_stream(file_bytes, timeout_seconds=timeout_seconds)
diff --git a/glm-ocr-pro/requirements.txt b/glm-ocr-pro/requirements.txt
new file mode 100644
index 0000000..97389ef
--- /dev/null
+++ b/glm-ocr-pro/requirements.txt
@@ -0,0 +1,4 @@
+streamlit
+python-dotenv
+pypdfium2
+pillow
diff --git a/glm-ocr-pro/style.css b/glm-ocr-pro/style.css
new file mode 100644
index 0000000..5583922
--- /dev/null
+++ b/glm-ocr-pro/style.css
@@ -0,0 +1,81 @@
+/*
+ GLM-OCR Pro - Premium Design System
+ Indigo / Slate / Neon Accents
+*/
+
+/* Main Sidebar Styling */
+[data-testid="stSidebar"] {
+ background-color: #0c0e14;
+ border-right: 1px solid rgba(255, 255, 255, 0.1);
+}
+
+/* Header Text */
+h1 {
+ font-weight: 800 !important;
+ background: linear-gradient(90deg, #6366f1 0%, #a855f7 100%);
+ -webkit-background-clip: text;
+ background-clip: text;
+ -webkit-text-fill-color: transparent;
+ letter-spacing: -0.02em;
+}
+
+h2, h3 {
+ font-weight: 700 !important;
+ letter-spacing: -0.01em;
+}
+
+/* Custom Card Wrapper (used with st.markdown) */
+.st-emotion-cache-1kyx7g3 {
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 16px;
+ padding: 24px;
+ box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
+ backdrop-filter: blur(5px);
+}
+
+/* Button Styling Overrides */
+.stButton > button {
+ border-radius: 12px !important;
+ font-weight: 600 !important;
+ transition: all 0.2s ease !important;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ font-size: 0.75rem !important;
+}
+
+.stButton > button:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 10px 15px -3px rgba(99, 102, 241, 0.3);
+ border-color: #6366f1 !important;
+}
+
+/* Primary Button Accent */
+div.stButton > button:first-child[kind="primary"] {
+ background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%) !important;
+ border: none !important;
+}
+
+/* Code area custom design */
+.stCode {
+ border-radius: 12px !important;
+ border: 1px solid rgba(255, 255, 255, 0.05) !important;
+}
+
+/* Spinner & Status colors */
+.st-emotion-cache-16idsys p {
+ color: #a5b4fc !important;
+}
+
+/* Info/Success/Warning bubbles */
+.stAlert {
+ border-radius: 12px !important;
+ border: none !important;
+}
+
+/* Divider colors */
+hr {
+ margin: 2em 0 !important;
+ border: 0;
+ border-top: 1px solid rgba(255, 255, 255, 0.1) !important;
+}
diff --git a/glm-ocr-pro/utils.py b/glm-ocr-pro/utils.py
new file mode 100644
index 0000000..c5698d9
--- /dev/null
+++ b/glm-ocr-pro/utils.py
@@ -0,0 +1,6 @@
+import base64
+
+
+def image_bytes_to_base64(file_bytes: bytes) -> str:
+ """Encodes image bytes to base64 string for Ollama consumption."""
+ return base64.b64encode(file_bytes).decode("utf-8")