Engineering BlueprintPythonFastAPISQLiteMandarinFSRSOllamaOpen SourceSpeakOn

SpeakOn Phase 5: Mandarin Studio Backend, Open Datasets, FSRS Replay, and Signed SQLite Packs

Building the Mandarin Studio backend in speakon-services: SHA-256 dataset lockfiles, bilingual YAML curriculum, deterministic jieba/pypinyin/OpenCC/DTW…

Célio Vieira611 words4 min read

Key Takeaways (TL;DR)

Summary
  • Separating Copyleft Datasets from Apache-2.0 Source — Third-party Mandarin resources span incompatible source licenses: Make Me a Hanzi pairs LGPL-3.0 definitions…
  • 11-Table Schema & Bilingual Foundations Curriculum — Migration 0002phase5mandarin_studio adds 11 SQLModel tables unified with users.id: HanziCharacter, DictionaryEntry…
  • Offline Linguistics, Sandhi Edge Cases & DTW Strokes — Every deterministic service under app/mandarin/ operates with zero network calls:
  • Cached Ollama AI Engines & HSK Vocabulary Gate — Extending OllamaLLMProvider.chatjson with schema validation and a single JSON repair retry powers four local AI workbenches…

Separating Copyleft Datasets from Apache-2.0 Source#

Third-party Mandarin resources span incompatible source licenses: Make Me a Hanzi pairs LGPL-3.0 definitions (dictionary.txt) with Arphic Public License stroke vectors (graphics.txt), CC-CEDICT is CC BY-SA 4.0, and complete-hsk-vocabulary is MIT. In Phase 5 of SpeakOn (Celio1878/speakon-services on develop), we kept datasets/ and data/ completely out of Git.

Instead, the repository commits only an explicit SHA-256 lockfile (datasets.lock.json), a streaming verifier (scripts/fetch_datasets.py), complete license attributions in NOTICE, and original bilingual Apache-2.0 curriculum files under app/mandarin/content/. Running speakon seed-mandarin parses and indexes all four sources cleanly into 9,574 Hanzi characters and 124,818 dictionary entries (112,195 unique CC-CEDICT records merged alongside HSK 1–6 rankings) using batched SQLite ON CONFLICT DO UPDATE upserts.

11-Table Schema & Bilingual Foundations Curriculum#

Migration 0002_phase5_mandarin_studio adds 11 SQLModel tables unified with users.id: HanziCharacter, DictionaryEntry, RadicalComponent, GrammarRule, GradedPassage, NuancePair, MandarinStudyItem, FSRSReviewLog, WritingAttempt, CompositionFeedback, and SentenceAnalysisCache.

Original English and Brazilian Portuguese YAML files seed automatically on boot (32 Kangxi radicals, 19 HSK 1–6 grammar patterns covering 把/被, 了/过/着, and 的/得/地, 8 curated confusable nuance clusters, and 4 graded starter stories alongside the complete "How Mandarin Works" tones, sandhi, stroke-order, and word-order guide).

Offline Linguistics, Sandhi Edge Cases & DTW Strokes#

Every deterministic service under app/mandarin/ operates with zero network calls:

  • Citation Base Tones Before Sandhi (app/mandarin/linguistics.py): While integrating jieba, OpenCC (opencc-python-reimplemented pure-Python universal wheel avoiding C++ CMake hurdles on Python 3.12), and pypinyin, testing caught a real subtle edge case: pypinyin applies phrase-level sandhi dictionaries directly (returning bú for 不是), which masked the underlying citation 4th tone of 不 and 一. Forcing citation base tones before applying third-tone (3+3 -> 2+3), 不, and 一 rules guarantees exact written-vs-spoken tone diffs.
  • Top-Down Geometric Stroke Normalization (app/mandarin/strokes.py): Make Me a Hanzi vector medians reside in upward Y font space ([0, 1024]). Flipping Y (900 - y_raw), normalizing into aspect-preserving [0, 1] coordinates, and resampling onto 16 equidistant arc-length points aligns dataset reference medians cleanly with touch canvases for Dynamic Time Warping (DTW) freehand matching and direction validation.

Cached Ollama AI Engines & HSK Vocabulary Gate#

Extending OllamaLLMProvider.chat_json with schema validation and a single JSON repair retry powers four local AI workbenches (qwen3.5:9b deep reasoning or fast hints via llama3.1:latest, all trust_env=False): Sentence Dissector, Nuance Comparator (short-circuiting to curated NuancePair entries before calling Ollama), Composition Coach, and HSK Graded Story Generator. Stories deterministically measure out_of_level_ratio against HSK <= target vocabulary and retry with explicit out-of-level character feedback until out_of_level_ratio <= 0.05.

Deterministic fsrs 6.x Replay & <= 5 MB SQLite Offline Packs#

Because fsrs 6.3.4 computes memory stability purely over review events (Scheduler without State.New or embedded reps/lapses fields), app/mandarin/fsrs_service.py enforces deterministic state reconstruction: fixing Card(card_id=1) and Scheduler(enable_fuzzing=False), sorting append-only FSRSReviewLog entries by (reviewed_at, id), and replaying every rating in UTC order. Client batches synced via POST /api/mandarin/sync deduplicate idempotently on client UUID primary keys.

Finally, scripts/build_starter_pack.py exports vacuumed, PRAGMA integrity_check-verified standalone SQLite bundles served with strong SHA-256 ETag (304 Not Modified) headers:

  • Starter HSK 1–2 Pack: 2,822,144 bytes (2.69 MiB) (486 Hanzi characters, 1,084 dictionary rows), fitting comfortably inside mobile app bundle limits (<= 5 MB).
  • Full Offline Pack: 105,574,400 bytes (100.68 MiB) across all 9,574 characters and 124,818 dictionary entries.

Verification & Clean Public CI#

ruff check, ruff format --check, strict mypy app across 62 files, export_openapi.py --check, uvx pip-audit (0 vulnerabilities), Hypothesis property tests (FSRS invariants, OpenCC round-trips), and 42 / 42 CPU tests all passed—followed by green CI (47451381599) and Gitleaks Secret Scan (47451381623) runs on Celio1878/speakon-services (3498bcb).

Next up in Phase 6: surfacing the full Mandarin Studio experience across the React Router 7 web workspace (aldeon/app) and Expo Skia/SQLite mobile screens (speakon-mobile).

Célio Vieira

Célio Vieira

Founder & Architect

Engineering applied AI systems, distributed cloud platforms, and the Aldeon umbrella venture ecosystem.

Related Technical Dispatches

View all 90