Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 26 additions & 7 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,10 @@
#
# That exclusion got more expensive on 2026-08-28. Android's suite went from 22
# tests to 50: the printed-rule port added ten, PageNormalizer's newly-testable
# internals fourteen, and the cv2 dilation fixture four. Six of those fifty are the
# fixture tests, and they are the only automated check that this app's segmenter and
# its page normaliser still agree with web and iOS, the two ports CI does run. The
# three shared fixtures below are verified on every push, but nothing here verifies
# that the Kotlin side still matches them.
# internals fourteen, and the cv2 dilation fixture four. Some of those are the
# fixture tests, the only automated check that this app's segmenter and page
# normaliser still agree with web and iOS. The `android` job now runs them on every
# push, alongside the web and iOS fixture checks.
#
# iOS is no longer excluded, but only its pure logic. `apps/ios/MonOcrCore` is a
# Swift package over the Foundation-only files, so `swift test` needs no
Expand Down Expand Up @@ -785,6 +784,28 @@ jobs:
done
echo "charsets identical ($(wc -c < "$ref") bytes)"

- name: The bundled models are the pinned bytes
# Web checks the download against MODEL_SHA256 and Android checks its
# asset at load, but nothing checked the committed files themselves: a
# re-export or a bad merge could replace them and every test would still
# pass. Android's asset must match the hash both engines pin, read from the
# source so this list cannot drift from it. iOS pins no hash in its own
# source, so its Core ML files are pinned here to the bytes committed on
# 2026-11-10: changing the export means changing these lines with it.
run: |
set -euo pipefail
kt=apps/android/app/src/main/java/dev/janakhpon/monocr/engine/MonOcrEngine.kt
pinned="$(sed -n 's/.*MODEL_SHA256 = "\([0-9a-f]\{64\}\)".*/\1/p' "$kt")"
[ -n "$pinned" ] || { echo "::error file=$kt::no MODEL_SHA256 found"; exit 1; }
grep -q "MODEL_SHA256 = '$pinned'" apps/web/src/lib/monocr-onnx.ts \
|| { echo "::error::web MODEL_SHA256 differs from Android's"; exit 1; }
sha256sum -c - <<EOF
$pinned apps/android/app/src/main/assets/monocr.onnx
3d1158a654e93d5de50e9ab2a794fc574ef050a6160239d65f77fd8039f19f6d apps/ios/monocr-ios/monocr.mlpackage/Manifest.json
b8ad3699faf4a4644812c58867ca214997e956f1522a485804c97cbe065fca11 apps/ios/monocr-ios/monocr.mlpackage/Data/com.apple.CoreML/model.mlmodel
aaa035c39c34753c2695e3e25766eb3d71d8bf291536244d48b4857206834698 apps/ios/monocr-ios/monocr.mlpackage/Data/com.apple.CoreML/weights/weight.bin
EOF

- name: The charset keeps its leading U+0020
# A bare trim() eats it and shifts every decoded index by one.
run: |
Expand All @@ -799,7 +820,6 @@ jobs:
missing=0
for f in apps/web/src/lib/config.ts \
apps/web/src/lib/monocr-onnx.ts \
apps/web/functions/monocr.onnx.js \
apps/ios/monocr-ios/MonOcrEngine.swift \
apps/android/app/src/main/java/dev/janakhpon/monocr/engine/MonOcrEngine.kt; do
grep -q "$pinned" "$f" || { echo "::error file=$f::does not mention the pinned revision $pinned"; missing=1; }
Expand All @@ -809,7 +829,6 @@ jobs:
stale="$(grep -ln 'a51be11' \
apps/web/src/lib/config.ts \
apps/web/src/lib/monocr-onnx.ts \
apps/web/functions/monocr.onnx.js \
apps/ios/monocr-ios/MonOcrEngine.swift \
apps/android/app/src/main/java/dev/janakhpon/monocr/engine/MonOcrEngine.kt 2>/dev/null || true)"
if [ -n "$stale" ]; then
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,10 @@ Android and iOS bundle it (46.2 MB and 46.3 MB respectively). The web app and th

## Limitations

**Held-out CER 0.0100** on 150 unseen lines in a typeface the model never trained on (95% interval 0.0056 to 0.0147), measured 2026-08-16. The [model card](https://huggingface.co/janakhpon/monocr#evaluation) states its limits:
**Held-out CER 0.0095** (95% interval 0.0079 to 0.0111) on 1,997 synthetic Mon lines (0.0061 over all 3,002 Mon, Burmese and English lines), in a typeface design the model never trained on, measured 2026-11-11. The [model card](https://huggingface.co/janakhpon/monocr#evaluation) states its limits:

- **n = 150**, so the interval is wide.
- **One typeface.** All 150 lines are Pyidaungsu, held out from training.
- **Synthetic lines, not real pages.** It is not accuracy on photographed or scanned pages.
- **One typeface design.** Every line is Pyidaungsu, Regular and Bold, held out from training.
- **Unseen text, not an unseen renderer.** Training and test images came from the same generator, so the number says nothing yet about camera photographs of real pages.
- **Disjointness is argued, not directly verified.**

Expand Down
12 changes: 12 additions & 0 deletions apps/android/app/src/main/res/xml-v28/backup_rules.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Android 9 to 11 (API 28 to 30). Mirrors data_extraction_rules.xml:
cloud backup takes settings only, while a device-to-device transfer also
takes scan history, recognised text and images. requireFlags is honoured
from API 28, which is why this file lives in xml-v28; on API 24 to 27 the
flagged include would apply to cloud backup too.
-->
<full-backup-content>
<include domain="sharedpref" path="." />
<include domain="root" path="." requireFlags="deviceToDeviceTransfer" />
</full-backup-content>
13 changes: 10 additions & 3 deletions apps/android/app/src/main/res/xml/backup_rules.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Android 7 and 8 (API 24 to 27). Must back up what data_extraction_rules.xml
lets cloud-backup take on Android 12+, and nothing more: settings only. The
database and files hold scan history, recognised text and images, which stay
on the device.

These versions cannot tell cloud backup from a device-to-device transfer
(requireFlags needs API 28), so scan history does not move to a new phone
here either. Android 9 to 11 use xml-v28/backup_rules.xml, which does.
-->
<full-backup-content>
<!-- Include essential data -->
<include domain="database" path="." />
<include domain="sharedpref" path="." />
<include domain="file" path="." />
</full-backup-content>
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package dev.janakhpon.monocr.ui

import java.io.File
import javax.xml.parsers.DocumentBuilderFactory
import org.junit.Assert.assertEquals
import org.junit.Test
import org.w3c.dom.Element

/**
* Cloud backup takes the same data on every Android version, and a
* device-to-device transfer takes scan history wherever Android can tell the
* two apart.
*
* `data_extraction_rules.xml` (Android 12+) limited cloud backup to shared
* preferences while `backup_rules.xml` (Android 11 and older) still sent the
* database and files, so scan history left the device on older phones only.
* `requireFlags="deviceToDeviceTransfer"` exists from API 28, so Android 9 to
* 11 (`xml-v28`) keep the history transfer; Android 7 and 8 cannot without
* also sending it to cloud backup, so they transfer settings only.
*/
class BackupRulesTest {
private fun includes(path: String, parentTag: String? = null): List<Element> {
val doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(File(path))
val root: Element = if (parentTag == null) doc.documentElement
else doc.getElementsByTagName(parentTag).item(0) as Element
val nodes = root.getElementsByTagName("include")
return (0 until nodes.length).map { nodes.item(it) as Element }
}

/** Domains every backup takes: includes with no `requireFlags`. */
private fun unflagged(path: String) =
includes(path).filter { !it.hasAttribute("requireFlags") }.map { it.getAttribute("domain") }.toSet()

private fun deviceTransferOnly(path: String) =
includes(path).filter { it.getAttribute("requireFlags") == "deviceToDeviceTransfer" }
.map { it.getAttribute("domain") }.toSet()

private val cloud = includes("src/main/res/xml/data_extraction_rules.xml", "cloud-backup")
.map { it.getAttribute("domain") }.toSet()
private val transfer = includes("src/main/res/xml/data_extraction_rules.xml", "device-transfer")
.map { it.getAttribute("domain") }.toSet()

@Test fun `older Android backs up only what Android 12 cloud backup does`() {
assertEquals(setOf("sharedpref"), cloud)
// API 24 to 27 ignore requireFlags, so any include there reaches cloud backup.
assertEquals(emptyList<Element>(), includes("src/main/res/xml/backup_rules.xml").filter { it.hasAttribute("requireFlags") })
assertEquals(cloud, unflagged("src/main/res/xml/backup_rules.xml"))
assertEquals(cloud, unflagged("src/main/res/xml-v28/backup_rules.xml"))
}

@Test fun `Android 9 to 11 transfer to a new device what Android 12 does`() {
assertEquals(setOf("root"), transfer)
assertEquals(transfer, deviceTransferOnly("src/main/res/xml-v28/backup_rules.xml"))
}
}
19 changes: 19 additions & 0 deletions apps/ios/MonOcrCore/Tests/MonOcrCoreTests/CtcDecoderTests.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Foundation
import Testing

@testable import MonOcrCore
Expand Down Expand Up @@ -66,4 +67,22 @@ struct CtcDecoderTests {
try CtcDecoder.decode(logits: logits, timeSteps: 2, numClasses: 4, charset: "AB")
}
}

/// The decoded text must never reach the log file: "Export Debug Logs" on the
/// About screen shares that file, and release builds used to append every
/// recognised line to it. Tests run as a DEBUG build, where debug and info lines
/// do reach the file, so this catches a decoder that logs its result at any level.
@Test func decodedTextIsNeverWrittenToTheLogFile() throws {
// Only what this decode appends is checked: the file outlives the run, so
// a line from an earlier build must not fail this one.
let before = (try? Data(contentsOf: MonLogger.logFileURL))?.count ?? 0
let charset = "QJXZVK"
let logits = buildLogits(timeSteps: 6, numClasses: 7, argmaxes: [1, 2, 3, 4, 5, 6])
let result = try CtcDecoder.decode(logits: logits, timeSteps: 6, numClasses: 7, charset: charset)
#expect(result == charset)
let data = (try? Data(contentsOf: MonLogger.logFileURL)) ?? Data()
let appended = String(decoding: data.dropFirst(data.count >= before ? before : 0), as: UTF8.self)
#expect(!appended.contains(charset))
#expect(!appended.contains("[1:Q]"))
}
}
7 changes: 3 additions & 4 deletions apps/ios/monocr-ios/CtcDecoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ nonisolated enum CtcDecoder {
// Step 2 & 3: CTC collapse — remove blanks (0) and consecutive duplicates
let decoded = NSMutableString()
var prevIdx = -1
var pathDescription = ""

for idx in predictions {
if idx != 0 && idx != prevIdx {
Expand All @@ -95,14 +94,14 @@ nonisolated enum CtcDecoder {
}
let char = String(Character(scalar))
decoded.append(char)
pathDescription += "[\(idx):\(char)] "
}
prevIdx = idx
}

let result = decoded as String
MonLogger.d("CTC Path: \(pathDescription)")
MonLogger.i("CTC Result: '\(result)'")
// A count, never the text: the log file can be exported from the About
// screen, and what a person scanned is theirs, not diagnostics.
MonLogger.d("CTC decoded \(result.count) characters")
return result
}
}
40 changes: 32 additions & 8 deletions apps/ios/monocr-ios/Logger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,40 @@ import os.log
/**
* A lightweight, structured logging utility for MonOCR iOS.
* Utilizes Apple's os.log for performance and system integration.
*
* The log file is the one "Export Debug Logs" on the About screen shares, so it
* must never hold what a person scanned. Two rules keep it that way: debug and
* info lines reach the file only in DEBUG builds, and os_log marks every message
* private, so a release build's unified log redacts it unless a debugger is
* attached. Callers still log counts and sizes, never recognised text.
*/
nonisolated enum MonLogger {
private static let log = OSLog(subsystem: "mondevhub.monocr", category: "App")
private static let maxFileSize: UInt64 = 1 * 1024 * 1024 // 1 MB


#if DEBUG
static let writesVerboseLinesToFile = true
#else
static let writesVerboseLinesToFile = false
#endif

static var logFileURL: URL {
_ = legacyLogRemoved
return cachesDirectory.appendingPathComponent("monocr_diagnostics.txt")
}

private static var cachesDirectory: URL {
FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
.appendingPathComponent("monocr_logs.txt")
}

/// Builds before this file name logged every recognised line to
/// `monocr_logs.txt` in release builds too. Delete it once per launch so an
/// export can never carry that text.
private static let legacyLogRemoved: Void = {
try? FileManager.default.removeItem(
at: cachesDirectory.appendingPathComponent("monocr_logs.txt"))
}()

private static let dateFormatter: DateFormatter = {
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
Expand Down Expand Up @@ -47,23 +71,23 @@ nonisolated enum MonLogger {
}

nonisolated static func d(_ message: String) {
os_log("%{public}@", log: log, type: .debug, message)
appendToFile(level: "D", message: message)
os_log("%{private}@", log: log, type: .debug, message)
if writesVerboseLinesToFile { appendToFile(level: "D", message: message) }
}

nonisolated static func i(_ message: String) {
os_log("%{public}@", log: log, type: .info, message)
appendToFile(level: "I", message: message)
os_log("%{private}@", log: log, type: .info, message)
if writesVerboseLinesToFile { appendToFile(level: "I", message: message) }
}

nonisolated static func w(_ message: String) {
os_log("%{public}@", log: log, type: .default, "[W] " + message)
os_log("%{private}@", log: log, type: .default, "[W] " + message)
appendToFile(level: "W", message: message)
}

nonisolated static func e(_ message: String, error: Error? = nil) {
let errorMessage = error != nil ? "\(message) | Error: \(error!.localizedDescription)" : message
os_log("%{public}@", log: log, type: .error, "[E] " + errorMessage)
os_log("%{private}@", log: log, type: .error, "[E] " + errorMessage)
appendToFile(level: "E", message: errorMessage)
}
}
Expand Down
4 changes: 3 additions & 1 deletion apps/web/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,9 @@ curl -L -o static/monocr.onnx \
falls back to the pinned URL otherwise, printing which one it chose; production never reads it.
Fetch exactly that revision and keep it equal to `CONFIG.MODELS.RECOGNITION`: `static/charset.txt`
is 276 characters, and the app refuses a model that does not match it with a `ModelContractError`
at load rather than returning wrong text.
at load rather than returning wrong text. Before that, every model download, local or remote, must
hash to `MODEL_SHA256` in `src/lib/monocr-onnx.ts` or it is refused with a `ModelIntegrityError`
and not cached.

## Test and check

Expand Down
1 change: 0 additions & 1 deletion apps/web/eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ export default ts.config(
'src/lib/utils/use-intersection.svelte.ts',
// Vendored quiet-ds: linted in its own repository, with its own rules.
'src/lib/quiet/',
'functions/',
// Generated by `paraglide-js compile`. .prettierignore already skips
// these; eslint did not, so regenerating them produced 114 warnings
// on code nobody writes. A linter that reports on generated output
Expand Down
43 changes: 0 additions & 43 deletions apps/web/functions/monocr.onnx.js

This file was deleted.

4 changes: 1 addition & 3 deletions apps/web/src/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ export const CONFIG = {
// Local override for development. Put the model at `static/monocr.onnx`
// and every reload reads it off disk instead of pulling 46.2 MB from
// Hugging Face. Gitignored — see the README for the fetch command.
//
// The path is the same one `functions/monocr.onnx.js` proxies in
// production, so nothing about the request shape changes between the two.
// It is checked against the same MODEL_SHA256 as the pinned download.
RECOGNITION_LOCAL: '/monocr.onnx',

CHARSET: '/charset.txt'
Expand Down
Loading
Loading