Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

40 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Build Status Python FastAPI PyTorch MongoDB License

๐Ÿงฎ The Editorial โ€” Math OCR System

Write it. Snap it. Solve it.
A full-stack AI-powered system that reads handwritten or printed math from images and solves it instantly.


๐Ÿ“Œ Introduction

The Editorial is a production-grade, full-stack web application that transforms handwritten or printed mathematical equations into structured LaTeX, then solves them symbolically or numerically โ€” all in real time. Draw on a canvas, upload a photo of your notebook, or type LaTeX directly; the system handles the rest with state-of-the-art vision transformers and a robust computer algebra engine.

View Live App


๐Ÿ”ญ Project Overview

Mathematics has always been a visual language, yet the tools for digitising it remain frustratingly manual. The Editorial bridges that gap.

The system was built to solve a specific pain point: taking a photo of a math problem on paper and getting an instant, verified solution โ€” without retyping a single symbol.

Under the hood it chains together:

  1. Intelligent Image Preprocessing โ€” OpenCV pipelines that handle everything from camera photos with shadows and skew to transparent web-canvas drawings.
  2. Dual OCR Engine โ€” Texify (a fine-tuned vision transformer) runs first; Pix2Tex acts as a secondary fallback when the primary parse fails validation.
  3. LaTeX Normalization โ€” A regex-powered sanitization layer that fixes common OCR quirks (missing backslashes, Unicode artifacts, implicit multiplication) before anything reaches the solver.
  4. Symbolic Solving โ€” SymPy and latex2sympy2 handle algebraic equations, definite/indefinite integrals, and expression simplification with both exact and numeric output modes.
  5. Persistent History โ€” Every equation is stored in MongoDB with dual-LaTeX tracking (raw OCR output vs. user-edited version) for full auditability.

๐Ÿ—๏ธ Architecture

The system follows a clean three-tier architecture: a static frontend dashboard, a FastAPI REST backend, and a MongoDB persistence layer.

Click to view full interactive architecture

View Full Architecture

๐Ÿ’ก Click the button above to explore the full interactive architecture diagram โ€” built as a standalone HTML page with animated data flow, API endpoint maps, database schema, and OCR pipeline breakdown.


๐Ÿ“ธ Screenshots & Demo

Demo Video

โš™๏ธ Tech Stack

Layer Technology Purpose
Frontend HTML5, CSS3, Vanilla JS Premium dark-themed SPA dashboard
Math Rendering KaTeX 0.16 Real-time LaTeX โ†’ beautiful typography
Math Editing MathQuill 0.10 Visual WYSIWYG equation editor
Backend FastAPI 0.135 + Uvicorn Async REST API with auto-generated docs
OCR โ€” Primary Texify 0.2 (Vision Transformer) Image โ†’ LaTeX conversion
OCR โ€” Fallback Pix2Tex 0.1 Secondary LaTeX extraction model
Image Processing OpenCV 4.13 + Pillow 10.4 Shadow crushing, deskew, binarization
Computer Algebra SymPy 1.14 + latex2sympy2 Symbolic & numeric equation solving
Deep Learning PyTorch 2.10, Transformers 4.38 Model inference backbone
Database MongoDB Atlas (PyMongo 4.16) Cloud NoSQL persistence
Validation Pydantic 2.12 Request/response schema enforcement
Testing Pytest 9.0 Unit tests for normalization pipeline
DevOps Docker (Dockerfile), .env config Containerized deployment ready

โœจ Core Features

  • ๐Ÿ–Š๏ธ Handwriting Canvas โ€” Draw equations directly in the browser with pen/eraser tools, adjustable thickness, undo/redo, and instant OCR parsing.
  • ๐Ÿ“ท Image Upload & OCR โ€” Drag-and-drop or upload PNG/JPEG/PDF images of printed or handwritten math; the system preprocesses and extracts LaTeX automatically.
  • โŒจ๏ธ MathQuill Equation Editor โ€” Type or edit LaTeX visually with a rich, interactive WYSIWYG math input complete with quick-insert symbol buttons.
  • ๐Ÿง  Dual-Engine OCR โ€” Texify (transformer-based) runs first; Pix2Tex validates and acts as fallback, ensuring the best possible LaTeX output.
  • ๐Ÿ”ฌ Smart Image Preprocessing โ€” Adaptive binarization with stroke-width detection prevents thick markers from blobing while rescuing faint pencil strokes. Handles dark-mode screenshots, transparent canvas PNGs, and camera photos with shadow crushing and deskew.
  • ๐Ÿ“ Symbolic & Numeric Solving โ€” Supports algebraic equations, definite/indefinite integrals, trigonometric expressions, and complex numbers. Toggle between exact symbolic and rounded numeric output.
  • ๐Ÿ“Š Interactive Plot Data โ€” For polynomial equations of degree โ‰ฅ 3, the solver generates plot coordinates for visual graphing on the frontend.
  • ๐Ÿ“œ Equation History Archive โ€” Full session-based history stored in MongoDB with search, filter (by type, date, status), batch delete, and data export.
  • ๐ŸŽจ Premium Dark/Light Theme โ€” Sleek, modern UI with glassmorphism aesthetics, smooth animations, and three theme modes (Dark, Light, System).
  • โ™ฟ Accessibility Settings โ€” Interface scaling, high-contrast mode, screen-reader optimized equation output, and customizable math typography fonts.
  • ๐Ÿ”„ Dual-LaTeX Tracking โ€” Every record stores both the raw OCR output (ocr_latex) and the user-edited version (final_latex) for debugging and auditability.

๐Ÿ› ๏ธ The Process

This project was developed iteratively with a pipeline-first methodology:

  1. OCR Pipeline First โ€” The image preprocessing and OCR engine were built and validated in isolation before any frontend existed. The goal: get accurate LaTeX from messy camera photos.
  2. Solver Hardening โ€” SymPy's parse_latex proved fragile with raw OCR output, so a multi-layer sanitization pipeline was built (latex_normalize.py โ†’ solver.py) with regex-based cleaning, and latex2sympy2 was integrated as a primary parser with the manual regex pipeline as fallback.
  3. Frontend as a Dashboard โ€” The UI was designed as a premium editorial experience, not a utility screen. MathQuill replaced basic textareas, KaTeX handles rendering, and the canvas supports full drawing tools.
  4. Database & History โ€” MongoDB Atlas was chosen for flexible schema evolution. The dual-LaTeX schema was introduced to track OCR accuracy vs. user corrections over time.
  5. Test-Driven Normalization โ€” Edge cases (higher-order derivatives, Unicode Greek, inverse trig from OCR) were captured as pytest fixtures to prevent regressions.

๐Ÿ“ Folder Structure

math-ocr-system/
โ”œโ”€โ”€ ๐Ÿ“„ .env.example              # Environment variable template
โ”œโ”€โ”€ ๐Ÿ“„ .gitignore                # Git ignore rules
โ”œโ”€โ”€ ๐Ÿ“„ .Dockerfile               # Docker build configuration
โ”œโ”€โ”€ ๐Ÿ“„ requirements.txt          # Python dependencies
โ”œโ”€โ”€ ๐Ÿ“„ README.md                 # โ† You are here
โ”‚
โ”œโ”€โ”€ ๐Ÿ“‚ src/
โ”‚   โ”œโ”€โ”€ ๐Ÿ“‚ app/                  # Backend application layer
โ”‚   โ”‚   โ”œโ”€โ”€ main.py              # FastAPI app entry point, model loading, routes
โ”‚   โ”‚   โ”œโ”€โ”€ routes.py            # API route handlers (/solve, /history CRUD)
โ”‚   โ”‚   โ”œโ”€โ”€ solver.py            # LaTeX โ†’ SymPy solving engine (626 lines)
โ”‚   โ”‚   โ”œโ”€โ”€ schemas.py           # Pydantic request/response models
โ”‚   โ”‚   โ””โ”€โ”€ database.py          # MongoDB data access layer (PyMongo)
โ”‚   โ”‚
โ”‚   โ”œโ”€โ”€ ๐Ÿ“‚ ocr/                  # OCR engine & image processing
โ”‚   โ”‚   โ”œโ”€โ”€ hybrid_ocr.py        # Texify + Pix2Tex dual-engine pipeline
โ”‚   โ”‚   โ”œโ”€โ”€ preprocess_math.py   # Advanced OpenCV preprocessing (251 lines)
โ”‚   โ”‚   โ”œโ”€โ”€ preprocessing.py     # Entry point router (auto/pil/manual variants)
โ”‚   โ”‚   โ”œโ”€โ”€ latex_parser.py      # EquationParser โ€” LaTeX โ†’ structured dict
โ”‚   โ”‚   โ”œโ”€โ”€ latex_normalize.py   # OCR LaTeX cleanup & normalization
โ”‚   โ”‚   โ”œโ”€โ”€ latex_utils.py       # String cleaning utilities
โ”‚   โ”‚   โ”œโ”€โ”€ ocr_model.py         # TrOCR HuggingFace model wrapper
โ”‚   โ”‚   โ”œโ”€โ”€ equation_structure.py
โ”‚   โ”‚   โ””โ”€โ”€ __init__.py
โ”‚   โ”‚
โ”‚   โ””โ”€โ”€ ๐Ÿ“‚ frontend/             # Client-side web application
โ”‚       โ”œโ”€โ”€ index.html           # SPA dashboard (510 lines)
โ”‚       โ”œโ”€โ”€ style.css            # Premium dark-theme styles (39K)
โ”‚       โ””โ”€โ”€ app.js               # Application logic & API integration (44K)
โ”‚
โ”œโ”€โ”€ ๐Ÿ“‚ tests/                    # Test suite
โ”‚   โ””โ”€โ”€ test_latex_normalize.py  # Normalization & sanitization tests
โ”‚
โ”œโ”€โ”€ ๐Ÿ“‚ models/                   # AI model weights (git-ignored)
โ”œโ”€โ”€ ๐Ÿ“‚ data/                     # Image processing pipeline
โ”‚   โ”œโ”€โ”€ ๐Ÿ“‚ raw_images/           # Uploaded originals (git-ignored)
โ”‚   โ””โ”€โ”€ ๐Ÿ“‚ cleaned_images/       # Preprocessed outputs (git-ignored)
โ”‚
โ””โ”€โ”€ ๐Ÿ“‚ venv/                     # Python virtual environment (git-ignored)

๐Ÿš€ Setup Instructions

Prerequisites

  • Python 3.10+ installed on your system
  • MongoDB Atlas account (or local MongoDB Community Server on port 27017)
  • Git for cloning the repository

1. Clone the Repository

git clone https://github.com/Bhomaramsuthar/Math-OCR-System.git
cd Math-OCR-System

2. Create & Activate Virtual Environment

python -m venv venv

# Windows (PowerShell)
.\venv\Scripts\Activate.ps1

# Windows (CMD)
venv\Scripts\activate.bat

# macOS / Linux
source venv/bin/activate

3. Install Dependencies

pip install -r requirements.txt

โš ๏ธ Note: PyTorch 2.10 with CUDA support requires a separate install command. See pytorch.org for GPU-accelerated installation.

4. Configure Environment Variables

# Copy the template
cp .env.example .env

# Edit .env and add your MongoDB connection string
# MONGODB_URI=mongodb+srv://<user>:<password>@<cluster>.mongodb.net/?appName=Cluster0

5. Start the Backend Server

uvicorn src.app.main:app --reload --host 0.0.0.0 --port 8000

The API will be live at http://localhost:8000 with interactive docs at http://localhost:8000/docs.

6. Open the Frontend

Open src/frontend/index.html in your browser, or use the Live Server VS Code extension for hot-reload during development. Make sure the API base URL in app.js points to your running backend.

7. Run Tests

pytest tests/ -v

๐Ÿ” Environment Variables

Variable Required Description
MONGODB_URI โœ… Yes MongoDB connection string (Atlas or local). Example: mongodb+srv://user:pass@cluster.mongodb.net/?appName=Cluster0

Create a .env file in the project root. See .env.example for the template.


๐Ÿงช What I Learned

Building this system surfaced a series of deep technical challenges:

  • OCR-to-CAS is harder than it looks โ€” Raw LaTeX from vision models contains subtle formatting quirks (missing backslashes, Unicode replacements, implicit multiplication) that crash standard parsers. I built a multi-layer regex normalization pipeline that handles dozens of edge cases before SymPy ever sees the input.

  • Stroke-width-based preprocessing โ€” Generic binarization either obliterates faint pencil lines or bloats thick marker strokes. I implemented adaptive stroke-width estimation using OpenCV's distance transform, then conditionally applied morphological operations only when strokes are thin/fragmented.

  • Dual-parser fallback strategy โ€” Instead of relying on a single OCR model, the system runs Texify first, validates the output against latex_parseable(), and falls back to Pix2Tex only when needed. This cut parse failures by ~40%.

  • Definite integral edge cases โ€” SymPy's symbolic integrator can silently return unevaluated Integral objects for valid expressions. I added a numeric fallback path using sympy.N() that catches these cases and still returns a meaningful result.

  • Schema evolution in NoSQL โ€” As the data model evolved (adding final_latex, solution_latex, etc.), older MongoDB documents lacked new fields. I implemented setdefault() normalization in the query layer so the frontend always receives a consistent document shape.

  • Canvas transparency handling โ€” Web <canvas> exports transparent PNGs where the "white background" is actually alpha=0. The preprocessing pipeline composites these onto a white background before any grayscale conversion.


โš ๏ธ Known Limitations

While The Editorial handles a wide range of mathematical expressions, there are constraints worth noting:

Area Limitation
Expression Complexity The solver rejects expressions longer than 100 characters or with more than 10 backslash commands โ€” a safety guard against pathological inputs that could hang the CAS engine.
Supported Math Types Currently limited to algebraic equations, integrals (definite & indefinite), expression simplification, Differential equations, limits, summations& matrix operations are not yet solvable.
OCR Accuracy Heavily stylised handwriting, overlapping symbols, or very low-resolution images can produce incorrect LaTeX. Multi-line or multi-equation images are not supported โ€” only single expressions per image.
LaTeX Subset Unsupported LaTeX constructs include \begin{array}, \mathbb, \mathbf, and \operatorname (except for inverse trig). These are flagged as "garbage" and rejected.
No Step-by-Step The solver returns the final answer only โ€” intermediate algebraic steps (factoring, substitution, etc.) are not shown.
Single Variable Focus Equation solving defaults to the first free symbol alphabetically. Systems of equations with multiple unknowns are not supported.
Session Isolation History is tied to browser-generated session IDs with no authentication โ€” there is no user account system or cross-device sync.
Cold Start Latency The first request after server boot takes 10โ€“30 seconds as both the Texify and Pix2Tex models are loaded into memory. Subsequent requests are fast.
PDF Support While the upload UI accepts PDF files, only rasterized/image-based PDFs are processed. Native vector PDFs with selectable text are not parsed.

๐Ÿ”ฎ Future Scope & Features

  • Multi-step Solution Breakdown โ€” Show intermediate algebraic steps (factoring, substitution, integration by parts) instead of just the final answer, using SymPy's step-by-step solver.
  • Improved Error Messages โ€” Surface specific feedback when OCR fails (e.g., "Handwriting too faint โ€” try a darker pen") instead of generic error strings.
  • User Authentication โ€” Add OAuth-based login (Google/GitHub) so equation history persists across devices and browsers.
  • Matrix & Linear Algebra โ€” Support for determinants, eigenvalues, matrix multiplication, and systems of linear equations via sympy.Matrix.
  • Custom Model Fine-Tuning โ€” Fine-tune the Texify model on a curated dataset of handwritten math to improve recognition accuracy for non-standard notations and regional handwriting styles.

๐Ÿ“„ License

This project is licensed under the MIT License โ€” see the LICENSE file for details.

MIT License

Copyright (c) 2026 Bhomaram Suthar

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Built with โค๏ธ and a lot of LaTeX debugging.
If this project helped you, consider giving it a โญ

About

Application that transforms handwritten or printed mathematical equations into structured LaTeX, then solves them symbolically or numerically

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages