Write it. Snap it. Solve it.
A full-stack AI-powered system that reads handwritten or printed math from images and solves it instantly.
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.
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:
- Intelligent Image Preprocessing โ OpenCV pipelines that handle everything from camera photos with shadows and skew to transparent web-canvas drawings.
- Dual OCR Engine โ Texify (a fine-tuned vision transformer) runs first; Pix2Tex acts as a secondary fallback when the primary parse fails validation.
- LaTeX Normalization โ A regex-powered sanitization layer that fixes common OCR quirks (missing backslashes, Unicode artifacts, implicit multiplication) before anything reaches the solver.
- Symbolic Solving โ SymPy and
latex2sympy2handle algebraic equations, definite/indefinite integrals, and expression simplification with both exact and numeric output modes. - Persistent History โ Every equation is stored in MongoDB with dual-LaTeX tracking (raw OCR output vs. user-edited version) for full auditability.
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
๐ก 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.
| 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 |
- ๐๏ธ 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.
This project was developed iteratively with a pipeline-first methodology:
- 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.
- Solver Hardening โ SymPy's
parse_latexproved fragile with raw OCR output, so a multi-layer sanitization pipeline was built (latex_normalize.pyโsolver.py) with regex-based cleaning, andlatex2sympy2was integrated as a primary parser with the manual regex pipeline as fallback. - 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.
- 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.
- Test-Driven Normalization โ Edge cases (higher-order derivatives, Unicode Greek, inverse trig from OCR) were captured as
pytestfixtures to prevent regressions.
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)
- Python 3.10+ installed on your system
- MongoDB Atlas account (or local MongoDB Community Server on port
27017) - Git for cloning the repository
git clone https://github.com/Bhomaramsuthar/Math-OCR-System.git
cd Math-OCR-Systempython -m venv venv
# Windows (PowerShell)
.\venv\Scripts\Activate.ps1
# Windows (CMD)
venv\Scripts\activate.bat
# macOS / Linux
source venv/bin/activatepip install -r requirements.txt
โ ๏ธ Note: PyTorch 2.10 with CUDA support requires a separate install command. See pytorch.org for GPU-accelerated installation.
# 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=Cluster0uvicorn src.app.main:app --reload --host 0.0.0.0 --port 8000The API will be live at http://localhost:8000 with interactive docs at http://localhost:8000/docs.
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.
pytest tests/ -v| Variable | Required | Description |
|---|---|---|
MONGODB_URI |
โ Yes | MongoDB connection string (Atlas or local). Example: mongodb+srv://user:pass@cluster.mongodb.net/?appName=Cluster0 |
Create a
.envfile in the project root. See.env.examplefor the template.
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
Integralobjects for valid expressions. I added a numeric fallback path usingsympy.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 implementedsetdefault()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.
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. |
- 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.
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 โญ
