MatHud - Mathematics Heads-Up Display
MatHud pairs an interactive drawing canvas with an AI assistant to help visualize, analyze, and solve real-world geometry, algebra, and calculus problems in real-time.
1. Key Capabilities
- Draw and manipulate geometric objects (points, segments, vectors, polygons, circles, ellipses, angles) directly on the canvas.
- Ask the assistant to solve algebra, calculus, trigonometry, statistics, and linear algebra problems with LaTeX-formatted explanations.
- Plot functions, compare intersections, shade bounded regions, and translate/rotate objects to explore relationships visually.
- Plot statistics visualizations (probability distributions and bar charts).
- Fit regression models to data (linear, polynomial, exponential, logarithmic,…
MatHud - Mathematics Heads-Up Display
MatHud pairs an interactive drawing canvas with an AI assistant to help visualize, analyze, and solve real-world geometry, algebra, and calculus problems in real-time.
1. Key Capabilities
- Draw and manipulate geometric objects (points, segments, vectors, polygons, circles, ellipses, angles) directly on the canvas.
- Ask the assistant to solve algebra, calculus, trigonometry, statistics, and linear algebra problems with LaTeX-formatted explanations.
- Plot functions, compare intersections, shade bounded regions, and translate/rotate objects to explore relationships visually.
- Plot statistics visualizations (probability distributions and bar charts).
- Fit regression models to data (linear, polynomial, exponential, logarithmic, power, logistic, sinusoidal) and visualize fitted curves with R² statistics.
- Create and analyze graph theory graphs (graphs, trees, DAGs).
- Save, list, load, and delete named workspaces so projects can be resumed or shared later.
- Share the current canvas with the assistant using Vision mode to get feedback grounded in your drawing.
- Trigger client-side tests from the UI or chat to verify canvas behavior without leaving the app.
2. Architecture Overview
- Frontend (Brython) –
static/client/hosts the Brython application (main.py) that wires aCanvas,AIInterface,CanvasEventHandler, and numerous managers. Canvas objects stay math-only; renderers translate them to screen primitives via shared plan builders. - Backend (Flask) –
app.pyboots a Flask app assembled bystatic/app_manager.py, registers routes (static/routes.py), and injects OpenAI, workspace, webdriver, and logging services. - AI integration –
static/openai_api.pywraps the OpenAI SDK, loads tool schemas fromstatic/functions_definitions.py, and maintains model state (static/ai_model.py). - Rendering –
static/client/rendering/factory.pyprefers Canvas2D, then SVG, and finally the still-incomplete WebGL path if earlier options fail. Canvas and SVG renderers include opt-in offscreen staging toggled bywindow.MatHudCanvas2DOffscreen/window.MatHudSvgOffscreenor matchinglocalStorageflags. - Vision pipeline – When the chat payload signals vision, the server either stores a data URL snapshot or drives Selenium (
static/webdriver_manager.py) to replay SVG state in headless Firefox and capturecanvas_snapshots/canvas.pngfor the model.
3. Getting Started
3.1 Prerequisites
- Python 3.10+ (tested with Python 3.11).
- Firefox installed locally for the vision workflow (the
geckodriver-autoinstallerpackage handles the driver). - An OpenAI API key with access to the desired models.
3.2 Environment Setup
- Clone the repository and create a virtual environment:
python -m venv venv
- Activate the environment:
- macOS/Linux:
source venv/bin/activate - Windows (PowerShell):
.\venv\Scripts\Activate.ps1
- Install dependencies:
pip install -r requirements.txt
- Provide credentials by setting
OPENAI_API_KEYin your shell or by creating.envin the project root:
OPENAI_API_KEY=sk-...
3.3 Run MatHud
- Launch the Flask server from the project root:
python app.py
- Open
http://127.0.0.1:5000/in a desktop browser (Chrome, Firefox, or Edge confirmed). The Brython client loads automatically. - Stop the server with
Ctrl+C. The shutdown handler closes any active Selenium session before exiting.
4. Configuration and Authentication
- The server reads configuration from environment variables or
.env(loaded viapython-dotenv). Common options:
OPENAI_API_KEY=sk-...
AUTH_PIN=123456 # Optional: access code required when auth is enabled
REQUIRE_AUTH=true # Force authentication in local development
PORT=5000 # Set by hosting platforms to indicate deployed mode
SECRET_KEY=override-me # Optional: otherwise a random key is generated per launch
-
Authentication rules (
static/app_manager.py): -
When
PORTis set (typical in hosted deployments), authentication is enforced automatically. -
Locally, you can opt-in by setting
REQUIRE_AUTH=true. The login page accepts theAUTH_PINvalue. -
Sessions use
flask-sessionwith a CacheLib-backed store; cookies are upgraded to secure/HTTP-only in deployed mode. -
Vision capture requires Firefox. The first request that needs Selenium will call
/init_webdriver, which in turn relies ongeckodriver-autoinstallerto download the driver if necessary.
5. Working with MatHud
5.1 Canvas Interaction
- Double-click within the canvas to log the precise math coordinates into the chat box.
- Pan by click-dragging; zoom with the mouse wheel (anchored around the cursor).
- The canvas tracks undo/redo, dependencies, and name generation automatically through managers in
static/client/managers/.
5.2 Conversing with the Assistant
-
Type a request in the chat input and press Enter or click Send. The assistant inspects the current canvas state and can call functions on your behalf.
-
Responses support Markdown and LaTeX; MathJax renders inline (
\( ... \)) and block ($$ ... $$) math. -
Sample prompts that map directly to available tools: Note: In this section, "plot" refers to function plots. "graph" refers to graph theory vertices/edges (not dependency graphs).
-
create point at (2, 3) named A -
draw a segment from (0,0) to (3,4) called s1 -
plot y = sin(x) from -pi to pi -
evaluate expression 2*sin(pi/4) -
derive x^3 + 2x - 1 -
solve system of equations: x + y = 5, x - y = 1 -
evaluate linear algebra expression with matrices A=[[1,2],[3,4]]; compute inv(A) -
plot a normal distribution with mean 0 and sigma 1, continuous, shade from -1 to 1 -
plot a bar chart with values [10,20,5] and labels ["A","B","C"] -
fit a linear regression to x_data=[1,2,3,4,5] and y_data=[2,4,6,8,10], show points and report R² -
create an undirected weighted graph named G1 with vertices A,B,C,D and edges A-B (1), B-C (2), A-C (4), C-D (1) -
on graph G1, find the shortest path from A to D and highlight the edges -
create a DAG named D1 with vertices A,B,C,D and edges A->B, A->C, B->D, C->D; then topologically sort it -
save workspace as "demo"/load workspace "demo" -
run tests
5.3 Vision Mode
- Use the Enable Vision checkbox in the chat header to include screenshots of the current canvas.
- The toggle is enabled only for models marked
has_visioninstatic/ai_model.py; non-vision models automatically disable it to avoid unsupported requests. - The server stores the latest snapshot under
canvas_snapshots/canvas.pngfor troubleshooting.
5.4 Workspace Management
- Workspaces are persisted as JSON under
workspaces/. - The chat tools
save_workspace,load_workspace,list_workspaces, anddelete_workspaceare exposed to the assistant and UI. - Client-side restores rebuild the Brython objects through
static/client/workspace_manager.py.
5.5 Testing
- Server tests: run
python run_server_tests.py(add--with-authto exercise authenticated flows). - Client tests: click Run Tests in the UI or ask the assistant to "run tests". Results stream back into the chat after execution (
static/client/test_runner.py).
6. Rendering Notes
static/client/rendering/factory.pyinstantiates renderers in preference ordercanvas2d → svg → webgl. If a constructor raises (for example, WebGL unavailable), the factory continues down the chain.- Canvas2D rendering (
canvas2d_renderer.py) supports optional offscreen compositing. Toggle it withwindow.MatHudCanvas2DOffscreen = trueorlocalStorage["mathud.canvas2d.offscreen"] = "1". - SVG rendering (
svg_renderer.py) mirrors the same offscreen staging controls throughwindow.MatHudSvgOffscreenorlocalStorage["mathud.svg.offscreen"]. - The WebGL renderer (
webgl_renderer.py) is experimental, not feature complete, and only instantiates when the browser exposes a WebGL context.
7. Diagram Generation
- Generate the full suite of diagrams from the project root:
python generate_diagrams_launcher.py
-
Output directories:
-
diagrams/generated_png/– raster versions for quick sharing. -
diagrams/generated_svg/– scalable diagrams for documentation. -
Additional guidance lives in
diagrams/README.mdanddiagrams/WORKFLOW_SUMMARY.md.
8. Repository Guide
app.py– entry point with graceful shutdown and threaded dev server.static/a.app_manager.py,routes.py,openai_api.py,ai_model.py,tool_call_processor.py,workspace_manager.py,log_manager.py,webdriver_manager.py. b.client/– Brython modules (canvas, managers, rendering, tests, utilities, workspace manager).templates/index.html– main HTML shell that loads Brython, MathJax, styles, and UI controls.workspaces/– saved canvas states.canvas_snapshots/– latest Selenium captures used for vision.server_tests/– pytest suites, including renderer plan tests underserver_tests/client_renderer/.documentation/– extended reference material.logs/– session-specific server logs.
9. Additional Documentation
documentation/Project Architecture.txt– deep dive into system design.documentation/Reference Manual.txt– comprehensive API and module reference.documentation/Example Prompts.txt– curated prompts for common workflows.