diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000000000000000000000000000000000000..8d938937da018a1f43284a296a51db062858179f
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,5 @@
+VoxPreference-frontend/node_modules
+VoxPreference-frontend/dist
+backend/data
+**/__pycache__
+.git
diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index c67d716f560b5519e4cd334ff27cccba0d52a146..0000000000000000000000000000000000000000
--- a/.gitignore
+++ /dev/null
@@ -1,4 +0,0 @@
-data/SpeechFiles
-dev_notes.txt
-.venv
-.DS_STORE
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
index ad4fd3eddfe14c155fe8abef8ecc2ff20990f428..07b85324040099e1809b9b64a61e4b74e24705dd 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,19 +1,27 @@
-FROM python:3.10.9
-
-RUN apt-get update && apt-get install -y espeak && rm -rf /var/lib/apt/lists/*
-
-RUN mkdir -p /app/hf_home && chmod -R 777 /app/hf_home
-
-RUN mkdir -p /app/numba_cache && chmod -R 777 /app/numba_cache
-
-COPY . .
-
-WORKDIR /
-
-ENV HF_HOME=/app/hf_home
-
-ENV NUMBA_CACHE_DIR=/app/numba_cache
-
-RUN pip install --no-cache-dir --upgrade -r /requirements.txt
-
+# One image for the whole app: the React frontend is built, then served by the FastAPI backend.
+# Works as a Hugging Face Space (sdk: docker, port 7860) or anywhere Docker runs. Needs about 3 GB of RAM.
+
+FROM node:22-slim AS frontend
+WORKDIR /frontend
+COPY VoxPreference-frontend/package.json VoxPreference-frontend/package-lock.json ./
+RUN npm ci
+COPY VoxPreference-frontend/ ./
+RUN npm run build
+
+FROM python:3.12-slim
+RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg espeak-ng && rm -rf /var/lib/apt/lists/*
+WORKDIR /app/backend
+# the same pins the pipeline was tested with; CPU-only PyTorch keeps the image small
+COPY backend/requirements-tested.txt ./
+RUN pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu -r requirements-tested.txt
+COPY backend/ ./
+COPY --from=frontend /frontend/dist /app/VoxPreference-frontend/dist
+# lexicons and models are fetched at build time so the first analysis does not wait for downloads
+ENV HF_HOME=/app/hf
+RUN python -m pg.kb.fetch && python -c "from pg.phones import PhoneModel; from pg.align import WordAligner; from pg.diarize import Diarizer; from huggingface_hub import snapshot_download; from pg.asr import ASR_MODEL; PhoneModel(); WordAligner(); Diarizer(); snapshot_download(ASR_MODEL, allow_patterns=['*.json', '*.txt', 'model.safetensors'])"
+# Hugging Face runs the container as user 1000: let it write its caches (transcripts, speaker turns)
+RUN mkdir -p /app/backend/data/cache && chmod -R a+rwX /app/backend/data /app/hf
+# load the models in the background as soon as the server starts
+ENV PG_WARM=1
+EXPOSE 7860
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
diff --git a/README.md b/README.md
index 475cab620538b4247b2948baf17f398c7a4adbf2..b3c27c512cb6441e61e45c376eda8eae745a9e1a 100644
--- a/README.md
+++ b/README.md
@@ -1,256 +1,19 @@
---
-title: Voxpreference
-emoji: 📈
+title: VoxPreference
+emoji: 🗣️
colorFrom: indigo
colorTo: gray
sdk: docker
+app_port: 7860
pinned: false
-short_description: speech recognition using nigerian english
+short_description: Preference Grammar analysis of Nigerian English speech
---
+# VoxPreference
-Read file: README.md
-
-Search files...
-Here is an extremely detailed `README.md` for your project, covering all aspects from what it does, how to use it, deployment, API, and more:
-
----
-
-# Voxpreference 📈
-
-**Speech Recognition and IPA Transcription for Nigerian English**
-
----
-
-## Table of Contents
-
-- [Project Overview](#project-overview)
-- [Features](#features)
-- [Architecture](#architecture)
-- [Demo](#demo)
-- [Quickstart](#quickstart)
- - [Running Locally (Docker)](#running-locally-docker)
- - [Running on Hugging Face Spaces](#running-on-hugging-face-spaces)
-- [API Reference](#api-reference)
- - [Root Endpoint `/`](#root-endpoint-)
- - [Health Endpoint `/health`](#health-endpoint-health)
- - [Transcription Endpoint `/` (POST)](#transcription-endpoint--post)
-- [Environment Variables](#environment-variables)
-- [Logging](#logging)
-- [Cache and Storage Management](#cache-and-storage-management)
-- [Development](#development)
-- [Finetuning the Model](#finetuning-the-model)
-- [Troubleshooting](#troubleshooting)
-- [License](#license)
-- [Acknowledgements](#acknowledgements)
-
----
-
-## Project Overview
-
-**Voxpreference** is a FastAPI-based web service for automatic speech recognition (ASR) and International Phonetic Alphabet (IPA) transcription, specifically tailored for Nigerian English. It leverages a fine-tuned Wav2Vec2 model and the `phonemizer` library to provide both text and phonetic transcriptions of uploaded audio files.
-
-The project is designed for easy deployment on [Hugging Face Spaces](https://huggingface.co/spaces) and in Dockerized environments.
-
----
-
-## Features
-
-- **Speech-to-Text**: Transcribes Nigerian English audio to text using a custom Wav2Vec2 model.
-- **IPA Transcription**: Converts recognized text to IPA using `phonemizer`.
-- **REST API**: Simple endpoints for health check and transcription.
-- **Production-Grade Logging**: Extensive logging for debugging and monitoring.
-- **Cache Management**: Configurable cache directories for model and Hugging Face data.
-- **Docker & Hugging Face Spaces Ready**: Optimized for containerized and cloud deployment.
-
----
-
-## Architecture
-
-- **FastAPI**: Web framework for serving the API.
-- **Wav2Vec2**: Transformer-based ASR model, fine-tuned for Nigerian English.
-- **Phonemizer**: Converts text to IPA.
-- **Docker**: Containerization for reproducible deployment.
-- **Hugging Face Spaces**: Cloud hosting for public demos.
-
----
-
-## Demo
-
-> **Live Demo:** [Hugging Face Spaces - Voxpreference](https://huggingface.co/spaces/thebickersteth/voxpreference)
-
----
-
-## Quickstart
-
-### Running Locally (Docker)
-
-1. **Clone the repository:**
- ```bash
- git clone https://huggingface.co/spaces/thebickersteth/voxpreference
- cd voxpreference
- ```
-
-2. **Build the Docker image:**
- ```bash
- docker build -t voxpreference .
- ```
-
-3. **Run the container:**
- ```bash
- docker run -p 7860:7860 voxpreference
- ```
-
-4. **Access the API:**
- - Open [http://localhost:7860](http://localhost:7860) in your browser or use `curl`/Postman.
-
-### Running on Hugging Face Spaces
-
-1. **Push your repository to Hugging Face Spaces** (with `sdk: docker` in your README).
-2. **Spaces will automatically build and run your Dockerfile.**
-3. **Access your app via the provided URL.**
-
----
-
-## API Reference
-
-### Root Endpoint `/`
-
-- **Method:** `GET`
-- **Description:** Welcome message and basic info.
-- **Response:**
- ```json
- {
- "message": "Welcome! This API is for transcription. Try /health or /transcribe."
- }
- ```
-
-### Health Endpoint `/health`
-
-- **Method:** `GET`
-- **Description:** Health check for monitoring.
-- **Response:**
- ```json
- {
- "status": "ok"
- }
- ```
-
-### Transcription Endpoint `/` (POST)
-
-- **Method:** `POST`
-- **Description:** Upload an audio file (WAV/MP3) and receive transcription and IPA.
-- **Request:**
- - **Form field:** `audioFile` (file upload)
-- **Response:**
- ```json
- {
- "success": true,
- "transcription": "recognized text",
- "ipa": "ˌɪn.təˈnæʃ.ə.nəl fəˈnɛ.tɪk ˈælfəˌbɛt",
- "ipa_error": null
- }
- ```
- - If an error occurs:
- ```json
- {
- "success": false,
- "error": "Error message"
- }
- ```
-
-#### Example `curl` Request
-
-```bash
-curl -X POST "http://localhost:7860/" \
- -F "audioFile=@/path/to/your/audio.wav"
-```
-
----
-
-## Environment Variables
-
-- `LOG_LEVEL`: Set the logging level (`DEBUG`, `INFO`, `WARNING`, `ERROR`). Default: `INFO`.
-- `HF_HOME`: Path for Hugging Face cache (default: `/app/hf_home`).
-- `TRANSFORMERS_CACHE`: Path for Transformers model cache (default: `/app/cache`).
-- `NUMBA_CACHE_DIR`: Path for Numba cache (default: `/app/numba_cache`).
-
----
-
-## Logging
-
-- Logs are output to stdout (visible in Docker logs and Hugging Face Spaces).
-- Log format:
- `YYYY-MM-DD HH:MM:SS | LEVEL | voxpreference.app | message`
-- All requests, responses, and errors are logged.
-- Set `LOG_LEVEL=DEBUG` for verbose output.
-
----
-
-## Cache and Storage Management
-
-- **No audio files are saved to disk**; all processing is in-memory.
-- Model and Hugging Face caches are stored in `/app/hf_home` and `/app/cache`.
-- On startup, cache directories can be cleaned to avoid storage bloat (see `app.py` for details).
-- **Tip:** Monitor disk usage on Hugging Face Spaces to avoid exceeding quotas.
-
----
-
-## Development
-
-### Requirements
-
-- Python 3.9+
-- See `requirements.txt` for dependencies.
-
-### Local Development (without Docker)
-
-1. **Create a virtual environment:**
- ```bash
- python3 -m venv .venv
- source .venv/bin/activate
- ```
-
-2. **Install dependencies:**
- ```bash
- pip install -r requirements.txt
- ```
-
-3. **Run the app:**
- ```bash
- uvicorn app:app --host 0.0.0.0 --port 7860
- ```
-
----
-
-## Finetuning the Model
-
-- See `finetune_model.py` for scripts and instructions to finetune the Wav2Vec2 model on your own Nigerian English dataset.
-- Training data should be in CSV format with columns for audio file paths and transcripts.
-- The script uses Hugging Face `datasets` and `transformers` libraries.
-V
----
-
-## Troubleshooting
-
-- **Model Download Issues:** Ensure your Hugging Face token (if needed) is set up and the model is public.
-- **Out of Disk Space:** Clean up `/app/hf_home` and `/app/cache` or increase your Hugging Face Space storage.
-- **Audio Format Errors:** Only WAV/MP3 files with 16kHz sample rate are supported.
-- **Performance:** For large files or high concurrency, consider scaling or optimizing the Docker resource limits.
-
----
-
-## License
-
-This project is licensed under the MIT License. See [LICENSE](LICENSE) for details.
-
----
-
-## Acknowledgements
-
-- [Hugging Face](https://huggingface.co/) for model hosting and Spaces.
-- [FastAPI](https://fastapi.tiangolo.com/) for the web framework.
-- [Transformers](https://github.com/huggingface/transformers) for the ASR model.
-- [Phonemizer](https://github.com/bootphon/phonemizer) for IPA conversion.
-- Nigerian English speech community for data and inspiration.
+Automates Prof. C.U.C. Ugorji's Preference Grammar for Nigerian English: give target words, recordings
+(single words, voice notes or whole podcasts) and a ranking of the six tenets; the app hears how each speaker
+pronounced the sound, counts the variants, and returns the operability table and the preferred pronunciation.
+Source and documentation: https://github.com/Oluwademiladeogo/VoxPreference (see backend/pg/README.md).
+Runs on free CPU hardware: short clips take about a minute; a long podcast takes much longer.
diff --git a/VoxPreference-frontend/.gitignore b/VoxPreference-frontend/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..1cac5597ea2f6d8340c6b356fb4e159c562f4a50
--- /dev/null
+++ b/VoxPreference-frontend/.gitignore
@@ -0,0 +1,25 @@
+# Logs
+logs
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+pnpm-debug.log*
+lerna-debug.log*
+
+node_modules
+dist
+dist-ssr
+*.local
+
+# Editor directories and files
+.vscode/*
+!.vscode/extensions.json
+.idea
+.DS_Store
+*.suo
+*.ntvs*
+*.njsproj
+*.sln
+*.sw?
+.env
\ No newline at end of file
diff --git a/VoxPreference-frontend/.impeccable/hook.cache.json b/VoxPreference-frontend/.impeccable/hook.cache.json
new file mode 100644
index 0000000000000000000000000000000000000000..d920f723672a7159c69622d5d9a5a58fc2f82cdd
--- /dev/null
+++ b/VoxPreference-frontend/.impeccable/hook.cache.json
@@ -0,0 +1 @@
+{"version":1,"sessions":{"84090a19-6eb2-42c5-be8c-3fa48c970d73":{"updatedAt":1792464511767,"files":{"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/components/pg/RecordingsInput.tsx":{"editCount":9,"findings":["gray-on-color:431"]},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/components/pg/AdvancedSettings.tsx":{"editCount":7,"findings":[],"cleanAcked":true},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/components/pg/UnitSummary.tsx":{"editCount":2,"findings":[],"cleanAcked":true},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/components/pg/OperabilityTable.tsx":{"editCount":10,"findings":[],"cleanAcked":true},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/components/pg/CandidateShares.tsx":{"editCount":1,"findings":[],"cleanAcked":true},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/components/pg/ClusterSummary.tsx":{"editCount":3,"findings":[],"cleanAcked":true},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/types/pg.ts":{"editCount":7,"findings":[]},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/components/pg/TokensTable.tsx":{"editCount":6,"findings":[],"cleanAcked":true},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/components/pg/AnalysisProgress.tsx":{"editCount":3,"findings":[],"cleanAcked":true},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/components/pg/AnalysisResults.tsx":{"editCount":4,"findings":[],"cleanAcked":true},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/components/PGAnalysis.tsx":{"editCount":14,"findings":[],"cleanAcked":true},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/utils/pg.ts":{"editCount":6,"findings":[]},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/components/pg/RankingEditor.tsx":{"editCount":7,"findings":[],"cleanAcked":true},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/hooks/useClipPlayer.ts":{"editCount":1,"findings":[]},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/components/pg/TierBadge.tsx":{"editCount":1,"findings":[],"cleanAcked":true},"/Users/demilade/Documents/VoxPreference/VoxPreference-frontend/src/components/pg/ValidationBadge.tsx":{"editCount":1,"findings":[],"cleanAcked":true}}}}}
\ No newline at end of file
diff --git a/VoxPreference-frontend/README.md b/VoxPreference-frontend/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..40ede56ea6e14587985fbe9b74c121cfcc7a9aa7
--- /dev/null
+++ b/VoxPreference-frontend/README.md
@@ -0,0 +1,54 @@
+# React + TypeScript + Vite
+
+This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
+
+Currently, two official plugins are available:
+
+- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
+- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
+
+## Expanding the ESLint configuration
+
+If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
+
+```js
+export default tseslint.config({
+ extends: [
+ // Remove ...tseslint.configs.recommended and replace with this
+ ...tseslint.configs.recommendedTypeChecked,
+ // Alternatively, use this for stricter rules
+ ...tseslint.configs.strictTypeChecked,
+ // Optionally, add this for stylistic rules
+ ...tseslint.configs.stylisticTypeChecked,
+ ],
+ languageOptions: {
+ // other options...
+ parserOptions: {
+ project: ['./tsconfig.node.json', './tsconfig.app.json'],
+ tsconfigRootDir: import.meta.dirname,
+ },
+ },
+})
+```
+
+You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
+
+```js
+// eslint.config.js
+import reactX from 'eslint-plugin-react-x'
+import reactDom from 'eslint-plugin-react-dom'
+
+export default tseslint.config({
+ plugins: {
+ // Add the react-x and react-dom plugins
+ 'react-x': reactX,
+ 'react-dom': reactDom,
+ },
+ rules: {
+ // other rules...
+ // Enable its recommended typescript rules
+ ...reactX.configs['recommended-typescript'].rules,
+ ...reactDom.configs.recommended.rules,
+ },
+})
+```
diff --git a/VoxPreference-frontend/eslint.config.js b/VoxPreference-frontend/eslint.config.js
new file mode 100644
index 0000000000000000000000000000000000000000..092408a9f09eae19150818b4f0db5d1b70744828
--- /dev/null
+++ b/VoxPreference-frontend/eslint.config.js
@@ -0,0 +1,28 @@
+import js from '@eslint/js'
+import globals from 'globals'
+import reactHooks from 'eslint-plugin-react-hooks'
+import reactRefresh from 'eslint-plugin-react-refresh'
+import tseslint from 'typescript-eslint'
+
+export default tseslint.config(
+ { ignores: ['dist'] },
+ {
+ extends: [js.configs.recommended, ...tseslint.configs.recommended],
+ files: ['**/*.{ts,tsx}'],
+ languageOptions: {
+ ecmaVersion: 2020,
+ globals: globals.browser,
+ },
+ plugins: {
+ 'react-hooks': reactHooks,
+ 'react-refresh': reactRefresh,
+ },
+ rules: {
+ ...reactHooks.configs.recommended.rules,
+ 'react-refresh/only-export-components': [
+ 'warn',
+ { allowConstantExport: true },
+ ],
+ },
+ },
+)
diff --git a/VoxPreference-frontend/index.html b/VoxPreference-frontend/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..22fac502238abb61f69b6b4bf8a36a88ae757ad7
--- /dev/null
+++ b/VoxPreference-frontend/index.html
@@ -0,0 +1,13 @@
+
+
+
+ Legacy view: it uses the old wav2vec2 model and dictionary IPA, which
+ shows how words are spelled in a dictionary, not how they were
+ pronounced.
+
+ );
+};
+
+export default Modal;
diff --git a/VoxPreference-frontend/src/components/PGAnalysis.tsx b/VoxPreference-frontend/src/components/PGAnalysis.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..9c662f92cea9142a39287263271b6cad8077c825
--- /dev/null
+++ b/VoxPreference-frontend/src/components/PGAnalysis.tsx
@@ -0,0 +1,494 @@
+import { FormEvent, useEffect, useRef, useState } from "react";
+import { API_CONFIG } from "../config/api";
+import ApiService from "../services/api";
+import {
+ AnalysisOutcome,
+ OverrideRow,
+ PGUnit,
+ PGUnitsResponse,
+ RankingItem,
+ RecordingItem,
+ SettingsForm,
+} from "../types/pg";
+import {
+ DEFAULT_RANKING,
+ DEFAULT_SETTINGS,
+ PG_TENETS,
+ buildSettings,
+ formatRanking,
+ isAutoTranscript,
+ isValidated,
+ nextId,
+ parseWords,
+ rankingItemsFrom,
+ rankingStrata,
+ validationLabel,
+} from "../utils/pg";
+import AdvancedSettings from "./pg/AdvancedSettings";
+import AnalysisProgress from "./pg/AnalysisProgress";
+import AnalysisResults from "./pg/AnalysisResults";
+import Icon from "./pg/Icon";
+import RankingEditor from "./pg/RankingEditor";
+import RecordingsInput from "./pg/RecordingsInput";
+import UnitSummary from "./pg/UnitSummary";
+
+interface ErrorState {
+ message: string;
+ type: "validation" | "analysis" | "cancelled";
+}
+
+interface RunState {
+ startedAt: number;
+ files: number;
+ words: string[];
+ unscripted: boolean;
+}
+
+const unitOptionLabel = (unit: PGUnit) =>
+ `${
+ unit.label === unit.key
+ ? `${unit.key} · /${unit.phoneme}/`
+ : `${unit.key} · ${unit.label} /${unit.phoneme}/`
+ } · ${validationLabel(unit)}`;
+
+const inputClass =
+ "w-full px-4 py-3 border border-gray-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-transparent";
+const sectionHeadingClass = "text-xl font-semibold text-gray-900";
+
+const PGAnalysis = () => {
+ const [catalog, setCatalog] = useState(null);
+ const [catalogError, setCatalogError] = useState(null);
+ const [catalogRequest, setCatalogRequest] = useState(0);
+ const [wordsInput, setWordsInput] = useState("");
+ const [unitKey, setUnitKey] = useState("");
+ const [ranking, setRanking] = useState(() =>
+ rankingItemsFrom(DEFAULT_RANKING, PG_TENETS)
+ );
+ const [recordings, setRecordings] = useState([]);
+ const [asr, setAsr] = useState(false);
+ const [diarize, setDiarize] = useState(true);
+ const [numSpeakers, setNumSpeakers] = useState("");
+ const [settings, setSettings] = useState(DEFAULT_SETTINGS);
+ const [overrides, setOverrides] = useState([]);
+ const [error, setError] = useState(null);
+ const [run, setRun] = useState(null);
+ const [outcome, setOutcome] = useState(null);
+ const rankingEdited = useRef(false);
+ const abortRef = useRef(null);
+ const resultsHeadingRef = useRef(null);
+
+ const tenets = catalog?.tenets ?? PG_TENETS;
+ const defaultRanking = catalog?.default_ranking ?? DEFAULT_RANKING;
+ const units = catalog ? Object.values(catalog.units) : [];
+ const selectedUnit = unitKey ? catalog?.units[unitKey] : undefined;
+ const words = parseWords(wordsInput);
+ const unvalidated = !!selectedUnit && !isValidated(selectedUnit);
+ // A variant can be any IPA phone, so overrides also suggest those heard in the last run
+ const lastRun =
+ outcome && (!unitKey || outcome.data.unit.key === unitKey)
+ ? outcome.data
+ : null;
+ const overrideVariants = Array.from(
+ new Set([
+ ...(selectedUnit?.candidates ?? lastRun?.unit.candidates ?? []),
+ ...(lastRun?.tokens.map((token) => token.variant) ?? []),
+ ])
+ );
+
+ useEffect(() => {
+ let ignore = false;
+ ApiService.getPGUnits()
+ .then((data) => {
+ if (ignore) return;
+ setCatalog(data);
+ setCatalogError(null);
+ // Use the server's default ranking unless the user has already edited it
+ if (!rankingEdited.current) {
+ setRanking(rankingItemsFrom(data.default_ranking, data.tenets));
+ }
+ })
+ .catch((err) => {
+ if (!ignore) {
+ setCatalogError(
+ err instanceof Error ? err.message : "Unknown error occurred"
+ );
+ }
+ });
+ return () => {
+ ignore = true;
+ };
+ }, [catalogRequest]);
+
+ // Stop waiting for a running analysis if the view goes away
+ useEffect(() => () => abortRef.current?.abort(), []);
+
+ // Bring the new results to the top and move keyboard and screen-reader users there
+ useEffect(() => {
+ const heading = resultsHeadingRef.current;
+ if (!outcome || !heading) return;
+ heading.scrollIntoView({ block: "start" });
+ heading.focus({ preventScroll: true });
+ }, [outcome]);
+
+ const handleRankingChange = (items: RankingItem[]) => {
+ rankingEdited.current = true;
+ setRanking(items);
+ };
+
+ const handleSubmit = async (e: FormEvent) => {
+ e.preventDefault();
+ setError(null);
+
+ if (!words.length) {
+ setError({ message: "Enter at least one target word", type: "validation" });
+ return;
+ }
+ if (!recordings.length) {
+ setError({ message: "Add at least one recording", type: "validation" });
+ return;
+ }
+ const strata = rankingStrata(ranking);
+ if (!strata.length) {
+ setError({
+ message: "Keep at least one tenet in the ranking",
+ type: "validation",
+ });
+ return;
+ }
+ const built = buildSettings(settings, overrides);
+ if (built.error !== null) {
+ setError({ message: built.error, type: "validation" });
+ return;
+ }
+
+ const formData = new FormData();
+ recordings.forEach((item) => formData.append("files", item.file));
+ formData.append("words", words.join(","));
+ if (unitKey) formData.append("unit", unitKey);
+ formData.append("ranking", formatRanking(strata));
+ // Transcripts and speakers are keyed by file name
+ const transcripts = Object.fromEntries(
+ recordings
+ .filter((item) => item.transcript.trim())
+ .map((item) => [item.file.name, item.transcript.trim()])
+ );
+ if (Object.keys(transcripts).length) {
+ formData.append("transcripts", JSON.stringify(transcripts));
+ }
+ const speakers = Object.fromEntries(
+ recordings
+ .filter((item) => item.speaker.trim())
+ .map((item) => [item.file.name, item.speaker.trim()])
+ );
+ if (Object.keys(speakers).length) {
+ formData.append("speakers", JSON.stringify(speakers));
+ }
+ if (Object.keys(built.settings).length) {
+ formData.append("settings", JSON.stringify(built.settings));
+ }
+ formData.append("asr", asr ? "true" : "false");
+ formData.append("diarize", diarize ? "true" : "false");
+ const speakerCount = Number.parseInt(numSpeakers, 10);
+ if (diarize && speakerCount >= 1 && speakerCount <= 20) {
+ formData.append("num_speakers", String(speakerCount));
+ }
+
+ const controller = new AbortController();
+ abortRef.current = controller;
+ setRun({
+ startedAt: Date.now(),
+ files: recordings.length,
+ words,
+ unscripted:
+ recordings.some((item) => isAutoTranscript(item.transcript)) ||
+ (asr && recordings.some((item) => !item.transcript.trim())),
+ });
+
+ try {
+ const data = await ApiService.analyzePG(formData, controller.signal);
+ setOutcome({
+ id: nextId("analysis"),
+ data,
+ files: new Map(recordings.map((item) => [item.file.name, item.file])),
+ settings: built.values,
+ unlabelledRecordings: recordings.length - Object.keys(speakers).length,
+ });
+ } catch (err) {
+ console.error("Error:", err);
+ if (controller.signal.aborted) {
+ setError({
+ message:
+ "Analysis cancelled. The server may still finish the job, but its results will not be shown.",
+ type: "cancelled",
+ });
+ } else if (err instanceof TypeError) {
+ setError({
+ message:
+ "Could not reach the analysis server. Check that the backend is running and try again.",
+ type: "analysis",
+ });
+ } else if (err instanceof Error && err.message.startsWith("Request timed out")) {
+ setError({
+ message: `The analysis took longer than ${
+ API_CONFIG.PG_ANALYZE_TIMEOUT / 60000
+ } minutes, so the app stopped waiting. Try fewer recordings at a time.`,
+ type: "analysis",
+ });
+ } else {
+ setError({
+ message: err instanceof Error ? err.message : "Unknown error occurred",
+ type: "analysis",
+ });
+ }
+ } finally {
+ abortRef.current = null;
+ setRun(null);
+ }
+ };
+
+ return (
+ // relative: absolutely positioned descendants (sr-only text) must scroll and clip
+ // inside this container instead of stretching the whole page
+
+
+
+
+ Preference Grammar analysis
+
+
+ Preference Grammar (C.U.C. Ugorji) standardises pronunciation in
+ New Englishes such as Nigerian English. Recordings of target words
+ from many speakers show which variants of a sound people actually
+ produce; the variants are then ranked on six tenets to choose the
+ preferred pronunciation.
+
+
+
+ How the analysis works
+
+
+
+ The server finds each target word in the recordings and decides
+ which variant of the sound each speaker produced, e.g. <th>
+ in “think” as [θ],{" "}
+ [t] or{" "}
+ [s].
+
+
+ The attested variants become candidates and receive violation
+ marks for International acceptance (I-Ac), Contrastiveness
+ (ContR), Frequency (FreQ), Disambiguity (DisaM), Phonetic
+ simplicity (Pho-S) and Pedagogic convenience (Ped-C).
+
+
+ The operability table checks the candidates tenet by tenet in
+ your ranking. A candidate drops out at its first fatal mark,
+ and the one left standing is the preferred pronunciation.
+
+ How variant shares are worked out for FreQ and Ped-C. Counting
+ speakers equally stops a few talkative speakers from deciding
+ the result. Default: count every token.
+
+
+
+
+
+
+ With “only the most frequent variant”, ranking FreQ first makes
+ the commonest pronunciation the preferred one. The threshold
+ reading is the one that reproduces Ugorji's published “think”
+ table.
+
+
+ {OTHER_FIELDS.map(numberField)}
+
+
+
+
+
+ Corrects the classifier's known biases with offsets fitted on
+ human-labelled tokens. Untick to see the uncorrected labels.
+ Default: on.
+
+
+
+
+
+
+
+
+ );
+};
+
+export default AdvancedSettings;
diff --git a/VoxPreference-frontend/src/components/pg/AnalysisProgress.tsx b/VoxPreference-frontend/src/components/pg/AnalysisProgress.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..b2d86ce089ecad19614015255a687486704b2b59
--- /dev/null
+++ b/VoxPreference-frontend/src/components/pg/AnalysisProgress.tsx
@@ -0,0 +1,89 @@
+import { useEffect, useState } from "react";
+import { formatDuration } from "../../utils/pg";
+
+interface AnalysisProgressProps {
+ startedAt: number;
+ files: number;
+ words: string[];
+ unscripted: boolean; // some files are transcribed by speech recognition first
+ onCancel: () => void;
+}
+
+// The server sends no progress events, so show what is happening and for how long
+const AnalysisProgress = ({
+ startedAt,
+ files,
+ words,
+ unscripted,
+ onCancel,
+}: AnalysisProgressProps) => {
+ const [now, setNow] = useState(() => Date.now());
+
+ useEffect(() => {
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(timer);
+ }, []);
+
+ return (
+
+ The server is locating each word, scoring every candidate variant
+ and building the operability table. This can take several minutes
+ on a CPU, and longer the first time while the phone model loads.
+ {unscripted &&
+ " Unscripted audio is transcribed by speech recognition first, which takes longer still."}{" "}
+ You can switch to the chat in the meantime.
+
+ {unlabelledRecordings === files.size
+ ? "No speaker ids were given, so each recording counts as a separate speaker."
+ : `${unlabelledRecordings} recording${
+ unlabelledRecordings === 1 ? "" : "s"
+ } without a speaker id count${
+ unlabelledRecordings === 1 ? "s" : ""
+ } as separate speakers.`}
+
+ Not stable: the preferred form depends on which
+ speakers are included — collect more speakers or check the
+ low-confidence tokens.
+
+
+ )}
+
+ {tableau?.tie && (
+
+
+
+ Tie. {data.preferred.length} candidates survive
+ every tenet in this ranking. Restore or re-rank a tenet that
+ separates them, or add an expert override, then run the analysis
+ again.
+
+
+ )}
+
+
+ {data.warnings.length > 0 && (
+
+
+
+ Warnings
+
+
+ {data.warnings.map((warning, i) => (
+
{warning}
+ ))}
+
+
+ )}
+
+ {tableau && (
+
+
+
Operability table
+
+
+
+ {otStyle
+ ? "Each candidate is checked against the tenets from left to right in your ranking. It drops out at its first fatal mark (!), its later cells are shaded, and ☞ marks the candidate left standing."
+ : "Every violation mark of each candidate, with the tenets in your ranking from left to right, as in Ugorji's published PG tables. ⇒ marks the preferred form."}{" "}
+ Select a cell to see the evidence behind its marks.
+
+
+
+ )}
+
+ {data.candidates.length > 0 && (
+
+
Attested variants
+
+
+ )}
+
+ {data.tokens.length > 0 && (
+
+
+
+ )}
+
+ {data.clusters && (
+ // Collapsed by default: the clusters are exploratory, not evidence for the result
+
+
+
+ Acoustic clusters (exploratory)
+
+
+ These groupings barely separate the variants; they are shown for
+ exploration, not as evidence.
+
+
+
+
+
+
+ )}
+
+
+
Downloads
+
+ Tables as CSV, the report as HTML, and the whole analysis as JSON.
+
+
+ );
+};
+
+export default AnalysisResults;
diff --git a/VoxPreference-frontend/src/components/pg/CandidateShares.tsx b/VoxPreference-frontend/src/components/pg/CandidateShares.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..0cb7979f5022c9a271d3ab69ba98ca109aa4498a
--- /dev/null
+++ b/VoxPreference-frontend/src/components/pg/CandidateShares.tsx
@@ -0,0 +1,119 @@
+import { PGCandidate, PGVariantCount, SettingsValues } from "../../types/pg";
+import { formatPercent } from "../../utils/pg";
+import TierBadge from "./TierBadge";
+
+interface CandidateSharesProps {
+ candidates: PGCandidate[];
+ superfluous: PGVariantCount[];
+ preferred: string[];
+ totalTokens: number;
+ settings: SettingsValues;
+}
+
+// Emphasis: the preferred form in the accent colour, the other variants in gray
+const CandidateShares = ({
+ candidates,
+ superfluous,
+ preferred,
+ totalTokens,
+ settings,
+}: CandidateSharesProps) => {
+ const threshold = Math.min(Math.max(settings.freq_threshold, 0), 1) * 100;
+ const hasTiers = candidates.some((candidate) => candidate.tier);
+
+ return (
+
+
+ {settings.freq_weighting === "speakers"
+ ? `Each variant's share of the speakers' usage, with every speaker counting equally (${totalTokens} tokens).`
+ : `Share of the ${totalTokens} token${totalTokens === 1 ? "" : "s"} realised with each variant.`}{" "}
+ The vertical rule marks the FreQ threshold (
+ {formatPercent(settings.freq_threshold)}): variants below it get *No
+ FreQ.
+
+ Tiers: the formal standard is the preferred form; an allophone loses
+ but meets I-Ac and ContR, so it stays in the formal inventory; other
+ variants belong to the outer (informal) norm.
+
+ )}
+
+ {superfluous.length > 0 && (
+
+
+ Also attested (too rare to compete)
+
+
+ A variant needs at least {settings.min_tokens} token
+ {settings.min_tokens === 1 ? "" : "s"} from{" "}
+ {settings.min_speakers} speaker
+ {settings.min_speakers === 1 ? "" : "s"} to compete.
+
+ Tokens are grouped by the variant they realise, then split by acoustic
+ similarity into sub-clusters: t.1{" "}
+ is the core of [t], higher numbers are sub-variants or outliers.
+ Separation is the mean silhouette (−1 to 1); higher means the variant
+ sounds more distinct from the others.
+
+ Cosine similarity between the average sound of each pair of
+ variants: 1 means identical, lower values mean the variants are
+ acoustically distinct.
+
+
+
+
+ Cosine similarity between variant centroids
+
+
+
+
+ {categories.map((category) => (
+
+ [{category}]
+
+ ))}
+
+
+
+ {categories.map((rowCategory, i) => (
+
+
+ [{rowCategory}]
+
+ {categories.map((columnCategory, j) => {
+ const value = contrast_matrix[i]?.[j] ?? 0;
+ const label = `[${rowCategory}] and [${columnCategory}]: ${value.toFixed(
+ 2
+ )}`;
+ // Self-similarity is always 1, so the diagonal stays neutral
+ if (i === j) {
+ return (
+
+ );
+};
+
+export default OperabilityTable;
diff --git a/VoxPreference-frontend/src/components/pg/RankingEditor.tsx b/VoxPreference-frontend/src/components/pg/RankingEditor.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..28ed2c00bbecbf1591002c1f5e2b4d3d78ff955b
--- /dev/null
+++ b/VoxPreference-frontend/src/components/pg/RankingEditor.tsx
@@ -0,0 +1,222 @@
+import { useEffect, useRef, useState } from "react";
+import { PGTenet, RankingItem } from "../../types/pg";
+import {
+ formatRanking,
+ moveRankingItem,
+ rankingItemsFrom,
+ rankingStrata,
+} from "../../utils/pg";
+import Icon from "./Icon";
+
+interface RankingEditorProps {
+ items: RankingItem[];
+ onChange: (items: RankingItem[]) => void;
+ tenets: PGTenet[];
+ defaultRanking: string;
+}
+
+const RankingEditor = ({
+ items,
+ onChange,
+ tenets,
+ defaultRanking,
+}: RankingEditorProps) => {
+ const [announcement, setAnnouncement] = useState("");
+ const buttonRefs = useRef(new Map());
+ const pendingFocus = useRef(null);
+
+ // Moving a row re-orders the DOM, so return focus to the button that moved it
+ useEffect(() => {
+ if (pendingFocus.current) {
+ buttonRefs.current.get(pendingFocus.current)?.focus();
+ pendingFocus.current = null;
+ }
+ }, [items]);
+
+ const setButtonRef = (id: string) => (element: HTMLButtonElement | null) => {
+ if (element) {
+ buttonRefs.current.set(id, element);
+ } else {
+ buttonRefs.current.delete(id);
+ }
+ };
+
+ const nameOf = (key: string) =>
+ tenets.find((tenet) => tenet.key === key)?.name ?? key;
+ const strata = rankingStrata(items);
+ const keptCount = items.filter((item) => item.enabled).length;
+
+ // Unranked tenets share their stratum's number
+ const rankOf = new Map();
+ strata.forEach((stratum, i) =>
+ stratum.forEach((key) => rankOf.set(key, i + 1))
+ );
+
+ const move = (index: number, delta: -1 | 1) => {
+ const next = moveRankingItem(items, index, delta);
+ if (!next) return;
+ const moved = items[index];
+ pendingFocus.current = `${moved.key}:${delta < 0 ? "up" : "down"}`;
+ onChange(next);
+ setAnnouncement(
+ `${moved.key} moved to position ${index + delta + 1} of ${items.length}`
+ );
+ };
+
+ const toggleKept = (index: number) => {
+ const item = items[index];
+ onChange(
+ items.map((other, i) =>
+ i === index ? { ...other, enabled: !other.enabled } : other
+ )
+ );
+ setAnnouncement(
+ item.enabled
+ ? `${item.key} deleted from the ranking`
+ : `${item.key} restored to the ranking`
+ );
+ };
+
+ const toggleTie = (index: number) => {
+ onChange(
+ items.map((other, i) =>
+ i === index ? { ...other, tiedWithAbove: !other.tiedWithAbove } : other
+ )
+ );
+ };
+
+ const reset = () => {
+ onChange(rankingItemsFrom(defaultRanking, tenets));
+ setAnnouncement("Ranking reset to the default");
+ };
+
+ // Buttons at either end use aria-disabled rather than disabled, so they keep focus
+ // and a repeated key press does nothing instead of bouncing the tenet back
+ const arrowClass =
+ "p-1.5 rounded border border-gray-300 text-gray-700 hover:bg-gray-100 aria-disabled:opacity-40 aria-disabled:cursor-not-allowed aria-disabled:hover:bg-transparent focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500";
+
+ return (
+
+
+ Higher tenets dominate lower ones: a candidate is out as soon as it has
+ more marks than a rival on the highest tenet where they differ. Untick
+ a tenet to delete it, or make it unranked with the tenet above to pool
+ their marks.
+
+ Files without a transcript are transcribed by speech recognition to
+ find the target words. This is slower. To do this for a single file,
+ type “auto” as its transcript.
+
+
+
+ A podcast has several voices. Each target word is credited to the
+ person who said it, so every speaker counts and the stability check
+ works. Applies to unscripted files with no speaker id; a file given a
+ speaker id counts as that one person.
+
+ {diarize && (
+
+ )}
+
+
+ {words.length > 1 && !asr && (
+
+ With several target words, name each single-word file after its word
+ (e.g. three-s01.wav) or give it a
+ transcript, so the server knows which word it is.
+
+
+ {unmatched
+ ? "No target word in the file name: add a transcript, or the server will skip this file."
+ : "The transcript does not contain a target word, so the server will skip this file."}
+
+ )}
+
+ );
+ })}
+
+
+ )}
+
+ );
+};
+
+export default RecordingsInput;
diff --git a/VoxPreference-frontend/src/components/pg/TierBadge.tsx b/VoxPreference-frontend/src/components/pg/TierBadge.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..85789fb1f76a48046baaf5d5394b495262723b13
--- /dev/null
+++ b/VoxPreference-frontend/src/components/pg/TierBadge.tsx
@@ -0,0 +1,25 @@
+import { tierLabel } from "../../utils/pg";
+
+// From most to least formal; the label, not the colour, carries the meaning
+const TIER_STYLES: Record = {
+ "preferred (formal standard)": "bg-blue-100 text-blue-900",
+ "allophone (formal inventory)": "bg-gray-100 text-gray-800",
+ "outer (informal) norm": "bg-white text-gray-700 ring-1 ring-inset ring-gray-300",
+};
+
+const TierBadge = ({ tier }: { tier?: string }) => {
+ if (!tier) return null;
+ return (
+
+ {tierLabel(tier)}
+ Tier: {tier}
+
+ );
+};
+
+export default TierBadge;
diff --git a/VoxPreference-frontend/src/components/pg/TokensTable.tsx b/VoxPreference-frontend/src/components/pg/TokensTable.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..0580fd6c24f77c39c6b9398174e70b8bbbc155bb
--- /dev/null
+++ b/VoxPreference-frontend/src/components/pg/TokensTable.tsx
@@ -0,0 +1,196 @@
+import { useState } from "react";
+import useClipPlayer from "../../hooks/useClipPlayer";
+import { PGToken } from "../../types/pg";
+import Icon from "./Icon";
+
+interface TokensTableProps {
+ tokens: PGToken[];
+ files: Map;
+ reviewBelow: number;
+}
+
+const otherVariants = (token: PGToken) =>
+ Object.entries(token.scores)
+ .filter(([variant]) => variant !== token.variant)
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 2);
+
+const headerClass =
+ "sticky top-0 z-10 bg-gray-50 border-b border-gray-300 px-3 py-2 text-left font-semibold text-gray-700 whitespace-nowrap";
+const cellClass = "border-b border-gray-200 px-3 py-2";
+
+const TokensTable = ({ tokens, files, reviewBelow }: TokensTableProps) => {
+ const [onlyReview, setOnlyReview] = useState(false);
+ const player = useClipPlayer();
+
+ // Play just the stretch of the recording the token was found in
+ const play = (index: number, token: PGToken) => {
+ const file = files.get(token.recording);
+ if (file) player.play(String(index), file, token.start, token.end);
+ };
+
+ const reviewCount = tokens.filter((token) => token.review).length;
+ const rows = tokens
+ .map((token, index) => ({ token, index }))
+ .filter(({ token }) => !onlyReview || token.review);
+
+ return (
+
+
+
Tokens
+
+
+
+ Each row is one occurrence of the sound. Rows marked “check by ear”
+ have a posterior below {reviewBelow}: the model was unsure which
+ variant it heard, so listen and correct the data if needed.
+
+ Each token is assigned to whichever of these variants fits it best.
+
+
+
+ {unit.notes &&
{unit.notes}
}
+ {unit.sources.length > 0 && (
+
+ Sources: {unit.sources.join("; ")}
+
+ )}
+
+ );
+};
+
+export default UnitSummary;
diff --git a/VoxPreference-frontend/src/components/pg/ValidationBadge.tsx b/VoxPreference-frontend/src/components/pg/ValidationBadge.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..78d3e8b258b620393b53941aa79d90dc6ae40010
--- /dev/null
+++ b/VoxPreference-frontend/src/components/pg/ValidationBadge.tsx
@@ -0,0 +1,23 @@
+import { PGUnit } from "../../types/pg";
+import { isValidated, validationLabel } from "../../utils/pg";
+
+// Whether the classifier's labels for the unit passed a human-labelled test; the label,
+// not the colour, carries the meaning
+const ValidationBadge = ({ unit }: { unit: PGUnit }) => {
+ const validated = isValidated(unit);
+ return (
+
+ Classifier:
+ {validationLabel(unit)}
+
+ );
+};
+
+export default ValidationBadge;
diff --git a/VoxPreference-frontend/src/config/api.ts b/VoxPreference-frontend/src/config/api.ts
new file mode 100644
index 0000000000000000000000000000000000000000..53232dc91f22d2c48c46ad01b606f28868942698
--- /dev/null
+++ b/VoxPreference-frontend/src/config/api.ts
@@ -0,0 +1,23 @@
+// in a production build the backend serves this app, so the API is on the same address
+const API_BASE_URL =
+ import.meta.env.VITE_API_BASE_URL ??
+ (import.meta.env.PROD ? "" : "http://localhost:3000");
+
+export const API_ENDPOINTS = {
+ UPLOAD_AUDIO: `${API_BASE_URL}/transcribe`,
+ PG_UNITS: `${API_BASE_URL}/pg/units`,
+ PG_ANALYZE: `${API_BASE_URL}/pg/analyze`,
+};
+
+export const API_CONFIG = {
+ MAX_FILE_SIZE: 50 * 1024 * 1024, // 50MB
+ SUPPORTED_FILE_TYPES: [
+ "audio/wav",
+ "audio/mpeg",
+ "audio/mp3",
+ "audio/ogg",
+ "audio/flac",
+ ],
+ TIMEOUT: 5 * 60 * 1000, // 5 minutes in milliseconds
+ PG_ANALYZE_TIMEOUT: 30 * 60 * 1000, // 30 minutes: the phone model runs over every recording on CPU
+};
diff --git a/VoxPreference-frontend/src/hooks/useAudioRecorder.ts b/VoxPreference-frontend/src/hooks/useAudioRecorder.ts
new file mode 100644
index 0000000000000000000000000000000000000000..29a0078b6bcb8ba4f1ffb06473cf09247c70cba4
--- /dev/null
+++ b/VoxPreference-frontend/src/hooks/useAudioRecorder.ts
@@ -0,0 +1,126 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+
+type RecorderState = "idle" | "requesting" | "recording";
+
+// Containers in order of preference; Safari only records audio/mp4
+const MIME_TYPES = [
+ "audio/webm;codecs=opus",
+ "audio/webm",
+ "audio/ogg;codecs=opus",
+ "audio/mp4",
+];
+
+export const isRecordingSupported = () =>
+ typeof window !== "undefined" &&
+ typeof MediaRecorder !== "undefined" &&
+ !!navigator.mediaDevices?.getUserMedia;
+
+const useAudioRecorder = (onRecorded: (clip: Blob) => void) => {
+ const [state, setState] = useState("idle");
+ const [elapsed, setElapsed] = useState(0);
+ const [error, setError] = useState(null);
+ const recorderRef = useRef(null);
+ const keepRef = useRef(true);
+ const mountedRef = useRef(false);
+ const onRecordedRef = useRef(onRecorded);
+
+ // Always call the latest callback, which sees the latest form state
+ useEffect(() => {
+ onRecordedRef.current = onRecorded;
+ });
+
+ const start = useCallback(async () => {
+ setError(null);
+ if (!isRecordingSupported()) {
+ setError(
+ "Recording is not available in this browser. It needs microphone support and a secure (https or localhost) connection."
+ );
+ return;
+ }
+
+ setState("requesting");
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ // The permission prompt can outlive the component
+ if (!mountedRef.current) {
+ stream.getTracks().forEach((track) => track.stop());
+ return;
+ }
+ const mimeType = MIME_TYPES.find((type) =>
+ MediaRecorder.isTypeSupported(type)
+ );
+ const recorder = new MediaRecorder(
+ stream,
+ mimeType ? { mimeType } : undefined
+ );
+ const chunks: Blob[] = [];
+
+ recorder.ondataavailable = (event) => {
+ if (event.data.size > 0) chunks.push(event.data);
+ };
+ recorder.onstop = () => {
+ // Release the microphone so the browser stops showing it as in use
+ stream.getTracks().forEach((track) => track.stop());
+ recorderRef.current = null;
+ setState("idle");
+ if (keepRef.current && chunks.length) {
+ onRecordedRef.current(
+ new Blob(chunks, {
+ type: recorder.mimeType || mimeType || "audio/webm",
+ })
+ );
+ }
+ };
+
+ keepRef.current = true;
+ recorderRef.current = recorder;
+ recorder.start();
+ setElapsed(0);
+ setState("recording");
+ } catch (err) {
+ setState("idle");
+ setError(
+ err instanceof DOMException && err.name === "NotAllowedError"
+ ? "Microphone access was blocked. Allow it in your browser's site settings and try again."
+ : `Could not start recording: ${
+ err instanceof Error ? err.message : "unknown error"
+ }`
+ );
+ }
+ }, []);
+
+ const stop = useCallback(() => {
+ recorderRef.current?.stop();
+ }, []);
+
+ const discard = useCallback(() => {
+ keepRef.current = false;
+ recorderRef.current?.stop();
+ }, []);
+
+ useEffect(() => {
+ if (state !== "recording") return;
+ const startedAt = Date.now();
+ const timer = window.setInterval(
+ () => setElapsed((Date.now() - startedAt) / 1000),
+ 250
+ );
+ return () => window.clearInterval(timer);
+ }, [state]);
+
+ // Stop an unfinished recording if the component goes away
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ keepRef.current = false;
+ if (recorderRef.current?.state === "recording") {
+ recorderRef.current.stop();
+ }
+ };
+ }, []);
+
+ return { state, elapsed, error, start, stop, discard };
+};
+
+export default useAudioRecorder;
diff --git a/VoxPreference-frontend/src/hooks/useClipPlayer.ts b/VoxPreference-frontend/src/hooks/useClipPlayer.ts
new file mode 100644
index 0000000000000000000000000000000000000000..613f5814f5c260eb62529aa41d43989991fe8a9a
--- /dev/null
+++ b/VoxPreference-frontend/src/hooks/useClipPlayer.ts
@@ -0,0 +1,60 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+
+// Plays one local clip at a time, optionally only the stretch from start to end (seconds)
+const useClipPlayer = () => {
+ const [playing, setPlaying] = useState(null);
+ const audioRef = useRef(null);
+ const urlRef = useRef(null);
+
+ const stop = useCallback(() => {
+ audioRef.current?.pause();
+ audioRef.current = null;
+ if (urlRef.current) URL.revokeObjectURL(urlRef.current);
+ urlRef.current = null;
+ setPlaying(null);
+ }, []);
+
+ // Release the audio when the component goes away
+ useEffect(() => stop, [stop]);
+
+ const play = useCallback(
+ (id: string, file: File, start = 0, end = Infinity) => {
+ stop();
+ const url = URL.createObjectURL(file);
+ const audio = new Audio(url);
+ urlRef.current = url;
+ audioRef.current = audio;
+
+ const finish = () => {
+ if (audioRef.current === audio) stop();
+ };
+ if (start > 0) {
+ // Before metadata loads this sets the start position; re-apply it once it has
+ audio.currentTime = start;
+ audio.addEventListener(
+ "loadedmetadata",
+ () => {
+ if (Math.abs(audio.currentTime - start) > 0.05) {
+ audio.currentTime = start;
+ }
+ },
+ { once: true }
+ );
+ }
+ if (Number.isFinite(end)) {
+ audio.addEventListener("timeupdate", () => {
+ if (audio.currentTime >= end) finish();
+ });
+ }
+ audio.addEventListener("ended", finish);
+ audio.addEventListener("error", finish);
+ audio.play().catch(finish);
+ setPlaying(id);
+ },
+ [stop]
+ );
+
+ return { playing, play, stop };
+};
+
+export default useClipPlayer;
diff --git a/VoxPreference-frontend/src/index.css b/VoxPreference-frontend/src/index.css
new file mode 100644
index 0000000000000000000000000000000000000000..e03459a07a749c080f3bbe68671fd8d442980cd7
--- /dev/null
+++ b/VoxPreference-frontend/src/index.css
@@ -0,0 +1,18 @@
+@import "tailwindcss";
+
+@theme {
+ /* Faces with full IPA coverage first, then system fonts that cover the common symbols */
+ --font-ipa: "Charis SIL", "Doulos SIL", "Gentium Plus", "Noto Sans",
+ "Segoe UI", "Lucida Grande", "DejaVu Sans", sans-serif;
+
+ --animate-indeterminate: indeterminate 1.6s ease-in-out infinite;
+
+ @keyframes indeterminate {
+ 0% {
+ transform: translateX(-100%);
+ }
+ 100% {
+ transform: translateX(300%);
+ }
+ }
+}
diff --git a/VoxPreference-frontend/src/main.tsx b/VoxPreference-frontend/src/main.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..bef5202a32cbd0632c43de40f6e908532903fd42
--- /dev/null
+++ b/VoxPreference-frontend/src/main.tsx
@@ -0,0 +1,10 @@
+import { StrictMode } from 'react'
+import { createRoot } from 'react-dom/client'
+import './index.css'
+import App from './App.tsx'
+
+createRoot(document.getElementById('root')!).render(
+
+
+ ,
+)
diff --git a/VoxPreference-frontend/src/services/api.ts b/VoxPreference-frontend/src/services/api.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b1256bc86d532581a9bb7989feb37a9f8e00e1a7
--- /dev/null
+++ b/VoxPreference-frontend/src/services/api.ts
@@ -0,0 +1,226 @@
+import { API_ENDPOINTS, API_CONFIG } from "../config/api";
+import { PGAnalysisResult, PGUnitsResponse } from "../types/pg";
+
+interface ApiError extends Error {
+ status?: number;
+ statusText?: string;
+ data?: unknown;
+ isTimeout?: boolean;
+}
+
+class ApiService {
+ // Default timeout of 5 minutes if not specified in API_CONFIG
+ private static readonly DEFAULT_TIMEOUT = 5 * 60 * 1000;
+
+ private static async handleResponse(response: Response) {
+ if (!response.ok) {
+ const error: ApiError = new Error("API request failed");
+ error.status = response.status;
+ error.statusText = response.statusText;
+
+ try {
+ const contentType = response.headers.get("content-type");
+ if (contentType?.includes("application/json")) {
+ const errorData = await response.json();
+ error.data = errorData;
+ error.message =
+ errorData.message || errorData.error || "API request failed";
+ } else {
+ const text = await response.text();
+ if (text.includes(" 0 &&
+ requestTimeout < 3600000
+ ? requestTimeout
+ : this.DEFAULT_TIMEOUT;
+
+ // Let a caller's signal (e.g. a cancel button) abort the request as well
+ const callerSignal = options.signal;
+ const abortFromCaller = () => controller.abort();
+ if (callerSignal?.aborted) {
+ controller.abort();
+ } else {
+ callerSignal?.addEventListener("abort", abortFromCaller);
+ }
+
+ // Create a promise that rejects after the timeout
+ const timeoutPromise = new Promise((_, reject) => {
+ timeoutId = window.setTimeout(() => {
+ const timeoutError: ApiError = new Error(
+ `Request timed out after ${timeout}ms`
+ );
+ timeoutError.isTimeout = true;
+ reject(timeoutError);
+ controller.abort();
+ }, timeout);
+ });
+
+ try {
+ console.log(`Starting request to ${url} with timeout ${timeout}ms`);
+
+ // Race between the fetch and the timeout
+ const response = await Promise.race([
+ fetch(url, {
+ ...options,
+ signal: controller.signal,
+ headers: {
+ ...options.headers,
+ Accept: "application/json",
+ },
+ }),
+ timeoutPromise,
+ ]);
+
+ console.log(`Received response from ${url}`);
+ return this.handleResponse(response);
+ } catch (error) {
+ console.error("Request failed:", {
+ url,
+ timeout,
+ error:
+ error instanceof Error
+ ? {
+ name: error.name,
+ message: error.message,
+ isTimeout: (error as ApiError).isTimeout,
+ isAbortError:
+ error instanceof DOMException && error.name === "AbortError",
+ }
+ : "Unknown error",
+ });
+
+ if (error instanceof DOMException && error.name === "AbortError") {
+ if ((error as ApiError).isTimeout) {
+ throw new Error(`Request timed out after ${timeout}ms`);
+ }
+ throw new Error("Request was aborted");
+ }
+
+ if (error instanceof Error) {
+ throw error;
+ }
+
+ throw new Error("An unknown error occurred during the request");
+ } finally {
+ if (timeoutId !== undefined) {
+ window.clearTimeout(timeoutId);
+ }
+ callerSignal?.removeEventListener("abort", abortFromCaller);
+ }
+ }
+
+ static async uploadAudio(formData: FormData) {
+ const formDataFiles = formData.getAll("audioFile");
+
+ if (!formDataFiles.length) {
+ throw new Error("No audio files provided in FormData");
+ }
+
+ // Validate that all items are actually files and cast them
+ const files = formDataFiles.filter(
+ (file): file is File => file instanceof File
+ );
+ if (files.length !== formDataFiles.length) {
+ throw new Error("Invalid file data provided - all entries must be files");
+ }
+
+ console.log("Starting audio upload...", {
+ fileCount: files.length,
+ fileNames: files.map((f: File) => f.name),
+ totalSize: files.reduce((acc: number, f: File) => acc + f.size, 0),
+ timeout:
+ typeof API_CONFIG.TIMEOUT === "number"
+ ? API_CONFIG.TIMEOUT
+ : this.DEFAULT_TIMEOUT,
+ });
+
+ try {
+ const response = await this.fetchWithTimeout(API_ENDPOINTS.UPLOAD_AUDIO, {
+ method: "POST",
+ body: formData,
+ // Intentionally omitting Content-Type to let browser set it with boundary
+ });
+ console.log("Audio upload completed successfully");
+ return response;
+ } catch (error) {
+ console.error("Audio upload failed:", error);
+ throw error;
+ }
+ }
+
+ static async getPGUnits(): Promise {
+ return this.fetchWithTimeout(API_ENDPOINTS.PG_UNITS, { method: "GET" });
+ }
+
+ static async analyzePG(
+ formData: FormData,
+ signal?: AbortSignal
+ ): Promise {
+ const files = formData.getAll("files");
+
+ if (!files.length) {
+ throw new Error("No audio files provided in FormData");
+ }
+ if (!files.every((file) => file instanceof File)) {
+ throw new Error("Invalid file data provided - all entries must be files");
+ }
+
+ console.log("Starting PG analysis...", {
+ fileCount: files.length,
+ words: formData.get("words"),
+ unit: formData.get("unit"),
+ ranking: formData.get("ranking"),
+ timeout: API_CONFIG.PG_ANALYZE_TIMEOUT,
+ });
+
+ try {
+ const response = await this.fetchWithTimeout(
+ API_ENDPOINTS.PG_ANALYZE,
+ {
+ method: "POST",
+ body: formData,
+ signal,
+ // Intentionally omitting Content-Type to let browser set it with boundary
+ },
+ API_CONFIG.PG_ANALYZE_TIMEOUT
+ );
+ if (!response.success) {
+ throw new Error(response.error || "PG analysis failed");
+ }
+ console.log("PG analysis completed successfully");
+ return response;
+ } catch (error) {
+ console.error("PG analysis failed:", error);
+ throw error;
+ }
+ }
+}
+
+export default ApiService;
diff --git a/VoxPreference-frontend/src/types/pg.ts b/VoxPreference-frontend/src/types/pg.ts
new file mode 100644
index 0000000000000000000000000000000000000000..82e15ac2338a2b032353d02a0e0409651821177c
--- /dev/null
+++ b/VoxPreference-frontend/src/types/pg.ts
@@ -0,0 +1,190 @@
+// Shapes of the Preference Grammar (PG) endpoints, /pg/units and /pg/analyze
+
+// Result of testing the variant classifier on human-labelled tokens of a unit
+export interface PGValidation {
+ status: "validated" | "not validated";
+ kappa?: number; // Cohen's kappa against the human labels
+ accuracy?: number;
+ majority_baseline?: number; // accuracy of always guessing the commonest variant
+ balanced_accuracy?: number;
+ share_error?: number; // mean absolute error of the variant shares
+ calibrated?: boolean;
+ note: string;
+}
+
+export interface PGUnit {
+ key: string;
+ label: string; // as shown in the operability table, e.g. "
"
+ phoneme: string; // the reference segment, e.g. "θ"
+ candidates: string[]; // realisations tested for in the audio
+ international: string[]; // realisations within international norms (I-Ac)
+ pedagogic_difficult: string[]; // realisations marked as hard to teach (Ped-C)
+ lexical_set: string;
+ notes: string;
+ sources: string[];
+ validation?: PGValidation; // missing from older servers, which counts as not validated
+}
+
+export interface PGTenet {
+ key: string;
+ name: string;
+}
+
+export interface PGUnitsResponse {
+ units: Record;
+ tenets: PGTenet[];
+ default_ranking: string;
+}
+
+export interface PGToken {
+ recording: string;
+ speaker: string;
+ word: string;
+ start: number;
+ end: number;
+ variant: string;
+ posterior: number;
+ scores: Record;
+ realised: string; // best-fitting form of the whole word, in IPA
+ heard: string; // free phone decoding of the word
+ primary: string;
+ secondary: string;
+ review: boolean;
+}
+
+export interface PGClusters {
+ categories: string[];
+ contrast_matrix: number[][];
+ separation: Record;
+ subclusters: Record;
+}
+
+export interface PGViolation {
+ count: number;
+ reason: string;
+ source: string;
+}
+
+export interface PGCandidate {
+ form: string;
+ segment: string;
+ tokens: number;
+ share: number; // of tokens, or averaged over speakers when FreQ counts speakers
+ // "preferred (formal standard)" | "allophone (formal inventory)" | "outer (informal) norm"
+ tier?: string;
+ violations: Record;
+}
+
+// A variant attested too rarely to compete (fewer than min_tokens tokens or min_speakers speakers)
+export interface PGVariantCount {
+ form: string;
+ segment: string;
+ tokens: number;
+ share: number;
+}
+
+// How often each variant came out preferred when the speakers and each token's variant
+// were resampled (bootstrap)
+export interface PGStability {
+ resamples: number;
+ speakers: number;
+ preferred_rate: Record; // segment -> share of resamples
+}
+
+// Tenet columns are keyed by their heading, e.g. "*No I-Ac", and hold the marks ("*", "*!")
+export interface PGTableauRow {
+ candidate: string;
+ segment: string;
+ tokens: number;
+ share: number;
+ preferred: boolean;
+ [column: string]: string | number | boolean;
+}
+
+export interface PGTableau {
+ ranking: string[][];
+ rows: PGTableauRow[];
+ markdown: string;
+ html: string;
+ tie: boolean;
+}
+
+export interface PGAnalysisResult {
+ success: true;
+ words: string[];
+ unit: PGUnit;
+ canonical: Record;
+ tokens: PGToken[];
+ clusters: PGClusters | null;
+ candidates: PGCandidate[];
+ superfluous?: PGVariantCount[];
+ tableau: PGTableau | null;
+ preferred: string[];
+ stability?: PGStability | null; // null with fewer than 3 speakers
+ warnings: string[];
+ files: Record;
+}
+
+export type FreqWeighting = "tokens" | "speakers";
+
+// "threshold": variants below the FreQ threshold get a mark; "most_frequent": every variant but the commonest does
+export type FreqMode = "threshold" | "most_frequent";
+
+export interface PGSettings {
+ freq_threshold?: number;
+ freq_weighting?: FreqWeighting;
+ freq_mode?: FreqMode;
+ min_tokens?: number;
+ min_speakers?: number;
+ disam_min_pairs?: number;
+ phos_world_threshold?: number;
+ review_below?: number;
+ calibrated?: boolean;
+ overrides?: Record; // "|" -> violation marks
+}
+
+// Every setting as used for a run, whether sent or left at its default
+export type SettingsValues = Required>;
+
+// Form state of the PG view
+
+export interface RecordingItem {
+ id: string;
+ file: File;
+ origin: "upload" | "recording";
+ speaker: string;
+ transcript: string;
+}
+
+export interface SettingsForm {
+ freq_threshold: string;
+ freq_weighting: FreqWeighting;
+ freq_mode: FreqMode;
+ min_tokens: string;
+ min_speakers: string;
+ disam_min_pairs: string;
+ phos_world_threshold: string;
+ review_below: string;
+ calibrated: boolean;
+}
+
+export interface OverrideRow {
+ id: string;
+ segment: string;
+ tenet: string;
+ count: string;
+}
+
+export interface RankingItem {
+ key: string;
+ enabled: boolean;
+ tiedWithAbove: boolean; // unranked with the tenet listed above it (same stratum)
+}
+
+export interface AnalysisOutcome {
+ id: string;
+ data: PGAnalysisResult;
+ files: Map; // the submitted recordings by name, for listening to tokens
+ settings: SettingsValues;
+ unlabelledRecordings: number; // recordings without a speaker id, which count as speakers of their own
+}
diff --git a/VoxPreference-frontend/src/utils/pg.ts b/VoxPreference-frontend/src/utils/pg.ts
new file mode 100644
index 0000000000000000000000000000000000000000..d07feae8823eec72138f19da3a4104fa1aeba849
--- /dev/null
+++ b/VoxPreference-frontend/src/utils/pg.ts
@@ -0,0 +1,390 @@
+import {
+ OverrideRow,
+ PGSettings,
+ PGTableau,
+ PGTableauRow,
+ PGTenet,
+ PGUnit,
+ RankingItem,
+ SettingsForm,
+ SettingsValues,
+} from "../types/pg";
+
+// The six PG tenets in their default order; /pg/units sends the same list
+export const PG_TENETS: PGTenet[] = [
+ { key: "I-Ac", name: "International acceptance" },
+ { key: "ContR", name: "Contrastiveness" },
+ { key: "FreQ", name: "Frequency" },
+ { key: "DisaM", name: "Disambiguity" },
+ { key: "Pho-S", name: "Phonetic simplicity" },
+ { key: "Ped-C", name: "Pedagogic convenience" },
+];
+
+export const DEFAULT_RANKING =
+ "I-Ac >> ContR >> FreQ >> DisaM >> Pho-S >> Ped-C";
+
+// Operability table headings, which are also the column keys of tableau.rows
+export const TENET_COLUMN_LABELS: Record = {
+ "I-Ac": "*No I-Ac",
+ ContR: "*No ContR",
+ FreQ: "*No FreQ",
+ DisaM: "DisaM",
+ "Pho-S": "*Pho-S",
+ "Ped-C": "*Ped-C",
+};
+
+// The server's defaults (pg/tenets.py Settings)
+export const DEFAULT_SETTINGS: SettingsForm = {
+ freq_threshold: "0.2",
+ freq_weighting: "tokens",
+ freq_mode: "threshold",
+ min_tokens: "3",
+ min_speakers: "2",
+ disam_min_pairs: "1",
+ phos_world_threshold: "0.15",
+ review_below: "0.75",
+ calibrated: true,
+};
+
+// Short names for the output tiers, from most to least formal
+const TIER_LABELS: Record = {
+ "preferred (formal standard)": "Formal standard",
+ "allophone (formal inventory)": "Allophone",
+ "outer (informal) norm": "Informal norm",
+};
+
+export const tierLabel = (tier: string) => TIER_LABELS[tier] ?? tier;
+
+// Classifier validation: a unit without a validation result (older servers) is not validated
+export const isValidated = (unit: PGUnit) =>
+ unit.validation?.status === "validated";
+
+export const validationLabel = (unit: PGUnit) => {
+ if (!isValidated(unit)) return "Not validated";
+ const kappa = unit.validation?.kappa;
+ return typeof kappa === "number"
+ ? `Validated (κ ${kappa.toFixed(2)})`
+ : "Validated";
+};
+
+let lastId = 0;
+// crypto.randomUUID needs a secure context, so a counter keeps ids working over plain http
+export const nextId = (prefix: string) => `${prefix}-${++lastId}`;
+
+// Ranking: "A >> B, C" ranks A above the stratum {B, C}, whose tenets are unranked
+
+export const parseRanking = (ranking: string): string[][] =>
+ ranking
+ .split(">>")
+ .map((stratum) =>
+ stratum
+ .split(",")
+ .map((tenet) => tenet.trim())
+ .filter(Boolean)
+ )
+ .filter((stratum) => stratum.length > 0);
+
+export const rankingItemsFrom = (
+ ranking: string,
+ tenets: PGTenet[]
+): RankingItem[] => {
+ const known = new Set(tenets.map((tenet) => tenet.key));
+ const items: RankingItem[] = [];
+ for (const stratum of parseRanking(ranking)) {
+ stratum
+ .filter((key) => known.has(key) && !items.some((item) => item.key === key))
+ .forEach((key, i) =>
+ items.push({ key, enabled: true, tiedWithAbove: i > 0 })
+ );
+ }
+ // Tenets the ranking leaves out are deleted, but stay listed so they can be restored
+ for (const { key } of tenets) {
+ if (!items.some((item) => item.key === key)) {
+ items.push({ key, enabled: false, tiedWithAbove: false });
+ }
+ }
+ return items;
+};
+
+// Strata are worked out over the whole list, deleted tenets included, so deleting a
+// tenet never merges the strata around it and restoring it is an exact undo
+export const rankingStrata = (items: RankingItem[]): string[][] => {
+ const strata: RankingItem[][] = [];
+ items.forEach((item, i) => {
+ if (item.tiedWithAbove && i > 0) {
+ strata[strata.length - 1].push(item);
+ } else {
+ strata.push([item]);
+ }
+ });
+ return strata
+ .map((stratum) =>
+ stratum.filter((item) => item.enabled).map((item) => item.key)
+ )
+ .filter((stratum) => stratum.length > 0);
+};
+
+// Swap a tenet with its neighbour. Every tenet whose neighbour above changes is ranked
+// strictly again, so a move never silently pulls a tenet into another stratum
+export const moveRankingItem = (
+ items: RankingItem[],
+ index: number,
+ delta: -1 | 1
+): RankingItem[] | null => {
+ const target = index + delta;
+ if (target < 0 || target >= items.length) return null;
+ const next = [...items];
+ next[index] = items[target];
+ next[target] = items[index];
+ const below = Math.max(index, target) + 1;
+ return next.map((item, i) =>
+ i === index || i === target || i === below
+ ? { ...item, tiedWithAbove: false }
+ : item
+ );
+};
+
+export const formatRanking = (strata: string[][]): string =>
+ strata.map((stratum) => stratum.join(", ")).join(" >> ");
+
+// Operability table
+
+export interface TableauColumn {
+ key: string; // tenet key, e.g. "I-Ac"
+ label: string; // heading and row key, e.g. "*No I-Ac"
+ name: string;
+ stratum: number;
+ startsStratum: boolean;
+}
+
+export const tableauColumns = (
+ tableau: PGTableau,
+ tenets: PGTenet[]
+): TableauColumn[] =>
+ tableau.ranking.flatMap((stratum, s) =>
+ stratum.map((key, i) => ({
+ key,
+ label: TENET_COLUMN_LABELS[key] ?? key,
+ name: tenets.find((tenet) => tenet.key === key)?.name ?? key,
+ stratum: s,
+ startsStratum: i === 0,
+ }))
+ );
+
+export const tableauCell = (row: PGTableauRow, column: TableauColumn) =>
+ String(row[column.label] ?? "");
+
+// The stratum holding a candidate's fatal mark ("!"); cells in later strata are shaded
+export const eliminatedAt = (
+ row: PGTableauRow,
+ columns: TableauColumn[]
+): number | null => {
+ const fatal = columns.find((column) =>
+ tableauCell(row, column).includes("!")
+ );
+ return fatal ? fatal.stratum : null;
+};
+
+export const describeMarks = (cell: string) => {
+ const count = (cell.match(/\*/g) ?? []).length;
+ const marks =
+ count === 0
+ ? "no violations"
+ : count === 1
+ ? "1 violation"
+ : `${count} violations`;
+ return cell.includes("!") ? `${marks}, fatal` : marks;
+};
+
+// Candidates are lettered a., b., c. as in PG operability tables
+export const candidateLetter = (index: number) =>
+ String.fromCharCode(97 + index);
+
+// Settings: only values that differ from the defaults are sent, so the server's own
+// defaults apply otherwise and a renamed setting cannot break a request nobody customised
+
+// Labels of the numeric settings, shared by the form and its error messages
+export const SETTING_LABELS = {
+ freq_threshold: "FreQ threshold",
+ min_tokens: "Minimum tokens",
+ min_speakers: "Minimum speakers",
+ disam_min_pairs: "DisaM minimum pairs",
+ phos_world_threshold: "Pho-S: rare in the world's languages below",
+ review_below: "Review threshold",
+} as const;
+
+const NUMBER_SETTINGS = [
+ ["freq_threshold", "fraction"],
+ ["min_tokens", "count"],
+ ["min_speakers", "count"],
+ ["disam_min_pairs", "count"],
+ ["phos_world_threshold", "fraction"],
+ ["review_below", "fraction"],
+] as const;
+
+export const buildSettings = (
+ form: SettingsForm,
+ overrides: OverrideRow[]
+):
+ | { settings: PGSettings; values: SettingsValues; error: null }
+ | { settings: null; values: null; error: string } => {
+ const settings: PGSettings = {};
+ const values: Partial = {
+ freq_weighting: form.freq_weighting,
+ freq_mode: form.freq_mode,
+ calibrated: form.calibrated,
+ };
+ for (const [field, kind] of NUMBER_SETTINGS) {
+ const label = `“${SETTING_LABELS[field]}”`;
+ const text = form[field].trim();
+ const value = Number(text);
+ const valid =
+ kind === "fraction"
+ ? Number.isFinite(value) && value >= 0 && value <= 1
+ : Number.isInteger(value) && value >= 0;
+ if (!text || !valid) {
+ return {
+ settings: null,
+ values: null,
+ error:
+ kind === "fraction"
+ ? `${label} must be a number from 0 to 1`
+ : `${label} must be a whole number (0 or more)`,
+ };
+ }
+ values[field] = value;
+ if (value !== Number(DEFAULT_SETTINGS[field])) settings[field] = value;
+ }
+ if (form.freq_weighting !== DEFAULT_SETTINGS.freq_weighting) {
+ settings.freq_weighting = form.freq_weighting;
+ }
+ if (form.freq_mode !== DEFAULT_SETTINGS.freq_mode) {
+ settings.freq_mode = form.freq_mode;
+ }
+ if (form.calibrated !== DEFAULT_SETTINGS.calibrated) {
+ settings.calibrated = form.calibrated;
+ }
+
+ const used = overrides.filter((row) => row.segment.trim());
+ for (const row of used) {
+ const count = Number(row.count);
+ if (!row.count.trim() || !Number.isInteger(count) || count < 0) {
+ return {
+ settings: null,
+ values: null,
+ error: `The override for [${row.segment.trim()}] needs a whole number of marks (0 or more)`,
+ };
+ }
+ }
+ if (used.length) {
+ settings.overrides = Object.fromEntries(
+ used.map((row) => [`${row.segment.trim()}|${row.tenet}`, Number(row.count)])
+ );
+ }
+ return { settings, values: values as SettingsValues, error: null };
+};
+
+// Words and recordings
+
+// Commas or spaces separate words; the server lower-cases them too
+export const parseWords = (input: string): string[] =>
+ Array.from(
+ new Set(
+ input
+ .split(/[\s,]+/)
+ .map((word) => word.trim().toLowerCase())
+ .filter(Boolean)
+ )
+ );
+
+// With several target words the server matches a single-word recording to its word by file name
+export const fileNameHasWord = (fileName: string, words: string[]) =>
+ words.some((word) => fileName.toLowerCase().includes(word));
+
+// A transcript of "auto" asks the server to find the words by speech recognition
+export const isAutoTranscript = (transcript: string) =>
+ transcript.trim().toLowerCase() === "auto";
+
+// Mirrors the server's aligner, which keeps only letters a-z and apostrophes
+export const transcriptHasWord = (transcript: string, words: string[]) => {
+ const spoken = transcript
+ .toLowerCase()
+ .replace(/’/g, "'")
+ .replace(/[^a-z' ]+/g, " ")
+ .split(" ");
+ return words.some((word) => spoken.includes(word));
+};
+
+const AUDIO_EXTENSIONS = /\.(wav|mp3|flac|ogg|oga|opus|webm|m4a|mp4|aac|aiff?)$/i;
+
+export const isAudioFile = (file: File) =>
+ file.type.startsWith("audio/") || AUDIO_EXTENSIONS.test(file.name);
+
+// Transcripts and speakers are keyed by file name on the server, so names must be unique
+export const uniqueFileName = (name: string, taken: Set) => {
+ if (!taken.has(name)) return name;
+ const dot = name.lastIndexOf(".");
+ const stem = dot > 0 ? name.slice(0, dot) : name;
+ const extension = dot > 0 ? name.slice(dot) : "";
+ const numbered = stem.match(/^(.*)-(\d+)$/);
+ const base = numbered ? numbered[1] : stem;
+ let n = numbered ? Number(numbered[2]) + 1 : 2;
+ while (taken.has(`${base}-${n}${extension}`)) n++;
+ return `${base}-${n}${extension}`;
+};
+
+export const extensionForMimeType = (type: string) => {
+ if (type.includes("ogg")) return "ogg";
+ if (type.includes("mp4") || type.includes("aac")) return "m4a";
+ if (type.includes("wav")) return "wav";
+ return "webm";
+};
+
+// Formatting
+
+export const formatPercent = (share: number) => `${Math.round(share * 100)}%`;
+
+export const formatDuration = (seconds: number) => {
+ const whole = Math.max(0, Math.floor(seconds));
+ return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}`;
+};
+
+export const formatFileSize = (bytes: number) =>
+ bytes < 1024 * 1024
+ ? `${Math.max(1, Math.round(bytes / 1024))} KB`
+ : `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+
+export const fileSlug = (text: string) =>
+ text
+ .toLowerCase()
+ .replace(/[^\p{L}\p{N}]+/gu, "-")
+ .replace(/^-+|-+$/g, "") || "analysis";
+
+// Downloads
+
+const BYTE_ORDER_MARK = String.fromCharCode(0xfeff);
+
+const DOWNLOAD_TYPES: Record = {
+ csv: "text/csv;charset=utf-8",
+ html: "text/html;charset=utf-8",
+ json: "application/json;charset=utf-8",
+};
+
+export const downloadText = (fileName: string, content: string) => {
+ const extension = fileName.split(".").pop() ?? "";
+ // A byte-order mark makes spreadsheet apps read the IPA in CSV files as UTF-8
+ const body = extension === "csv" ? `${BYTE_ORDER_MARK}${content}` : content;
+ const url = URL.createObjectURL(
+ new Blob([body], {
+ type: DOWNLOAD_TYPES[extension] ?? "text/plain;charset=utf-8",
+ })
+ );
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = fileName;
+ document.body.appendChild(link);
+ link.click();
+ link.remove();
+ // Give the browser a moment to start the download before releasing the blob
+ window.setTimeout(() => URL.revokeObjectURL(url), 1000);
+};
diff --git a/VoxPreference-frontend/src/vite-env.d.ts b/VoxPreference-frontend/src/vite-env.d.ts
new file mode 100644
index 0000000000000000000000000000000000000000..11f02fe2a0061d6e6e1f271b21da95423b448b32
--- /dev/null
+++ b/VoxPreference-frontend/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/VoxPreference-frontend/tsconfig.app.json b/VoxPreference-frontend/tsconfig.app.json
new file mode 100644
index 0000000000000000000000000000000000000000..358ca9ba93f089b0133f05933f133a446402eb17
--- /dev/null
+++ b/VoxPreference-frontend/tsconfig.app.json
@@ -0,0 +1,26 @@
+{
+ "compilerOptions": {
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
+ "target": "ES2020",
+ "useDefineForClassFields": true,
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "skipLibCheck": true,
+
+ /* Bundler mode */
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "isolatedModules": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "jsx": "react-jsx",
+
+ /* Linting */
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUncheckedSideEffectImports": true
+ },
+ "include": ["src"]
+}
diff --git a/VoxPreference-frontend/tsconfig.json b/VoxPreference-frontend/tsconfig.json
new file mode 100644
index 0000000000000000000000000000000000000000..1ffef600d959ec9e396d5a260bd3f5b927b2cef8
--- /dev/null
+++ b/VoxPreference-frontend/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "files": [],
+ "references": [
+ { "path": "./tsconfig.app.json" },
+ { "path": "./tsconfig.node.json" }
+ ]
+}
diff --git a/VoxPreference-frontend/tsconfig.node.json b/VoxPreference-frontend/tsconfig.node.json
new file mode 100644
index 0000000000000000000000000000000000000000..db0becc8b033a4a78144f4a3bb852082fe91cd62
--- /dev/null
+++ b/VoxPreference-frontend/tsconfig.node.json
@@ -0,0 +1,24 @@
+{
+ "compilerOptions": {
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
+ "target": "ES2022",
+ "lib": ["ES2023"],
+ "module": "ESNext",
+ "skipLibCheck": true,
+
+ /* Bundler mode */
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "isolatedModules": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+
+ /* Linting */
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUncheckedSideEffectImports": true
+ },
+ "include": ["vite.config.ts"]
+}
diff --git a/VoxPreference-frontend/vite.config.ts b/VoxPreference-frontend/vite.config.ts
new file mode 100644
index 0000000000000000000000000000000000000000..c4069b77004b2443326a0afa4a5919012d757fc5
--- /dev/null
+++ b/VoxPreference-frontend/vite.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from 'vite'
+import react from '@vitejs/plugin-react'
+import tailwindcss from '@tailwindcss/vite'
+
+// https://vite.dev/config/
+export default defineConfig({
+ plugins: [react(), tailwindcss()],
+})
diff --git a/app.py b/app.py
deleted file mode 100644
index 3b03055b384350aa3aaa071c32d987fd90fa4546..0000000000000000000000000000000000000000
--- a/app.py
+++ /dev/null
@@ -1,141 +0,0 @@
-from fastapi import FastAPI, File, UploadFile, Request, Form
-from fastapi.responses import JSONResponse
-from fastapi.middleware.cors import CORSMiddleware
-import io
-import librosa
-from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
-from text_to_ipa import convert_to_ipa
-import torch
-import os
-import logging
-import sys
-from typing import List
-import numpy as np
-import re
-
-os.environ["HF_HOME"] = "/app/hf_home"
-
-
-# Logging configuration
-LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
-logging.basicConfig(
- level=LOG_LEVEL,
- format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
- stream=sys.stdout
-)
-logger = logging.getLogger("voxpreference.app")
-
-logger.info("Starting Voxpreference FastAPI app...")
-
-app = FastAPI()
-
-app.add_middleware(
- CORSMiddleware,
- allow_origins=["*"],
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
-)
-
-import os
-processor = Wav2Vec2Processor.from_pretrained("thebickersteth/wav2vec2-nigerian-english")
-model = Wav2Vec2ForCTC.from_pretrained("thebickersteth/wav2vec2-nigerian-english")
-# model.eval()
-
-@app.middleware("http")
-async def log_requests(request: Request, call_next):
- logger.info(f"Incoming request: {request.method} {request.url}")
- try:
- response = await call_next(request)
- logger.info(f"Response status: {response.status_code} for {request.method} {request.url}")
- return response
- except Exception as exc:
- logger.exception(f"Unhandled exception for {request.method} {request.url}")
- raise
-
-@app.get("/")
-def root():
- logger.info("Root endpoint called.")
- return {"message": "Welcome! This API is for transcription. Try /health or /transcribe."}
-
-@app.head("/")
-def root_head():
- logger.info("Root HEAD endpoint called.")
- return {"message": "Welcome! This API is for transcription. Try /health or /transcribe."}
-
-@app.get("/health")
-def health():
- logger.info("Health check endpoint called.")
- return {"status": "ok"}
-
-@app.post("/")
-async def transcribe(audioFile: UploadFile = File(...)):
- logger.info(f"Transcription endpoint called. Filename: {audioFile.filename}")
- try:
- audio_bytes = await audioFile.read()
- logger.debug(f"Read {len(audio_bytes)} bytes from uploaded file.")
- audio_input, sr = librosa.load(io.BytesIO(audio_bytes), sr=16000)
- logger.debug("Audio loaded and resampled to 16kHz.")
- duration = len(audio_input) / sr
- inputs = processor(audio_input, sampling_rate=16000, return_tensors="pt")
- logger.debug("Audio processed for model input.")
- with torch.no_grad():
- logits = model(inputs.input_values).logits
- predicted_ids = torch.argmax(logits, dim=-1)
- transcription = processor.batch_decode(predicted_ids.numpy())[0]
- logger.info(f"Transcription result: {transcription}")
- words = transcription.strip().split()
- n_words = len(words)
- segments = []
- if n_words > 0:
- word_duration = duration / n_words
- for i, word in enumerate(words):
- start = round(i * word_duration, 2)
- end = round((i + 1) * word_duration, 2)
- ipa_result = convert_to_ipa(word)
- ipa = ipa_result["ipa"] if ipa_result["success"] else None
- ipa_error = ipa_result["error"] if not ipa_result["success"] else None
- segments.append({
- "start": start,
- "end": end,
- "text": word,
- "ipa": ipa,
- "ipa_error": ipa_error
- })
- return JSONResponse(
- status_code=200,
- content={
- "success": True,
- "segments": segments,
- "transcription": transcription,
- "duration": duration
- }
- )
- except Exception as e:
- logger.exception(f"Error during transcription process: {e}")
- return JSONResponse(
- status_code=500,
- content={"success": False, "error": str(e)}
- )
-
-@app.post("/ipa")
-async def word_to_ipa(word: str = Form(...)):
- logger.info(f"IPA endpoint called for word: {word}")
- try:
- ipa_result = convert_to_ipa(word)
- ipa = ipa_result["ipa"] if ipa_result["success"] else None
- ipa_error = ipa_result["error"] if not ipa_result["success"] else None
- return JSONResponse(
- status_code=200,
- content={
- "success": ipa_result["success"],
- "ipa": ipa,
- "ipa_error": ipa_error
- }
- )
- except Exception as e:
- logger.exception(f"Error during IPA conversion: {e}")
- return JSONResponse(
- status_code=500,
- content={"success": False, "error": str(e)}
- )
diff --git a/backend/.DS_Store b/backend/.DS_Store
new file mode 100644
index 0000000000000000000000000000000000000000..3102e897aec6f75527d5b3bed27dc5cf2ba25c72
Binary files /dev/null and b/backend/.DS_Store differ
diff --git a/backend/README.md b/backend/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..b5317c15a356810882984a2ae69d42d031a195d6
--- /dev/null
+++ b/backend/README.md
@@ -0,0 +1,11 @@
+---
+title: Voxpreference
+emoji: 📈
+colorFrom: indigo
+colorTo: gray
+sdk: docker
+pinned: false
+short_description: speech recognition using nigerian english
+---
+
+Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/backend/app.py b/backend/app.py
new file mode 100644
index 0000000000000000000000000000000000000000..eefaff98c4c49e385b10b72563021a5d06de81ca
--- /dev/null
+++ b/backend/app.py
@@ -0,0 +1,182 @@
+from dataclasses import asdict
+import threading
+from typing import List, Optional
+import json
+import os
+from pathlib import Path
+from fastapi import FastAPI, File, Form, UploadFile
+from fastapi.responses import JSONResponse
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.staticfiles import StaticFiles
+import io
+import librosa
+from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
+from text_to_ipa import convert_to_ipa
+import torch
+from pg import audio as pg_audio
+from pg.ot import DEFAULT_RANKING, TENET_NAMES, TENETS, parse_ranking
+from pg.report import contrast_csv, html_report, subclusters_csv, tokens_csv
+from pg.tenets import load_units, settings_from
+
+app = FastAPI()
+
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+_asr = None
+
+
+def get_asr():
+ global _asr
+ if _asr is None:
+ processor = Wav2Vec2Processor.from_pretrained("thebickersteth/wav2vec2-nigerian-english")
+ model = Wav2Vec2ForCTC.from_pretrained("thebickersteth/wav2vec2-nigerian-english").eval()
+ _asr = (processor, model)
+ return _asr
+
+FRONTEND_DIST = Path(os.environ.get("FRONTEND_DIST", Path(__file__).resolve().parents[1] / "VoxPreference-frontend" / "dist"))
+
+
+if not FRONTEND_DIST.is_dir():
+ @app.get("/")
+ def root():
+ return {"message": "Welcome! This API is for transcription. Try /health or /transcribe."}
+
+
+@app.get("/health")
+def health():
+ return {"status": "ok"}
+
+@app.post("/transcribe")
+async def transcribe(audioFile: UploadFile = File(...)):
+ try:
+ audio_bytes = await audioFile.read()
+ audio_input, _ = librosa.load(io.BytesIO(audio_bytes), sr=16000)
+ processor, model = get_asr()
+ inputs = processor(audio_input, sampling_rate=16000, return_tensors="pt")
+ with torch.no_grad():
+ logits = model(inputs.input_values).logits
+ predicted_ids = torch.argmax(logits, dim=-1)
+ transcription = processor.batch_decode(predicted_ids.numpy())[0]
+ ipa_result = convert_to_ipa(transcription)
+ ipa = ipa_result["ipa"] if ipa_result["success"] else None
+ ipa_error = ipa_result["error"] if not ipa_result["success"] else None
+ print(transcription, ipa, ipa_error)
+ return JSONResponse(
+ status_code=200,
+ content={
+ "success": True,
+ "transcription": transcription,
+ "ipa": ipa,
+ "ipa_error": ipa_error
+ }
+ )
+ except Exception as e:
+ return JSONResponse(
+ status_code=500,
+ content={"success": False, "error": str(e)}
+ )
+
+
+_analyzer = None
+# one analysis at a time: the models take ~2 GB and every analysis uses all CPU cores
+_analysis_lock = threading.Lock()
+MAX_FILES = 300
+MAX_FILE_BYTES = 50 * 1024 * 1024
+
+
+_analyzer_lock = threading.Lock()
+
+
+def get_analyzer():
+ # the phone model is large, so it loads on the first PG request, or in the background at start-up
+ # when PG_WARM=1 (the Docker image sets it, so a woken Space is ready sooner)
+ global _analyzer
+ with _analyzer_lock:
+ if _analyzer is None:
+ from pg.pipeline import Analyzer
+ _analyzer = Analyzer()
+ return _analyzer
+
+
+@app.on_event("startup")
+def _warm_up():
+ if os.environ.get("PG_WARM") == "1":
+ threading.Thread(target=lambda: get_analyzer().aligner, daemon=True).start()
+
+
+@app.get("/pg/units")
+def pg_units():
+ return {
+ "units": {k: asdict(u) for k, u in load_units().items()},
+ "tenets": [{"key": t, "name": TENET_NAMES[t]} for t in TENETS],
+ "default_ranking": DEFAULT_RANKING,
+ }
+
+
+@app.post("/pg/analyze")
+def pg_analyze(
+ files: List[UploadFile] = File(...),
+ words: str = Form(...),
+ unit: Optional[str] = Form(None),
+ ranking: str = Form(DEFAULT_RANKING),
+ transcripts: Optional[str] = Form(None),
+ speakers: Optional[str] = Form(None),
+ settings: Optional[str] = Form(None),
+ asr: bool = Form(False),
+ diarize: bool = Form(True),
+ num_speakers: Optional[int] = Form(None),
+):
+ """files: recordings; words: comma-separated target words; transcripts/speakers: JSON objects
+ keyed by file name (omit transcripts for single-word recordings; "auto" or asr=true finds the
+ words in unscripted audio by speech recognition); diarize: separate the speakers inside unscripted
+ recordings that have no speaker id; num_speakers: how many talk in each, if known; settings: JSON
+ tenet thresholds."""
+ from pg.pipeline import Recording
+ try:
+ config = settings_from(json.loads(settings) if settings else None)
+ parse_ranking(ranking)
+ if len(files) > MAX_FILES:
+ raise ValueError(f"at most {MAX_FILES} recordings per analysis")
+ transcript_of = json.loads(transcripts) if transcripts else {}
+ speaker_of = json.loads(speakers) if speakers else {}
+ if num_speakers is not None and not 1 <= num_speakers <= 20:
+ raise ValueError("num_speakers must be between 1 and 20")
+ recordings = []
+ for f in files:
+ data = f.file.read(MAX_FILE_BYTES + 1)
+ if len(data) > MAX_FILE_BYTES:
+ raise ValueError(f"{f.filename} is larger than {MAX_FILE_BYTES // 2**20} MB")
+ try:
+ audio = pg_audio.load(data)
+ except RuntimeError as e:
+ raise ValueError(f"{f.filename}: {e}") from e
+ recordings.append(Recording(f.filename, audio, speaker=speaker_of.get(f.filename, ""),
+ transcript=transcript_of.get(f.filename, "auto" if asr else ""),
+ diarize=None if diarize else False, num_speakers=num_speakers))
+ with _analysis_lock:
+ result = get_analyzer().analyse(recordings, words.split(","), unit or None, ranking, config)
+ except (ValueError, KeyError) as e:
+ return JSONResponse(status_code=400, content={"success": False, "error": str(e).strip("'\"")})
+ except Exception as e:
+ return JSONResponse(status_code=500, content={"success": False, "error": str(e)})
+ body = result.to_dict()
+ body["success"] = True
+ body["files"] = {
+ "tokens.csv": tokens_csv(result),
+ "subclusters.csv": subclusters_csv(result),
+ "contrast_matrix.csv": contrast_csv(result),
+ "operability_table.csv": result.tableau.to_csv() if result.tableau else "",
+ "report.html": html_report(result),
+ }
+ return body
+
+
+# the built frontend (npm run build) is served from the same address as the API, so one process is the whole app
+if FRONTEND_DIST.is_dir():
+ app.mount("/", StaticFiles(directory=FRONTEND_DIST, html=True), name="frontend")
diff --git a/prepare_balanced_dataset.py b/backend/eval/__init__.py
similarity index 100%
rename from prepare_balanced_dataset.py
rename to backend/eval/__init__.py
diff --git a/backend/eval/diarize_eval.py b/backend/eval/diarize_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1123e30b239eb02d047645453a087a5fbbe3bf3
--- /dev/null
+++ b/backend/eval/diarize_eval.py
@@ -0,0 +1,125 @@
+"""How well speaker separation works, on made-up conversations whose speakers are known.
+
+Utterances from different SLR70 Nigerian English speakers are joined into one recording in short turns
+(1-3 utterances each, small pauses), as in a panel podcast. We then score how much of the speech is given to
+the right speaker (after matching our anonymous labels to the true speakers) and whether the number of
+speakers was found. Same-sex speakers are included, which is the harder case.
+
+ python -m eval.diarize_eval [--conversations 8] [--minutes 4]
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import random
+from collections import defaultdict
+from pathlib import Path
+
+import numpy as np
+from scipy.optimize import linear_sum_assignment
+
+from pg.audio import load
+from pg.diarize import Diarizer, cluster, speech_windows
+
+SLR70 = Path(__file__).resolve().parents[1] / "data" / "work" / "slr70" / "wav"
+SR = 16000
+
+
+def by_speaker() -> dict[str, list[Path]]:
+ out = defaultdict(list)
+ for p in sorted(SLR70.glob("*.wav")):
+ out[p.stem.rsplit("_", 1)[0]].append(p)
+ return {s: ps for s, ps in out.items() if len(ps) >= 20}
+
+
+def conversation(speakers: list[str], files: dict[str, list[Path]], seconds: float, rng: random.Random):
+ pieces, truth, t, last = [], [], 0.0, None
+ while t < seconds:
+ who = rng.choice([s for s in speakers if s != last] or speakers)
+ last = who
+ for _ in range(rng.randint(1, 3)):
+ audio = load(rng.choice(files[who]))
+ gap = np.zeros(int(rng.uniform(0.15, 0.6) * SR), dtype=np.float32)
+ pieces += [audio, gap]
+ truth.append((t, t + len(audio) / SR, who))
+ t += (len(audio) + len(gap)) / SR
+ return np.concatenate(pieces), truth
+
+
+def score(truth, dia, step: float = 0.05) -> float:
+ """Share of speech time given to the right speaker, under the best one-to-one matching of labels."""
+ true_names = sorted({w for _, _, w in truth})
+ hyp_names = sorted({t.speaker for t in dia.turns}) or ["none"]
+ m = np.zeros((len(true_names), len(hyp_names)))
+ total = 0.0
+ for s, e, who in truth:
+ for x in np.arange(s, e, step):
+ got = dia.speaker_at(x, x + step, reach=0.0)
+ total += step
+ if got is not None:
+ m[true_names.index(who), hyp_names.index(got)] += step
+ r, c = linear_sum_assignment(-m)
+ return float(m[r, c].sum() / total)
+
+
+def clip_score(truth, dia) -> tuple[float, float]:
+ """Share of clips (a sentence each) credited to the right speaker, the way a word inside it is credited,
+ under the best matching of labels; and the same for 0.4 s pieces from the middle of each clip."""
+ true_names = sorted({w for _, _, w in truth})
+ hyp = sorted({t.speaker for t in dia.turns}) or ["none"]
+ whole, piece = np.zeros((len(true_names), len(hyp))), np.zeros((len(true_names), len(hyp)))
+ for s, e, who in truth:
+ for m, (a, b) in ((whole, (s, e)), (piece, ((s + e) / 2 - 0.2, (s + e) / 2 + 0.2))):
+ got = dia.speaker_at(a, b)
+ if got is not None:
+ m[true_names.index(who), hyp.index(got)] += 1
+ out = []
+ for m in (whole, piece):
+ r, c = linear_sum_assignment(-m)
+ out.append(float(m[r, c].sum() / len(truth)))
+ return tuple(out)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--conversations", type=int, default=8)
+ ap.add_argument("--minutes", type=float, default=4)
+ ap.add_argument("--thresholds", default="0.8,0.9")
+ ap.add_argument("--seed", type=int, default=0, help="a new seed gives conversations not used for tuning")
+ ap.add_argument("--out", default="data/work/diarize_eval.json")
+ ap.add_argument("--model", default=None, help="speaker model (default: pg.diarize.SPEAKER_MODEL)")
+ args = ap.parse_args()
+ files = by_speaker()
+ rng = random.Random(args.seed)
+ diarizer = Diarizer(args.model) if args.model else Diarizer()
+ rows = []
+ for i in range(args.conversations):
+ n = [2, 3, 4, 5][i % 4]
+ speakers = rng.sample(sorted(files), n)
+ audio, truth = conversation(speakers, files, args.minutes * 60, rng)
+ windows = speech_windows(audio)
+ emb = diarizer.embed(audio, windows)
+ cache = Path(args.out).with_suffix("") / f"conv{i}.npz"
+ cache.parent.mkdir(parents=True, exist_ok=True)
+ np.savez(cache, emb=emb, windows=np.array(windows), truth=np.array(truth, dtype=object), speakers=speakers)
+ row = {"speakers": n, "ids": speakers, "seconds": round(len(audio) / SR)}
+ for th in [float(x) for x in args.thresholds.split(",")]:
+ d = cluster(windows, emb, None, th)
+ row[f"auto_{th}"] = {"found": d.speakers, "accuracy": round(score(truth, d), 3),
+ "word_level": round(clip_score(truth, d)[1], 3)}
+ d = cluster(windows, emb, n)
+ row["known_n"] = {"found": d.speakers, "accuracy": round(score(truth, d), 3),
+ "word_level": round(clip_score(truth, d)[1], 3)}
+ rows.append(row)
+ print(json.dumps(row), flush=True)
+ Path(args.out).write_text(json.dumps(rows, indent=1))
+ keys = [k for k in rows[0] if k.startswith("auto_") or k == "known_n"]
+ for k in keys:
+ acc = np.mean([r[k]["accuracy"] for r in rows])
+ right_n = np.mean([r[k]["found"] == r["speakers"] for r in rows])
+ word = np.mean([r[k]["word_level"] for r in rows])
+ print(f"{k}: words credited right {word:.3f}, speech time {acc:.3f}, right number of speakers in {right_n:.0%}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/backend/eval/diarize_tune.py b/backend/eval/diarize_tune.py
new file mode 100644
index 0000000000000000000000000000000000000000..e22382cae3549dd0fc5c005d3a743d4b9e8fa5e9
--- /dev/null
+++ b/backend/eval/diarize_tune.py
@@ -0,0 +1,39 @@
+"""Tune the speaker clustering on embeddings saved by eval.diarize_eval (no model needed).
+
+ python -m eval.diarize_tune [data/work/diarize_eval]
+"""
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import numpy as np
+
+from eval.diarize_eval import clip_score, score
+from pg.diarize import cluster
+
+
+def load(folder: Path):
+ for p in sorted(folder.glob("conv*.npz")):
+ d = np.load(p, allow_pickle=True)
+ yield p.stem, d["emb"], [tuple(w) for w in d["windows"]], [tuple(t) for t in d["truth"]], len(d["speakers"])
+
+
+def main():
+ folder = Path(sys.argv[1] if len(sys.argv) > 1 else "data/work/diarize_eval")
+ convs = list(load(folder))
+ configs = [(th, rf, sm) for th in (0.6, 0.7, 0.8) for rf in (0, 5) for sm in (1, 3, 5, 9)]
+ results = {cfg: [] for cfg in configs}
+ for name, emb, windows, truth, n in convs:
+ for th, rf, sm in configs:
+ d = cluster(windows, emb, None, th, smooth=sm, refine=rf)
+ results[(th, rf, sm)].append((score(truth, d), d.speakers == n, d.speakers - n, clip_score(truth, d)[1]))
+ k = cluster(windows, emb, n)
+ print(name, n, "known count:", round(score(truth, k), 3), "word-level:", round(clip_score(truth, k)[1], 3), flush=True)
+ for (th, rf, sm), r in results.items():
+ print(f"threshold={th} refine={rf} smooth={sm}: accuracy {np.mean([x[0] for x in r]):.3f}, "
+ f"word-level {np.mean([x[3] for x in r]):.3f}, right count {np.mean([x[1] for x in r]):.0%}, mean count error {np.mean([x[2] for x in r]):+.2f}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/backend/eval/fetch_saa.py b/backend/eval/fetch_saa.py
new file mode 100644
index 0000000000000000000000000000000000000000..7dde9e14d7f19a37993b97b1600a68f36c1ab872
--- /dev/null
+++ b/backend/eval/fetch_saa.py
@@ -0,0 +1,35 @@
+"""Download the Nigerian/West African subset of the Speech Accent Archive used by eval/saa_gold.py.
+
+Source: Weinberger, S. (2015). Speech Accent Archive, George Mason University; audio and IPA transcriptions on OSF
+(https://osf.io/yh23d, https://osf.io/e2j5y), licence CC BY-NC-SA 4.0. The file list is eval/saa_west_african_subset.tsv.
+
+python -m eval.fetch_saa
+"""
+from __future__ import annotations
+
+import csv
+import urllib.request
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+DEST = HERE.parent / "data" / "resources" / "speech_accent_archive"
+
+
+def main():
+ with open(HERE / "saa_west_african_subset.tsv", encoding="utf-8") as f:
+ rows = list(csv.DictReader(f, delimiter="\t"))
+ for sub in ("flac", "transcription_texts"):
+ (DEST / sub).mkdir(parents=True, exist_ok=True)
+ got = 0
+ for r in rows:
+ for url, path in ((r.get("flac_url"), DEST / "flac" / f"{r['sample']}.flac"),
+ (r.get("txt_url") if r.get("has_text_ipa") == "True" else None,
+ DEST / "transcription_texts" / f"{r['sample']}.txt")):
+ if url and not path.exists():
+ urllib.request.urlretrieve(url, path)
+ got += 1
+ print(f"downloaded {got} files into {DEST}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/backend/eval/fit_calibration.py b/backend/eval/fit_calibration.py
new file mode 100644
index 0000000000000000000000000000000000000000..26e3e49c81818a0d3a795f299e0f0adee961e14a
--- /dev/null
+++ b/backend/eval/fit_calibration.py
@@ -0,0 +1,145 @@
+"""Validate the variant classifier per unit on gold-labelled tokens, and fit calibration where it truly helps.
+
+Metrics, with speaker-bootstrap 95% intervals: accuracy beside the majority-class baseline, balanced accuracy,
+Cohen's kappa (agreement beyond chance; a constant predictor scores 0), and the error in the estimated variant
+shares (total variation distance), which is what PG's Frequency tenet consumes. Calibration is evaluated on
+held-out speakers and kept only if it raises kappa with an interval that excludes zero, because under class
+imbalance accuracy rewards predicting the majority class for every token.
+
+Writes pg/kb/calibration.json and each unit's "validation" entry in pg/kb/units.json (--write).
+
+python -m eval.fit_calibration [--rows data/work/saa_rows.json] [--write]
+"""
+from __future__ import annotations
+
+import argparse
+import collections
+import datetime
+import json
+import random
+from pathlib import Path
+
+import numpy as np
+
+from eval.saa_gold import BACKEND, CLASS, to_class
+from pg.calibrate import KB, fit, predict
+from pg.tenets import KB_DIR, load_units
+
+VALIDATED_KAPPA = 0.5 # substantial agreement beyond chance, on held-out speakers
+
+
+def kappa(gold: list[str], pred: list[str]) -> float:
+ n = len(gold)
+ labels = sorted(set(gold) | set(pred))
+ po = sum(g == p for g, p in zip(gold, pred)) / n
+ gc, pc = collections.Counter(gold), collections.Counter(pred)
+ pe = sum(gc[l] * pc[l] for l in labels) / n / n
+ return 0.0 if pe == 1 else (po - pe) / (1 - pe)
+
+
+def metrics(gold: list[str], pred: list[str]) -> dict:
+ n = len(gold)
+ gc = collections.Counter(gold)
+ recalls = [sum(g == p for g, p in zip(gold, pred) if g == c) / k for c, k in gc.items()]
+ pc = collections.Counter(pred)
+ tvd = 0.5 * sum(abs(gc[c] / n - pc[c] / n) for c in set(gc) | set(pc))
+ return {"accuracy": sum(g == p for g, p in zip(gold, pred)) / n, "majority": max(gc.values()) / n,
+ "balanced_accuracy": float(np.mean(recalls)), "kappa": kappa(gold, pred), "share_tvd": tvd}
+
+
+def bootstrap(rows: list[dict], preds: list[str], n: int = 1000, seed: int = 0) -> dict:
+ """95% intervals over speakers (resampled with replacement)."""
+ by = collections.defaultdict(list)
+ for i, r in enumerate(rows):
+ by[r["speaker"]].append(i)
+ spk = sorted(by)
+ rng = random.Random(seed)
+ draws = collections.defaultdict(list)
+ for _ in range(n):
+ idx = [i for s in rng.choices(spk, k=len(spk)) for i in by[s]]
+ m = metrics([rows[i]["gold"] for i in idx], [preds[i] for i in idx])
+ for k, v in m.items():
+ draws[k].append(v)
+ return {k: (float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))) for k, v in draws.items()}
+
+
+def raw_prediction(r: dict, labels: list[str], class_of: dict) -> str:
+ """The deployed closed-set decision without calibration: the candidate with the lowest CTC loss."""
+ scored = [(r["nll"][l], l) for l in labels if r["nll"].get(l) is not None]
+ return class_of[min(scored)[1]] if scored else "other"
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--rows", default=str(BACKEND / "data" / "work" / "saa_rows.json"))
+ ap.add_argument("--write", action="store_true")
+ ap.add_argument("--l2", type=float, default=0.5)
+ args = ap.parse_args(argv)
+ rows = json.loads(Path(args.rows).read_text(encoding="utf-8"))
+ units = load_units()
+ calibrations, validation = {}, {}
+ for unit_key in CLASS:
+ labels = list(units[unit_key].candidates)
+ class_of = {l: to_class(unit_key, l) for l in labels}
+ rs = [r for r in rows if r["unit"] == unit_key and r["gold"] in set(class_of.values()) and r.get("nll")]
+ if len({r["speaker"] for r in rs}) < 3:
+ continue
+ gold = [r["gold"] for r in rs]
+ raw = [raw_prediction(r, labels, class_of) for r in rs]
+ # leave-one-speaker-out calibrated predictions
+ cal = [None] * len(rs)
+ for spk in sorted({r["speaker"] for r in rs}):
+ train = [r for r in rs if r["speaker"] != spk]
+ c = fit(train, labels, class_of, args.l2)
+ for i, r in enumerate(rs):
+ if r["speaker"] == spk:
+ cal[i] = predict(r, c, class_of)[0]
+ m_raw, m_cal = metrics(gold, raw), metrics(gold, cal)
+ ci_raw = bootstrap(rs, raw)
+ # bootstrap the kappa gain over speakers
+ by = collections.defaultdict(list)
+ for i, r in enumerate(rs):
+ by[r["speaker"]].append(i)
+ spk, rng, gains = sorted(by), random.Random(1), []
+ for _ in range(1000):
+ idx = [i for s in rng.choices(spk, k=len(spk)) for i in by[s]]
+ g = [gold[i] for i in idx]
+ gains.append(kappa(g, [cal[i] for i in idx]) - kappa(g, [raw[i] for i in idx]))
+ gain_lo, gain_hi = np.percentile(gains, [2.5, 97.5])
+ keep = bool(gain_lo > 0)
+ chosen = m_cal if keep else m_raw
+ print(f"\n{unit_key}: {len(rs)} tokens, {len(spk)} speakers")
+ for name, m in (("raw", m_raw), ("calibrated, held-out speakers", m_cal)):
+ print(f" {name:30s} accuracy {m['accuracy']:.0%} (majority {m['majority']:.0%}) balanced {m['balanced_accuracy']:.0%} "
+ f"kappa {m['kappa']:.2f} share error {m['share_tvd']:.2f} predicted {dict(collections.Counter(raw if name == 'raw' else cal))}")
+ print(f" raw 95% CI: accuracy {ci_raw['accuracy'][0]:.0%}-{ci_raw['accuracy'][1]:.0%}, kappa {ci_raw['kappa'][0]:.2f}-{ci_raw['kappa'][1]:.2f}")
+ print(f" kappa gain from calibration {np.mean(gains):+.2f} (95% CI {gain_lo:+.2f} to {gain_hi:+.2f}) -> {'kept' if keep else 'not kept'}")
+ if keep:
+ calibrations[unit_key] = {**fit(rs, labels, class_of, args.l2),
+ "fitted_on": f"{len(rs)} human-labelled tokens from {len(spk)} speakers"}
+ validated = chosen["kappa"] >= VALIDATED_KAPPA
+ validation[unit_key] = {
+ "status": "validated" if validated else "not validated",
+ "kappa": round(chosen["kappa"], 2), "accuracy": round(chosen["accuracy"], 2),
+ "majority_baseline": round(chosen["majority"], 2), "balanced_accuracy": round(chosen["balanced_accuracy"], 2),
+ "share_error": round(chosen["share_tvd"], 2), "calibrated": keep,
+ "note": (f"kappa {chosen['kappa']:.2f} on {len(rs)} tokens from {len(spk)} Nigerian speakers "
+ f"(Speech Accent Archive; one paragraph, so new words are untested)"),
+ }
+ if args.write:
+ KB.write_text(json.dumps({
+ "about": "Per-unit temperature and variant offsets fitted by pg/calibrate.py on human-labelled Nigerian tokens "
+ "(Speech Accent Archive, phonetician IPA). Kept only where they raise Cohen's kappa on held-out speakers "
+ "with a speaker-bootstrap interval above zero. Refit with eval/fit_calibration.py when more labels exist.",
+ "model": "facebook/wav2vec2-xlsr-53-espeak-cv-ft", "date": datetime.date.today().isoformat(), "units": calibrations,
+ }, ensure_ascii=False, indent=1), encoding="utf-8")
+ path = KB_DIR / "units.json"
+ kb = json.loads(path.read_text(encoding="utf-8"))
+ for key, unit in kb["units"].items():
+ unit["validation"] = validation.get(key, {"status": "not validated", "note": "no human-labelled test yet"})
+ path.write_text(json.dumps(kb, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ print("\nwrote", KB, "and validation entries in", path)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/backend/eval/saa_gold.py b/backend/eval/saa_gold.py
new file mode 100644
index 0000000000000000000000000000000000000000..de80a8912b08f6014ce843953b9073cd2c324615
--- /dev/null
+++ b/backend/eval/saa_gold.py
@@ -0,0 +1,247 @@
+"""Gold evaluation on the Nigerian speakers of the Speech Accent Archive (narrow IPA by trained phoneticians).
+
+Each speaker reads the same paragraph. The transcription is aligned to the paragraph (dynamic programming,
+so repeated or skipped words are handled), segments inside each target word are aligned to the reference
+pronunciation to read off the realisation of the unit, and the pipeline's own token scorer is run on the
+audio. Reports token accuracy per unit and whether operability tables built from the expert labels and from
+the automatic labels prefer the same form; writes every token (with raw scores) for calibration.
+
+python -m eval.saa_gold [--calibrated] [--out data/work/saa_rows.json]
+"""
+from __future__ import annotations
+
+import argparse
+import collections
+import json
+import re
+import sys
+import time
+import unicodedata
+from pathlib import Path
+
+import numpy as np
+
+from pg import audio as audio_io, lexicon
+from pg.ot import Candidate, evaluate
+from pg.pipeline import Analyzer, Recording
+from pg.tenets import Settings, assess
+
+BACKEND = Path(__file__).resolve().parents[1]
+SAA = BACKEND / "data" / "resources" / "speech_accent_archive"
+PARAGRAPH = ("Please call Stella. Ask her to bring these things with her from the store: Six spoons of fresh snow peas, "
+ "five thick slabs of blue cheese, and maybe a snack for her brother Bob. We also need a small plastic snake "
+ "and a big toy frog for the kids. She can scoop these things into three red bags, and we will go meet her "
+ "Wednesday at the train station.")
+PWORDS = re.findall(r"[a-z']+", PARAGRAPH.lower())
+UNIT_OF = {
+ "things": "TH-voiceless", "thick": "TH-voiceless", "three": "TH-voiceless",
+ "these": "TH-voiced", "the": "TH-voiced", "brother": "TH-voiced",
+ "her": "NURSE",
+ "snow": "GOAT", "go": "GOAT", "also": "GOAT",
+ "maybe": "FACE", "snake": "FACE", "train": "FACE", "station": "FACE",
+ "bring": "KIT", "six": "KIT", "big": "KIT", "kids": "KIT", "will": "KIT",
+ "please": "FLEECE", "cheese": "FLEECE", "peas": "FLEECE", "meet": "FLEECE", "need": "FLEECE", "she": "FLEECE",
+ "we": "FLEECE",
+}
+# gold symbols (broad) and predicted labels map onto comparable classes per unit
+CLASS = {
+ "TH-voiceless": {"θ": "θ", "t": "t", "s": "s", "f": "f", "d": "d", "ð": "ð", "z": "z"},
+ "TH-voiced": {"ð": "ð", "d": "d", "z": "z", "v": "v", "θ": "θ", "t": "t", "s": "z"},
+ "NURSE": {"ɜ": "ɜː", "ɜː": "ɜː", "ɝ": "ɜː", "ɚ": "ɜː", "ɛ": "ɛ", "e": "ɛ", "a": "a", "æ": "a", "ɑ": "a", "ɐ": "ə",
+ "ɔ": "ɔ", "ɒ": "ɔ", "o": "ɔ", "ə": "ə", "ʌ": "ə"},
+ "GOAT": {"əʊ": "əʊ", "oʊ": "əʊ", "ou": "əʊ", "ɔʊ": "əʊ", "o": "o", "ɔ": "ɔ", "ɒ": "ɔ"},
+ "FACE": {"eɪ": "eɪ", "ei": "eɪ", "ɛɪ": "eɪ", "e": "e", "ɛ": "ɛ"},
+ "KIT": {"ɪ": "ɪ", "i": "i", "iː": "i", "e": "e", "ɛ": "e"},
+ "FLEECE": {"i": "iː", "iː": "iː", "ɪ": "ɪ"},
+}
+DIPHTHONGS = {"oʊ", "əʊ", "ou", "ɔʊ", "eɪ", "ei", "ɛɪ", "aɪ", "ai", "aʊ", "au", "ɔɪ", "oɪ"}
+LOOKALIKE = {"ⅼ": "l", "а": "a", "і": "i", "ǝ": "ə", "ʧ": "tʃ", "ʤ": "dʒ", "I": "ɪ", "g": "ɡ", "ɫ": "l", "ε": "ɛ"}
+STRIP = set("ːˑʰʲˠ̆ʼ")
+VOWELS = set("aeiouæɑɒɔəɛɜɪʊʌɐɚɝœøy")
+
+
+def clean(text: str) -> list[str]:
+ text = "\n".join(l for l in text.splitlines() if "[" in l or not re.search(r"speaker", l, re.I))
+ text = unicodedata.normalize("NFD", text)
+ for a, b in LOOKALIKE.items():
+ text = text.replace(a, b)
+ return [w for w in re.sub(r"[\[\]ˈˌ.,]", " ", text).split() if w]
+
+
+def broad(seg: str) -> str:
+ s = "".join(c for c in unicodedata.normalize("NFD", seg) if not unicodedata.combining(c) and c not in STRIP)
+ return s.replace("r", "ɹ").replace("ɾ", "ɹ")
+
+
+def segs_of(word: str) -> list[str]:
+ """Segments with diacritics attached; affricates and vowel + offglide diphthongs kept whole."""
+ s, out, i = unicodedata.normalize("NFD", word), [], 0
+ while i < len(s):
+ ch = s[i]
+ i += 1
+ if ch in ("t", "d") and s[i:i + 1] in ("ʃ", "ʒ"):
+ ch += s[i]
+ i += 1
+ while i < len(s) and (unicodedata.combining(s[i]) or s[i] in STRIP):
+ ch += s[i]
+ i += 1
+ out.append(ch)
+ merged, i = [], 0
+ while i < len(out):
+ if i + 1 < len(out) and broad(out[i]) + broad(out[i + 1]) in DIPHTHONGS:
+ merged.append(out[i] + out[i + 1])
+ i += 2
+ else:
+ merged.append(out[i])
+ i += 1
+ return merged
+
+
+def seg_cost(a: str, b: str) -> float:
+ a, b = broad(a), broad(b)
+ if a == b:
+ return 0.0
+ return 0.6 if (a[:1] in VOWELS) == (b[:1] in VOWELS) else 1.0
+
+
+def align(xs, ys, cost, gap: float):
+ n, m = len(xs), len(ys)
+ D = np.zeros((n + 1, m + 1))
+ D[:, 0] = np.arange(n + 1) * gap
+ D[0, :] = np.arange(m + 1) * gap
+ for i in range(1, n + 1):
+ for j in range(1, m + 1):
+ D[i, j] = min(D[i - 1, j - 1] + cost(xs[i - 1], ys[j - 1]), D[i - 1, j] + gap, D[i, j - 1] + gap)
+ pairs, i, j = [], n, m
+ while i > 0 or j > 0:
+ if i > 0 and j > 0 and np.isclose(D[i, j], D[i - 1, j - 1] + cost(xs[i - 1], ys[j - 1])):
+ pairs.append((i - 1, j - 1))
+ i, j = i - 1, j - 1
+ elif i > 0 and np.isclose(D[i, j], D[i - 1, j] + gap):
+ pairs.append((i - 1, None))
+ i -= 1
+ else:
+ pairs.append((None, j - 1))
+ j -= 1
+ return pairs[::-1]
+
+
+def to_class(unit: str, symbol: str) -> str:
+ b = broad(symbol)
+ if b[:2] in ("tʃ", "dʒ"):
+ return "other"
+ for key in (symbol, b, b[:2], b[:1]):
+ if key in CLASS[unit]:
+ return CLASS[unit][key]
+ return "other"
+
+
+def gold_tokens(an: Analyzer, canon: dict, speaker_file: Path):
+ """(orthographic labels of every transcribed word, [(label index, word, unit, gold symbol)])"""
+ twords = clean(speaker_file.read_text(encoding="utf-8"))
+
+ def word_cost(pw, tw):
+ a, b = canon.get(pw, list(pw)), segs_of(tw)
+ pairs = align(a, b, seg_cost, 1.0)
+ return sum(seg_cost(a[i], b[j]) if i is not None and j is not None else 1.0 for i, j in pairs) / max(len(a), len(b))
+
+ labels, golds = [], []
+ for pi, ti in align(PWORDS, twords, word_cost, 0.9):
+ if ti is None:
+ continue
+ if pi is not None and word_cost(PWORDS[pi], twords[ti]) < 0.75:
+ labels.append(PWORDS[pi])
+ else: # repeats take the label of the paragraph word they echo
+ best = min(set(PWORDS), key=lambda w: word_cost(w, twords[ti]))
+ labels.append(best if word_cost(best, twords[ti]) < 0.5 else None)
+ w = labels[-1]
+ if w in UNIT_OF:
+ unit = an.units[UNIT_OF[w]]
+ slot = an.slots(canon[w], unit)[0]
+ tsegs = segs_of(twords[ti])
+ sp = dict(align(canon[w], tsegs, seg_cost, 1.0))
+ golds.append((len(labels) - 1, w, unit.key, tsegs[sp[slot]] if sp.get(slot) is not None else "∅"))
+ return labels, golds
+
+
+def summarise(rows: list[dict], an: Analyzer) -> None:
+ for unit_key in CLASS:
+ rs = [r for r in rows if r["unit"] == unit_key and r["gold"] != "other"]
+ if not rs:
+ continue
+ acc = np.mean([r["gold"] == r["pred"] for r in rs])
+ conf = collections.defaultdict(collections.Counter)
+ for r in rs:
+ conf[r["gold"]][r["pred"]] += 1
+ print(f"\n{unit_key}: {len(rs)} tokens, {len({r['speaker'] for r in rs})} speakers, token accuracy {acc:.1%}")
+ for g in sorted(conf, key=lambda k: -sum(conf[k].values())):
+ print(f" gold {g}: {dict(conf[g].most_common())}")
+ sure = [r for r in rs if r["posterior"] >= 0.9]
+ if sure:
+ print(f" confident (p >= 0.9): {len(sure) / len(rs):.0%} of tokens, accuracy {np.mean([r['gold'] == r['pred'] for r in sure]):.1%}")
+ unit = an.units[unit_key]
+ words = sorted({r["word"] for r in rs})
+ winners = {}
+ for source in ("gold", "pred"):
+ counts = collections.Counter(r[source] for r in rs)
+ total = sum(counts.values())
+ cands = [Candidate(seg, seg, n, n / total) for seg, n in counts.most_common(5)]
+ assess(cands, unit, words, list(an.lexicons.values()), an.typology, Settings())
+ winners[source] = [c.segment for c in evaluate(cands).winners]
+ print(f" {'expert' if source == 'gold' else 'automatic':9s}: "
+ + ", ".join(f"{c.segment} {c.share:.0%}" for c in cands) + f" -> preferred {winners[source]}")
+ print(f" same preferred form: {winners['gold'] == winners['pred']}")
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--saa", default=str(SAA))
+ ap.add_argument("--out", default=str(BACKEND / "data" / "work" / "saa_rows.json"))
+ ap.add_argument("--calibrated", action="store_true", help="score with kb/calibration.json (default: raw scores)")
+ args = ap.parse_args(argv)
+ an = Analyzer()
+ settings = Settings(calibrated=args.calibrated)
+ canon = {}
+ for w in set(PWORDS):
+ prons = an.pronunciations(w) if (w in an.lexicons["britfone"] or w in an.lexicons["cmudict"]) else []
+ if not prons:
+ continue
+ unit = an.units[UNIT_OF[w]] if w in UNIT_OF else None
+ canon[w] = an.canonical(w, unit)
+ rows, t0 = [], time.time()
+ saa = Path(args.saa)
+ for txt in sorted((saa / "transcription_texts").glob("*.txt")):
+ spk = txt.stem
+ flac = saa / "flac" / f"{spk}.flac"
+ if spk.startswith("krio") or not flac.exists():
+ continue
+ labels, golds = gold_tokens(an, canon, txt)
+ audio = audio_io.load(flac)
+ spans = an.aligner.align(audio, " ".join(l for l in labels if l))
+ span_of, k = {}, 0
+ for li, l in enumerate(labels):
+ if l:
+ span_of[li] = spans[k] if k < len(spans) else None
+ k += 1
+ rec = Recording(flac.name, audio, speaker=spk)
+ for li, w, unit_key, gseg in golds:
+ span = span_of.get(li)
+ if span is None:
+ continue
+ unit = an.units[unit_key]
+ ev = an._evidence(audio, span.start, span.end)
+ slot = an.slots(canon[w], unit)[0]
+ tok, _ = an._token(rec, w, canon[w], slot, unit, ev, span.start, span.end, settings)
+ rows.append({"speaker": spk, "word": w, "unit": unit_key, "gold_symbol": gseg, "gold": to_class(unit_key, gseg),
+ "label": tok.variant, "pred": to_class(unit_key, tok.variant), "posterior": tok.posterior,
+ "nll": tok.nll, "heard": tok.heard})
+ print(f"{spk}: {sum(r['speaker'] == spk for r in rows)} tokens ({time.time() - t0:.0f}s)", flush=True)
+ out = Path(args.out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(json.dumps(rows, ensure_ascii=False, indent=0), encoding="utf-8")
+ summarise(rows, an)
+ print("\nrows written to", out)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/backend/eval/saa_west_african_subset.tsv b/backend/eval/saa_west_african_subset.tsv
new file mode 100644
index 0000000000000000000000000000000000000000..cba3e95ebbbb96ecfc3611af5133a128179e7f01
--- /dev/null
+++ b/backend/eval/saa_west_african_subset.tsv
@@ -0,0 +1,37 @@
+sample native_language alternative_native_language city state_or_province country age gender onset_age english_residence length_of_residence learning_style has_text_ipa has_gif_ipa mp3_bytes flac_bytes txt_url mp3_url flac_url notes
+ebira1 ebira okene nigeria 35 male 3 usa 7 naturalistic True True 527045 1318965 https://osf.io/download/6a7e01894704944492a592a0/ https://osf.io/download/698ab1e2a77edfa196dfc62b/ https://osf.io/download/6a0fd719cec9ad87a5f92bed/
+edo1 edo benin city nigeria 25 male 6 usa 4 academic True True 588903 1243387 https://osf.io/download/6a7e018c3cb996957c0021a9/ https://osf.io/download/698ab1e6b1a0f415a5dfc45f/ https://osf.io/download/6a0fd71ea2aab73e4af92af1/
+english503 english NULL benin city NULL nigeria 29 female 0 nigeria, usa 25 naturalistic False False 589321 1587538 https://osf.io/download/698ab81a3d9d151d12e24aaa/ https://osf.io/download/6a0fdf08beb193cbd2aba6cd/ 7 may 2013. residence: 12 years usa
+fulfulde_adamawa1 fulfulde adamawa fulani hong adamawa nigeria 48 male 8 nigeria, usa 48 academic True False 384939 771155 https://osf.io/download/6a7e054f43e20f0d76002245/ https://osf.io/download/698b4a79a5c9a9cacac72adb/ https://osf.io/download/6a0fe6463e488459c9417871/ 24 november 2008. residence: 28 years nigeria, 20 years usa
+hausa1 hausa NULL kano NULL nigeria 49 male 7 nigeria, usa 28 academic True True 670823 1227186 https://osf.io/download/6a7e0654724d02e5bb0021a0/ https://osf.io/download/698b4cad52d60e8bd6c734c2/ https://osf.io/download/6a0fe8a8c11001e42eaba9c4/ 19 november 2008. residence: 28 years nigeria, 2 months usa.
+hausa2 hausa NULL bauchi NULL nigeria 46 male 10 nigeria, usa 46 academic True True 449305 904845 https://osf.io/download/6a7e0656ba629dc18fd90e32/ https://osf.io/download/698b4cb588e45fde42c729fb/ https://osf.io/download/6a0fe8b72e3deb8a9caba800/ 24 november 2008. residence: 29 years nigeria, 17 years usa
+hausa3 hausa NULL malumfashi NULL nigeria 47 female 6 nigeria, usa 47 academic True True 509909 990178 https://osf.io/download/6a7e0659195ece5ebda591a5/ https://osf.io/download/698b4cba3a7f417185dfc446/ https://osf.io/download/6a0fe8bfc11001e42eaba9cd/ 24 november 2008. residence: 43 years nigeria, 4 years usa
+hausa4 hausa NULL kano NULL nigeria 62 male 10 nigeria, uk, usa 62 academic True True 537912 1015694 https://osf.io/download/6a7e065c38a5fa09a898087b/ https://osf.io/download/698b4cbfd518dfa77be250dd/ https://osf.io/download/6a0fe8c62308112b83f92863/ 24 november 2008. residence: 40 years nigeria, 2 years uk, 20 years usa
+hausa5 hausa NULL maine NULL niger 43 female 12 niger, usa 13.5 academic True True 474800 892135 https://osf.io/download/6a7e06630b03c7059d0ca235/ https://osf.io/download/698b4cc73a7f417185dfc44c/ https://osf.io/download/6a0fe8cca2b657d4fff92855/ 25 november 2008. residence: 1.5 years niger, 12 years usa
+hausa6 hausa NULL kano NULL nigeria 48 male 6 nigeria, usa 48 academic True True 479816 889727 https://osf.io/download/6a7e0665f5aa6981b00189e7/ https://osf.io/download/698b4cca88e45fde42c72a1b/ https://osf.io/download/6a0fe8d3a2b657d4fff92859/ 25 november 2008. residence: 46 years nigeria, 2 years usa.
+hausa7 hausa NULL sokoto NULL nigeria 52 male 7 nigeria, usa 52 academic True True 390790 730455 https://osf.io/download/6a7e0668eab78d349f002252/ https://osf.io/download/698b4ccea514910b92e25774/ https://osf.io/download/6a0fe8d9a2b75db1da4177d0/ 25 november 2008. residence: 20 years nigeria, 32 years usa.
+hausa8 hausa NULL katsina NULL nigeria 30 male 7 usa 4 academic True True 499460 949935 https://osf.io/download/6a7e066c195ece5ebda591af/ https://osf.io/download/698b4cd26892d27b28dfcaaa/ https://osf.io/download/6a0fe8e1a2b657d4fff9285d/ 39938
+hausa9 hausa NULL kaltungo gombe nigeria 43 male 5 nigeria, uk, usa 43 naturalistic True True 480384 1107283 https://osf.io/download/6a7e066ecb0d3adeb6002189/ https://osf.io/download/698b4cd66892d27b28dfcaac/ https://osf.io/download/6a0fe8e89da90957ababa832/ 4 december 2010. residence: 34 yrs. nigeria, 5 yrs uk, 4 yrs usa
+hausa10 hausa NULL kaduna NULL nigeria 29 female 3 NULL 0 academic False False 702336 1997116 https://osf.io/download/698b4cb03a7f417185dfc438/ https://osf.io/download/6a0fe8ae2308112b83f9285e/ 18 april 2018. LING507
+ibibio1 ibibio NULL uyo akwa ibom nigeria 52 male 3 nigeria, uk, usa 52 naturalistic True True 443871 820940 https://osf.io/download/6a7e06c9e43194be2fa59239/ https://osf.io/download/698b4dd76892d27b28dfcb60/ https://osf.io/download/6a0fea5d3f5a6ce862f929be/ 11 july 2009. residence: nigeria 39 years; uk 1 year, usa 12 years
+ibibio2 ibibio NULL abak akwa ibom nigeria 45 female 4 nigeria, uk, usa 45 naturalistic True True 527463 1044313 https://osf.io/download/6a7e06cbff9ce4e82fd90e24/ https://osf.io/download/698b4ddb0c2eaf0704c72fa1/ https://osf.io/download/6a0fea6241fe9894a6f92b60/ 11 july 2009. residence: nigeria 27 years; uk 5 years, usa 13 years
+ibibio3 ibibio NULL lagos NULL nigeria 36 male 6 usa 13 academic False False 499878 1277071 https://osf.io/download/698b4dde0cbfd21038dfcfdc/ https://osf.io/download/6a0fea66a2b657d4fff92969/ 41225
+igbo1 igbo imo state imo state nigeria 23 female 12 usa 0.4 academic True True 635714 1752264 https://osf.io/download/6a7e06d8bed7d0ff77d90e0e/ https://osf.io/download/698b4df03a7f417185dfc579/ https://osf.io/download/6a0fea812308112b83f928cc/
+igbo2 igbo kafanchan nigeria 65 male 14 uk 7 academic True True 542510 981056 https://osf.io/download/6a7e06db443f9565650189e4/ https://osf.io/download/698b4df53a7f417185dfc57d/ https://osf.io/download/6a0fea88a2b657d4fff92978/ july 2007._x000D_english is a national language of nigeria
+igbo3 igbo NULL lagos NULL nigeria 35 male 5 nigeria, usa 35 academic True True 363205 703090 https://osf.io/download/6a7e06dead04cc036fa59237/ https://osf.io/download/698b4df9a34d8d82d3e2505d/ https://osf.io/download/6a0fea8cc11001e42eabaac0/ 24 november 2008. residence: 2820 years nigeria, 15 years usa
+igbo4 igbo NULL onitsha NULL nigeria 22 male 6 usa 17 naturalistic False False 663718 752104 https://osf.io/download/698b4dfd88e45fde42c72c69/ https://osf.io/download/6a0fea92c11001e42eabaac6/ 12 november 2018. LING306
+kanuri1 kanuri NULL kaduna NULL nigeria 48 female 6 nigeria, usa 48 academic True True 487757 912886 https://osf.io/download/6a7e07a3724d02e5bb002215/ https://osf.io/download/698b4ff898092578f4dfca42/ https://osf.io/download/6a7b3f2ca20236b07712d4d6/ 25 november 2008. residence: 24 years nigeria, 24 years usa.
+krio1 krio freetown sierra leone 46 female 5 usa 16 academic True True 524537 1696885 https://osf.io/download/6a7e0accbed39f98ffa593bc/ https://osf.io/download/698b527ac61361a730c7298e/ https://osf.io/download/6a7b505e1c895c0aea6a5a77/
+krio2 krio freetown sierra leone 26 male 5 sierra leone, usa 26 naturalistic True True 533732 965770 https://osf.io/download/6a7e0acf330bde30b9a5920a/ https://osf.io/download/698b527ec61361a730c72991/ https://osf.io/download/6a7b506350dc60b9c612d326/ residence: 14 years sierra leone; 12 years usa
+krio3 krio NULL freetown NULL sierra leone 21 female 5 sierra leone, usa 18 naturalistic True True 534150 1049215 https://osf.io/download/6a7e0ad258506a2bdb0021d5/ https://osf.io/download/698b528370b0e3cc9be25011/ https://osf.io/download/6a7b5a1b70d3f567b912d310/ 39859
+krio4 krio NULL freetown NULL sierra leone 48 female 7 usa 30 academic True True 524955 1120154 https://osf.io/download/6a7e0ad582ce4a55ada5921e/ https://osf.io/download/698b52876892d27b28dfd065/ https://osf.io/download/6a7b5a23ec598b782a692b5e/ 39869
+krio5 krio NULL freetown NULL sierra leone 36 male 6 sierra leone, usa 26 naturalistic True True 511999 1456183 https://osf.io/download/6a7e0ad894b385b8a200223f/ https://osf.io/download/698b52902ed7550359e24d94/ https://osf.io/download/6a7b5a2a20315170bf6a5a56/ 17 may 2009. residence: sierra leone 20 years; usa 6 years
+krio6 krio NULL freetown NULL sierra leone 26 female 3 sierra leone, usa 26 academic False False 537494 1630939 https://osf.io/download/698b52952ed7550359e24d9c/ https://osf.io/download/6a7b5a3253a77753f96a5bbe/ 20 december 2014. residence: 24 yrs. sierra leone, 2 yrs. usa.
+yoruba1 yoruba cotonou benin 20 male 20 usa 0.25 academic True True 622758 1220698 https://osf.io/download/6a7e127ee474f19774002397/ https://osf.io/download/698d787e51db31ca2ce256e5/ https://osf.io/download/6a7bf1a3e64566c2a6241ffb/
+yoruba2 yoruba ibadan oyo nigeria 40 female 2 usa, uk 8.5 academic True True 480652 957283 https://osf.io/download/6a7e1281c85bb508a1d90f71/ https://osf.io/download/698d78824ed52ae49cdfcfd1/ https://osf.io/download/6a7bf1a6e64566c2a6242000/ 7 july 2007._x000D_7 years usa, 1.5 years uk._x000D_english is a national language of nigeria
+yoruba3 yoruba lagos nigeria 46 female 5 usa 34 academic True True 561736 1098246 https://osf.io/download/6a7e12847ebdf08df7d9115b/ https://osf.io/download/698d78853ad9ce0284dfcb99/ https://osf.io/download/6a7bf1ab6aa53c9b4db1f633/ 39264
+yoruba4 yoruba lagos nigeria 46 male 12 nigeria, usa 15 academic True True 550033 1021950 https://osf.io/download/6a7e1286ecd43d36240021fe/ https://osf.io/download/2t6sp/ https://osf.io/download/6a7bf1b17905a60fefb1f6ae/ 3 february 2008_x000D_residence: nigeria for 31 years
+yoruba5 yoruba NULL ibadan NULL nigeria 47 female 2 nigeria, usa 47 naturalistic False False 663300 1247271 https://osf.io/download/698d788dadec0d7ce3e24ddb/ https://osf.io/download/6a7bf1b7c1aeee1b9fe1cdc6/ 12 november 2014. LING306
+yoruba6 yoruba NULL akure NULL nigeria 29 male 3 usa 1 academic False False 868518 966242 https://osf.io/download/698d7891f97f84d3f3c733bd/ https://osf.io/download/6a7bf1bce64566c2a624203b/ 5 sept. 2019. LING523
+yoruba7 yoruba NULL ibadan oyo nigeria 30 male 5 nigeria 30 naturalistic False False 781582 917082 https://osf.io/download/698d7894f97f84d3f3c733bf/ https://osf.io/download/6a7bf1c15d45e0c713241f83/ 20 december 2019. LING523
+yoruba8 yoruba NULL ibadan oyo nigeria 21 male 2 nigeria, usa 21 academic False False 792679 992137 https://osf.io/download/698d7898f97f84d3f3c733c5/ https://osf.io/download/6a7bf1c5935acd7f01e1ca7f/ 18 november 2021. LING306
diff --git a/backend/eval/slr70.py b/backend/eval/slr70.py
new file mode 100644
index 0000000000000000000000000000000000000000..605487b0f8aff94cd1481bdaa5aaae8fdde97c6b
--- /dev/null
+++ b/backend/eval/slr70.py
@@ -0,0 +1,83 @@
+"""Prepare SLR70 (Google's crowdsourced Nigerian English, CC BY-SA 4.0) inputs for PG analyses.
+
+Downloads the transcript lists, picks utterances that contain words of each unit (capped per word), fetches
+only those WAVs from the remote zips with HTTP range requests, and writes words/files/transcripts/speakers
+lists per unit under data/work/slr70/inputs//.
+
+python -m eval.slr70 [--units TH-voiceless,TH-voiced,NURSE] [--cap 200]
+"""
+from __future__ import annotations
+
+import argparse
+import collections
+import os
+import re
+import urllib.request
+from pathlib import Path
+
+from pg import lexicon
+from pg.pipeline import RESOURCES
+from pg.tenets import load_units
+
+WORK = Path(__file__).resolve().parents[1] / "data" / "work" / "slr70"
+MIRROR = "https://openslr.elda.org/resources/70"
+WEAK = {"the", "her", "were", "per", "with", "within", "without"} # reduced forms, or
that may be voiced or not
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--units", default="TH-voiceless,TH-voiced,NURSE")
+ ap.add_argument("--cap", type=int, default=200, help="max utterances per word (common words like 'that' are capped)")
+ ap.add_argument("--min-tokens", type=int, default=5)
+ args = ap.parse_args(argv)
+ WORK.mkdir(parents=True, exist_ok=True)
+ text = {}
+ for g in ("male", "female"):
+ tsv = WORK / f"line_index_{g}.tsv"
+ if not tsv.exists():
+ urllib.request.urlretrieve(f"{MIRROR}/line_index_{g}.tsv", tsv)
+ for line in tsv.read_text(encoding="utf-8").splitlines():
+ fid, t = line.split("\t", 1)
+ text[fid] = t
+ lexs = lexicon.load_default(RESOURCES, names=("britfone", "cmudict"))
+ units = load_units()
+ keep = set()
+ for key in args.units.split(","):
+ unit = units[key]
+ symbols = lexicon.same_phoneme(unit.phoneme)
+ chosen = collections.defaultdict(list)
+ for fid, t in text.items():
+ for w in set(re.findall(r"[a-z']+", t.lower().replace("’", "'"))):
+ if w in WEAK or len(chosen[w]) >= args.cap:
+ continue
+ prons = lexs["britfone"].pronunciations(w) or lexs["cmudict"].pronunciations(w)
+ if prons and any(s in symbols for p in prons for s in p):
+ chosen[w].append(fid)
+ chosen = {w: ids for w, ids in chosen.items() if len(ids) >= args.min_tokens}
+ fids = sorted({f for ids in chosen.values() for f in ids})
+ keep |= set(fids)
+ d = WORK / "inputs" / key
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "words.txt").write_text(",".join(sorted(chosen)))
+ (d / "files.txt").write_text("\n".join(str(WORK / "wav" / f"{f}.wav") for f in fids))
+ (d / "transcripts.tsv").write_text("\n".join(f"{f}.wav\t{text[f]}" for f in fids))
+ (d / "speakers.tsv").write_text("\n".join(f"{f}.wav\t{'_'.join(f.split('_')[:2])}" for f in fids))
+ print(f"{key}: {len(chosen)} words, {sum(len(v) for v in chosen.values())} word tokens, {len(fids)} utterances")
+ from remotezip import RemoteZip
+
+ (WORK / "wav").mkdir(exist_ok=True)
+ got = 0
+ for z in ("en_ng_male.zip", "en_ng_female.zip"):
+ with RemoteZip(f"{MIRROR}/{z}") as rz:
+ for info in rz.infolist():
+ stem = os.path.splitext(os.path.basename(info.filename))[0]
+ dest = WORK / "wav" / f"{stem}.wav"
+ if stem in keep and not dest.exists():
+ with rz.open(info) as src, open(dest, "wb") as out:
+ out.write(src.read())
+ got += 1
+ print(f"fetched {got} new clips; {len(list((WORK / 'wav').glob('*.wav')))} in {WORK / 'wav'}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/backend/finetune_model.py b/backend/finetune_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..a73d8dbeccc8445003342d3e35c2cf5a83a143fb
--- /dev/null
+++ b/backend/finetune_model.py
@@ -0,0 +1,148 @@
+from datasets import load_dataset, Audio
+from transformers import (
+ Wav2Vec2ForCTC,
+ Wav2Vec2Processor,
+ TrainingArguments,
+ Trainer,
+ TrainerCallback,
+)
+from dataclasses import dataclass
+from typing import Any, Dict, List, Union
+
+import math
+import re
+
+import jiwer
+import numpy as np
+import torch
+
+BASE_MODEL = "facebook/wav2vec2-base-960h"
+
+
+def clean_text(text):
+ # the base model's vocabulary is upper-case letters, apostrophe and "|"; lower-case letters would all become
+ text = text.upper().replace("’", "'").replace("-", " ")
+ text = re.sub(r"[^A-Z' ]+", '', text)
+ return re.sub(r"\s+", " ", text).strip()
+
+
+dataset = load_dataset(
+ "csv",
+ data_files={"train": "data/train.csv", "validation": "data/val.csv"},
+ delimiter=","
+)
+# digits are read out in the audio but can't be spelled by the vocabulary; drop those utterances
+dataset = dataset.filter(lambda b: not re.search(r"\d", b["transcript"]))
+
+dataset = dataset.cast_column("path", Audio(sampling_rate=16000))
+
+processor = Wav2Vec2Processor.from_pretrained(BASE_MODEL)
+model = Wav2Vec2ForCTC.from_pretrained(
+ BASE_MODEL,
+ ctc_loss_reduction="mean",
+ ctc_zero_infinity=True,
+ pad_token_id=processor.tokenizer.pad_token_id,
+)
+# transformers leaves the SpecAugment mask vector uninitialised when loading this checkpoint (it is not
+# saved in it); NaNs there turn every training loss into NaN, so initialise it as wav2vec2 does
+torch.nn.init.uniform_(model.wav2vec2.masked_spec_embed)
+assert not torch.isnan(model.wav2vec2.masked_spec_embed).any()
+model.freeze_feature_encoder()
+
+
+def prepare_batch(batch):
+ audio = batch["path"]
+ batch["input_values"] = processor(audio["array"], sampling_rate=16000).input_values[0]
+ batch["input_length"] = len(batch["input_values"])
+ batch["labels"] = processor(text=clean_text(batch["transcript"])).input_ids
+ return batch
+
+
+dataset = dataset.map(prepare_batch, remove_columns=dataset["train"].column_names)
+unk = processor.tokenizer.unk_token_id
+unk_share = np.mean([i == unk for ids in dataset["train"]["labels"] for i in ids])
+assert unk_share < 0.01, f"{unk_share:.0%} of label tokens are ; the labels do not match the vocabulary"
+
+
+@dataclass
+class DataCollatorCTCWithPadding:
+ processor: Wav2Vec2Processor
+ padding: Union[bool, str] = True
+
+ def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
+ input_features = [{"input_values": f["input_values"]} for f in features]
+ label_features = [{"input_ids": f["labels"]} for f in features]
+
+ batch = self.processor.pad(
+ input_features,
+ padding=self.padding,
+ return_tensors="pt"
+ )
+ labels_batch = self.processor.tokenizer.pad(
+ label_features,
+ padding=self.padding,
+ return_tensors="pt"
+ )
+
+ labels = labels_batch["input_ids"].masked_fill(labels_batch["input_ids"] == self.processor.tokenizer.pad_token_id, -100)
+ batch["labels"] = labels
+ return batch
+
+
+def compute_metrics(pred):
+ pred_ids = np.argmax(pred.predictions, axis=-1)
+ label_ids = pred.label_ids.copy()
+ label_ids[label_ids == -100] = processor.tokenizer.pad_token_id
+ hyp = processor.batch_decode(pred_ids)
+ ref = processor.batch_decode(label_ids, group_tokens=False)
+ return {"wer": jiwer.wer(ref, hyp), "cer": jiwer.cer(ref, hyp)}
+
+
+class StopOnBrokenTraining(TrainerCallback):
+ # a NaN gradient norm or a logged loss of exactly 0 means no real update is happening
+ def on_log(self, args, state, control, logs=None, **kwargs):
+ logs = logs or {}
+ if "loss" in logs and (logs["loss"] == 0 or math.isnan(logs.get("grad_norm", 0.0))):
+ raise RuntimeError(f"training is broken at step {state.global_step}: {logs}")
+
+
+data_collator = DataCollatorCTCWithPadding(processor=processor, padding=True)
+
+training_args = TrainingArguments(
+ output_dir="./wav2vec2-nigerian-english",
+ group_by_length=True,
+ length_column_name="input_length",
+ per_device_train_batch_size=8,
+ per_device_eval_batch_size=8,
+ eval_strategy="steps",
+ num_train_epochs=10,
+ fp16=torch.cuda.is_available(),
+ save_steps=200,
+ eval_steps=200,
+ logging_steps=50,
+ learning_rate=1e-4,
+ warmup_steps=500,
+ save_total_limit=2,
+ load_best_model_at_end=True,
+ metric_for_best_model="wer",
+ greater_is_better=False,
+ push_to_hub=False,
+)
+
+trainer = Trainer(
+ model=model,
+ data_collator=data_collator,
+ args=training_args,
+ train_dataset=dataset["train"],
+ eval_dataset=dataset["validation"],
+ processing_class=processor,
+ compute_metrics=compute_metrics,
+ callbacks=[StopOnBrokenTraining()],
+)
+
+print("before fine-tuning:", trainer.evaluate())
+trainer.train()
+print("after fine-tuning:", trainer.evaluate())
+
+trainer.save_model("./wav2vec2-nigerian-english")
+processor.save_pretrained("./wav2vec2-nigerian-english")
diff --git a/backend/pg/README.md b/backend/pg/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..7deced392802c16e90199fb9849ff1ef8c5d6e33
--- /dev/null
+++ b/backend/pg/README.md
@@ -0,0 +1,116 @@
+# Automated Preference Grammar (`pg`)
+
+Automates Ugorji's Preference Grammar (PG): from recordings of target words spoken by many speakers, it finds
+which variants of a sound speakers actually produce, clusters them, ranks the attested variants on the six PG
+tenets, and outputs the operability table and the preferred form.
+
+```
+recordings + target word(s) + tenet ranking
+ -> locate the words: whole clip | forced alignment to a transcript | speech recognition audio.py align.py asr.py
+ -> which variant of the unit each token realises (acoustic forced choice + open set) phones.py
+ -> primary clusters (variants) and secondary clusters (acoustic sub-variants) cluster.py
+ -> candidates (attested >= 3 tokens from >= 2 speakers) with marks for the six tenets tenets.py
+ -> operability table (strict domination, as in OT) -> preferred form, tiers, stability ot.py pipeline.py
+ -> CSV / VTT / JSON / HTML outputs, and a listening page for human checking report.py review.py
+```
+
+## Why not ASR + text-to-IPA
+
+Converting recognised *words* to IPA (e.g. eSpeak) returns the dictionary pronunciation, so every speaker's
+"think" comes out as /θɪŋk/ whatever they said. PG's input is the set of *attested* forms, so the variant has to
+come from the audio. `phones.py` uses a multilingual CTC phone recogniser
+(`facebook/wav2vec2-xlsr-53-espeak-cv-ft`) and makes a forced choice (the GOP-SF / PP-AF method of the
+mispronunciation-detection literature): each candidate pronunciation of the word ([θɪŋk], [tɪŋk], [sɪŋk]…)
+is scored by its CTC likelihood against the audio, over the usual spellings of each variant ([t]/[t̪]), with
+the word's other vowels allowed to vary so an accent feature elsewhere cannot bias the decision. Low-confidence
+tokens are flagged for listening. (An open-set option also scores the phones the model hears most in the slot, so a
+realisation outside the candidate set is reported under its own symbol; it is off by default because it never
+improved accuracy on the gold set.)
+
+## Measured accuracy (Nigerian English): what is and is not validated
+
+Development gold set: the 22 Nigerian speakers of the Speech Accent Archive, narrow IPA by trained phoneticians
+(`python -m eval.saa_gold`, then `python -m eval.fit_calibration`). Figures are for the deployed closed-set
+classifier; calibration is used only where it raised kappa on held-out speakers with a bootstrap interval above
+zero (only /ð/). Kappa measures agreement beyond chance: a classifier that always answers the commonest variant
+scores 0, however high its accuracy.
+
+| Unit | Tokens | Accuracy (95% CI by speaker) | Majority baseline | Kappa | Error in variant shares | Status |
+|---|---|---|---|---|---|---|
+|
/ð/ (calibrated) | 129 | 81% | 53% | 0.64 | 0.09 | validated |
+| KIT | 112 | 81% (73–89) | 76% | 0.55 | 0.08 | validated |
+| NURSE ("her") | 86 | 43% (24–63) | 41% | 0.23 | 0.41 | **not validated** |
+| GOAT | 68 | 72% (60–84) | 87% | 0.16 | 0.13 | **not validated** |
+| FACE | 89 | 54% (41–65) | 72% | 0.13 | 0.17 | **not validated** |
+| FLEECE | 183 | 90% (86–94) | 92% | 0.06 | 0.05 | **not validated** |
+
+For the not-validated units the acoustic evidence the phone model gives is weak (a class-balanced calibration does
+not rescue them either), so analyses of those sounds carry a warning and their shares should be checked by ear.
+Known limits, from an independent QA review:
+
+- **Same paragraph, new speakers only.** Every speaker reads the same text, so these numbers show transfer to new
+ speakers, not to new words; NURSE is tested only on "her", often a weak form. Treat the set as development data
+ and validate on 150–300 double-labelled tokens of other words before publishing results.
+- **The model leans towards dictionary forms.** It was trained on eSpeak transcriptions of Common Voice text,
+ and its errors run towards RP (gold [d] heard as [ð] 36 times, the reverse once); its vocabulary has [t̪] but no
+ [d̪]. Raw shares therefore overstate the RP variant; the /ð/ calibration corrects most of this.
+- **"Same preferred form" is not an accuracy test.** With the default knowledge base the RP form wins NURSE, KIT
+ and FLEECE whenever it is attested at all, and TH, GOAT and FACE hinge only on whether one share passes 20%.
+ The stability figure redraws each token's variant from its posterior and resamples speakers, so it reflects
+ classifier uncertainty, but only as far as the posteriors are honest (they are for the validated units).
+- **Acoustic sub-clusters and the contrast matrix are exploratory**: they barely separate the variants.
+- On Mandarin-L1 learners (speechocean762) TH/DH accuracy was 47%/53%: do not assume transfer to other accents.
+
+## How each tenet is computed
+
+The PG sources assign marks by analyst judgement and give no algorithm. These rules are a documented
+operationalisation that reproduces both evaluations Ugorji published, mark for mark:
in "think"
+(Ugorji 2010: 58) and the GOAT vowel (reported by Jowitt 2015: 8) (`tests/test_tenets.py`).
+
+| Tenet | Mark when | Evidence |
+|---|---|---|
+| I-Ac | the variant is outside the internationally accepted realisations of the unit (e.g. /θ/: θ, t, t̪, f) | `kb/units.json` (RP/GA, established L1-variety norms, Lingua Franca Core, ICAO) |
+| ContR | the variant neutralises a contrast crucial to international intelligibility: consonant contrasts except those of θ/ð, vowel length, the NURSE quality | Lingua Franca Core (Jenkins 2000; Walker 2010) |
+| FreQ | the variant's share of tokens (or of speakers' usage) is below 20% | the analysed recordings |
+| DisaM | the variant merges the unit with another RP phoneme so that common words sound alike (the target word's homophones, or minimal pairs among the 20,000 most frequent words) | CMUdict + Britfone, `wordfreq` |
+| Pho-S | the variant is absent from at least two of Hausa, Igbo, Yoruba, or occurs in under 15% of the world's languages | PHOIBLE 2.0 |
+| Ped-C | the variant is absent from those languages and used by under 20% of the speakers analysed (no local model to teach from), or experts list it as difficult | PHOIBLE + data |
+
+These marks are configurable defaults pending the PG experts' judgement, not PG's own verdicts: the rules were chosen so that the only two published evaluations come out right (a fit to seven candidates, not a validation), and conventions decide some outcomes. For example, Nigerian [e] and [o] are treated as non-RP phonemes; under Gimson's notation, where RP DRESS is /e/, FACE [e] would merge with DRESS and lose to [eɪ]. The open questions are listed in `RESEARCH.md` §6.
+
+Default ranking `I-Ac >> ContR >> FreQ >> DisaM >> Pho-S >> Ped-C`. Experts can override any mark
+(`Settings.overrides`, e.g. `{"t|DisaM": 0}`), re-rank, pool tenets into one stratum (`"I-Ac, ContR >> FreQ"`),
+or delete tenets. Results depend on who was recorded: FreQ measured on less-educated speech can flip "think"
+to [t] (θ ≈ 16% there; Akande 2005), so the analysis reports how often the preferred form wins when the
+speakers are resampled (`stability`). Losing candidates are classed as allophones of the formal inventory
+(no I-Ac or ContR mark) or as the outer norm.
+
+## Use
+
+```bash
+# single-word recordings (one file per speaker), unit inferred from the word
+python -m pg --words think --audio recordings/*.wav --out results/
+# sentences with transcripts (TSV: file nametranscript), a lexical set, a different ranking
+python -m pg --words bird,work,girl --unit NURSE --audio clips/*.wav --transcripts transcripts.tsv \
+ --speakers speakers.tsv --ranking "FreQ >> I-Ac >> ContR >> DisaM >> Pho-S >> Ped-C" --out results/
+# unscripted audio (podcasts, interviews): words are found by speech recognition
+python -m pg --words think,three,thing --unit TH-voiceless --asr --audio episode1.mp3 --out results/
+# listen to the tokens and label them, then measure accuracy against your labels
+python -m pg.review export results/analysis.json recordings/*.wav --out review/
+python -m pg.review score results/analysis.json labels.csv
+```
+
+The API (`app.py`) exposes `GET /pg/units` and `POST /pg/analyze` with the same options.
+
+Outputs: `operability_table.csv`, `tokens.csv` (every token with variant, confidence, clusters),
+`subclusters.csv` (members of each sub-cluster; the phoneme under study is at cell (0,0)),
+`contrast_matrix.csv` (cosine similarity between variant clusters), one `.vtt` per recording,
+`analysis.json`, and `report.html`.
+
+## Setup
+
+`pip install -r requirements.txt` (on an Intel Mac: `requirements-tested.txt`, which pins the last
+PyTorch with Intel wheels). The lexicons download on first use (`python -m pg.kb.fetch`); models download from
+Hugging Face. `kb/typology.json` is built from PHOIBLE by `python -m pg.kb.build_typology`.
+Tests: `pytest` in `backend/`. Reproduce the evaluation: `python -m eval.fetch_saa`, `python -m eval.saa_gold`, `python -m eval.fit_calibration` (add `--write` to refresh `kb/calibration.json` and the validation status in `kb/units.json`); SLR70 inputs: `python -m eval.slr70`.
diff --git a/backend/pg/RESEARCH.md b/backend/pg/RESEARCH.md
new file mode 100644
index 0000000000000000000000000000000000000000..dda8a82dc71dbfa52f05d8c424b60b74515bacd0
--- /dev/null
+++ b/backend/pg/RESEARCH.md
@@ -0,0 +1,90 @@
+# Research notes behind the `pg` pipeline
+
+Condensed from three research passes (October 2026): the Preference Grammar sources, open data, and
+phone-recognition models. "[S]" = read in a source; "[P]" = our proposal, not in any PG source.
+
+## 1. Preference Grammar as published
+
+Sources actually read: Avram (2014) review of Ugorji (2010), *BWPL* XVI(1): 119–121; Jowitt (2015) "Nigerian
+Received Pronunciation", REAL Studies 9: 3–13 (publisher preview); Benjamin-Ohwodede & Osewa (2023) *Marang* 36:
+61–78 (Konglish, 9 tableaux); Benjamin-Ohwodede & Ugorji (2026) *JOLLS* 15(2): 239–248 (Naijá). Not accessible:
+Ugorji (2010) *Nigerian English Phonology: A Preference Grammar* (Peter Lang), Ugorji (2013) in *JEIL* 8(2), the
+"Ugorji 2022" title.
+
+- [S] PG evaluates contending sounds with Optimality-Theory machinery: six parameters ranked
+ I-Ac >> ContR >> FreQ >> DisaM >> Pho-S >> Ped-C, violable, the winner joins the normative inventory
+ (Jowitt 2015: 8). Candidates are attested surface forms only (no underlying forms, no GEN).
+- [S] Evaluation is **strict domination**, not counting marks: in Konglish Table 12, θ wins with three marks over
+ s with two because s violates I-Ac. Ties are broken by rank.
+- [S] No source gives an algorithm, threshold or numeric "operability" index; marks are analyst judgement
+ ("descriptive and non-numerical"). Jowitt (2015: 9) asks on what basis I-Ac is assigned and how candidates
+ enter the list. Ugorji (2010: 80): evaluation "need not be exhausted", so blank cells in published tables
+ may mean "not evaluated".
+- [S] Published evaluations by Ugorji:
in *think* (2010: 58): tɪŋk {DisaM}, sɪŋk {I-Ac, FreQ, DisaM},
+ ⇒θɪŋk {Pho-S}, zɪŋk {I-Ac, FreQ, DisaM}. GOAT (via Jowitt 2015: 8): /o/ satisfies all six and wins; /əʊ/
+ violates FreQ, Pho-S, Ped-C; /ɒ/ (phonetically [ɔ]) violates I-Ac, ContR, FreQ, DisaM.
+- [S] Output classes (Benjamin-Ohwodede & Osewa 2023): formal standard (winner), allophones of the formal
+ inventory, informal/outer norm, developmental/regional forms. The sources apply these inconsistently.
+- [S] For Naijá, I-Ac is judged against Naijá itself, so TH-stopping wins there (B-O & Ugorji 2026): the
+ reference norm is a parameter of the analysis.
+
+## 2. The operationalisation used here [P]
+
+Chosen because it reproduces both Ugorji evaluations exactly (`tests/test_tenets.py`); every threshold is a
+setting, every mark can be overridden.
+
+- I-Ac: accept-sets per unit (θ → θ, t, t̪, f): RP/GA plus realisations that are established norms in L1
+ varieties (stopping in Irish, Caribbean, Liberian English; fronting in London) or sanctioned in ICAO
+ "airspeak". The Lingua Franca Core alone cannot decide: Jenkins (2000) treats /θ ð/ as non-core and
+ weighs [t d], [f v], [s z] without choosing.
+- ContR: the variant neutralises a contrast the LFC treats as core (consonants except θ/ð; vowel length;
+ the NURSE quality). This is the least settled tenet: the Konglish tableaux contradict every rule tried.
+- FreQ: share below 20%. **The population decides results**: ICE-Nigeria word-initial /θ/ is θ 47.2%,
+ t 48.8%, s 4.0%, z 0 (Oyebola, Ho & Li 2019), but among Yoruba undergraduates θ is about 16% (Akande 2005),
+ where *think* flips to [t].
+- DisaM: merger with another RP phoneme that loses minimal pairs among common words (Britfone: θ~t 52,
+ θ~s 36, θ~z 25, əʊ~ɒ 56 pairs).
+- Pho-S: absent from at least 2 of Hausa, Igbo, Yoruba (PHOIBLE), or under 15% of the world's languages
+ (θ 3.4%, ð 4.8%, t 76%, s 70%, z 29%, ɜ 0.9%).
+- Ped-C: substrate-absent and used by under 20% of the speakers analysed.
+
+## 3. Nigerian English facts used in the knowledge base
+
+- /θ/: [t]/[t̪] (south, Igbo most), [θ] (acrolect; Yoruba 60%), [s] (Hausa 14%); [z] unattested.
+ /ð/: [d] (south), [z] (Hausa, reading). Udofot; Muhammad-Gombe (2019); Oyebola et al. (2019).
+- NURSE (9 Igbo men, ICE-Nigeria): [ɛ] 40%, [a] 31%, [ɔ] 16%, [ɜ] 8%, [e] 5%, spelling-led
+ (Jamakovic & Fuchs 2019). GOAT [o] 50%, FACE [e] 51%; KIT and FLEECE both [i].
+- MFA's english_nigeria dictionary (CC BY 4.0) gives learned variant probabilities: *think* t̪ 0.99 / θ 0.59,
+ *bird* b aː d, *work* w ɔ k.
+
+## 4. Data
+
+- Speech Accent Archive (OSF, CC BY-NC-SA 4.0): 22 Nigerian-L1 speakers with narrow IPA as text, same paragraph;
+ the only Nigerian gold with realised phones we found. `eval/saa_gold.py` uses it.
+- SLR70 (CC BY-SA 4.0): 3,359 read utterances, 31 speakers, 5.77 h. No phone labels.
+- speechocean762 (CC BY 4.0): Mandarin-L1 learners (many children); realised-phone labels only in the GitHub
+ `scores.json`, few on TH/DH.
+- Not used yet: L2-ARCTIC (request form, CC BY-NC 4.0), AfriSpeech-200 (gated, CC BY-NC-SA, 142 h Nigerian),
+ ICE-Nigeria (CC BY-NC-SA, 18 GB audio, ethnicity metadata), SautiDB (restricted). Licences matter for podcasts too.
+
+## 5. Models and platform
+
+- Phone model `facebook/wav2vec2-xlsr-53-espeak-cv-ft` (Apache-2.0). Forced-choice CTC scoring is the GOP-SF / PP-AF
+ method (Parikh et al. 2025 used this model; Cao et al. CTC-based GOP); mispronunciation-detection F1 on
+ L2-ARCTIC is about 60–70 in the literature. Known weakness here: dental stops [t̪ d̪] are heard as [ð]/[θ].
+- Intel Mac: torch 2.2.2 is the last wheel, needs numpy<2; transformers ≥4.52 refuses `.bin` weights under
+ torch<2.6; faster-whisper and torch crash in one process (use transformers' Whisper). MFA installs only via conda.
+
+## 6. Questions only the PG experts can answer
+
+1. Which norms count for I-Ac (RP, GA, LFC, L1-variety attestation)? Why is [t] spared I-Ac in *think* but not [s]?
+2. What separates ContR from DisaM?
+3. DisaM scope: systemic merger (thin/tin) or homophony of the word itself (think/sink)?
+4. FreQ: token or speaker frequency, over which population (all lects or the acrolect), what threshold, per word
+ or per phoneme class?
+5. Pho-S: universal complexity or relative to the substrate languages? How are diphthongs treated?
+6. Ped-C: what evidence counts (teachers' production, acquisition, spelling, curriculum)?
+7. Candidate admission: minimum attestation? Who defines the phonological space? Should zɪŋk be a candidate?
+8. Binary or graded marks? Ties: free variation or expert decision? Does a blank cell mean satisfied?
+9. Rules for allophone vs outer vs developmental tiers; which reference norm for Naijá.
+10. Prosody (stress, rhythm, syllable structure): no published tableau found.
diff --git a/backend/pg/__init__.py b/backend/pg/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e9747043b2b7494f4dde679099d0896f5781cce
--- /dev/null
+++ b/backend/pg/__init__.py
@@ -0,0 +1 @@
+"""Automated Preference Grammar analysis of speech (after Ugorji)."""
diff --git a/backend/pg/__main__.py b/backend/pg/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ac74a83f368afa28e31ae7c71c6c52059c4b157
--- /dev/null
+++ b/backend/pg/__main__.py
@@ -0,0 +1,105 @@
+"""Command line: python -m pg --words think --audio recordings/*.wav --out results/
+
+Recordings are single words unless --transcripts gives a TSV of \t lines, or
+--asr is set for unscripted audio (the target words are then found by speech recognition).
+A TSV of \t lines can be passed with --speakers.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+from . import audio as audio_io
+from .ot import DEFAULT_RANKING
+from .pipeline import Analyzer, Recording, survey
+from .report import write_all
+from .tenets import settings_from
+
+
+def _tsv(path: str | None) -> dict[str, str]:
+ if not path:
+ return {}
+ out = {}
+ for line in Path(path).read_text(encoding="utf-8").splitlines():
+ if "\t" in line:
+ k, v = line.split("\t", 1)
+ out[Path(k.strip()).name] = v.strip()
+ out[Path(k.strip()).stem] = v.strip()
+ return out
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(prog="python -m pg", description="Preference Grammar analysis of recordings")
+ ap.add_argument("--words", help="comma-separated target words, e.g. think,three,thank")
+ ap.add_argument("--survey", action="store_true",
+ help="analyse every sound in the knowledge base, choosing the target words from the transcripts")
+ ap.add_argument("--unit", help="knowledge-base unit, e.g. TH-voiceless or NURSE (default: inferred from the words)")
+ ap.add_argument("--audio", nargs="+", required=True, help="audio files")
+ ap.add_argument("--transcripts", help="TSV: file name, transcript (omit for single-word recordings)")
+ ap.add_argument("--asr", action="store_true",
+ help="unscripted audio (podcasts, interviews): find the target words by speech recognition")
+ ap.add_argument("--speakers", help="TSV: file name, speaker id (a file with an id counts as that one speaker)")
+ ap.add_argument("--no-diarize", action="store_true",
+ help="with --asr, do not separate the speakers inside each recording (by default they are separated)")
+ ap.add_argument("--num-speakers", type=int, help="with --asr, how many people talk in each recording, if known")
+ ap.add_argument("--ranking", default=DEFAULT_RANKING, help=f'tenet ranking (default "{DEFAULT_RANKING}")')
+ ap.add_argument("--settings", help="JSON object overriding tenet thresholds, e.g. {\"freq_threshold\": 0.15}")
+ ap.add_argument("--out", default="pg_results", help="output folder")
+ args = ap.parse_args(argv)
+
+ transcripts, speakers = _tsv(args.transcripts), _tsv(args.speakers)
+ recordings = []
+ for f in args.audio:
+ p = Path(f)
+ transcript = transcripts.get(p.name, transcripts.get(p.stem, "auto" if args.asr else ""))
+ recordings.append(Recording(p.name, audio_io.load(p), speaker=speakers.get(p.name, speakers.get(p.stem, "")),
+ transcript=transcript, diarize=False if args.no_diarize else None,
+ num_speakers=args.num_speakers))
+ unnamed = sum(not r.speaker for r in recordings) if not args.asr or args.no_diarize else 0
+ if unnamed:
+ print(f"warning: {unnamed} recording(s) have no speaker id (--speakers), so each counts as a separate speaker "
+ "for the minimum-speaker rule and the stability resampling")
+ settings = settings_from(json.loads(args.settings) if args.settings else None)
+ if args.survey:
+ run_survey(Analyzer(), recordings, args, settings)
+ return
+ if not args.words:
+ ap.error("--words is required unless --survey is given")
+ analysis = Analyzer().analyse(recordings, args.words.split(","), args.unit, args.ranking, settings)
+ for p in write_all(analysis, Path(args.out)):
+ print(p)
+ if analysis.tableau:
+ print()
+ print(analysis.tableau.to_markdown())
+ print("\npreferred:", ", ".join(analysis.preferred))
+ for w in analysis.warnings:
+ print("warning:", w)
+
+
+def run_survey(analyzer, recordings, args, settings):
+ results = survey(analyzer, recordings, args.ranking, settings)
+ out = Path(args.out)
+ rows = ["| Sound | Classifier | Tokens | Speakers | Variant shares | Preferred | Stable in |", "|---|---|---|---|---|---|---|"]
+ summary = {}
+ for key, a in results.items():
+ write_all(a, out / key)
+ status = (a.unit.validation or {}).get("status", "not validated")
+ shares = ", ".join(f"[{c.segment}] {c.share:.0%}" for c in a.candidates) or "-"
+ rate = max((a.stability or {}).get("preferred_rate", {}).values(), default=None)
+ stable = f"{rate:.0%}" if rate is not None else "-"
+ speakers = len({t.speaker for t in a.tokens})
+ rows.append(f"| {a.unit.label} /{a.unit.phoneme}/ | {status} | {len(a.tokens)} | {speakers} | {shares} | "
+ f"{', '.join(a.preferred) or '-'} | {stable} |")
+ summary[key] = {"status": status, "tokens": len(a.tokens), "speakers": speakers, "words": a.words,
+ "candidates": [{"segment": c.segment, "share": round(c.share, 4), "tokens": c.tokens} for c in a.candidates],
+ "preferred": a.preferred, "stability": a.stability, "warnings": a.warnings}
+ out.mkdir(parents=True, exist_ok=True)
+ (out / "survey.md").write_text("\n".join(rows) + "\n", encoding="utf-8")
+ (out / "survey.json").write_text(json.dumps(summary, ensure_ascii=False, indent=1), encoding="utf-8")
+ print("\n".join(rows))
+ print("\nper-sound results in", out)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/backend/pg/align.py b/backend/pg/align.py
new file mode 100644
index 0000000000000000000000000000000000000000..46da6762b3ede896c72109e41d076b17d2b8a461
--- /dev/null
+++ b/backend/pg/align.py
@@ -0,0 +1,91 @@
+"""Find where each word of a known transcript is spoken (CTC forced alignment over letters)."""
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+import numpy as np
+import torch
+
+ALIGNER_MODEL = "facebook/wav2vec2-base-960h"
+SECONDS_PER_FRAME = 320 / 16000
+
+
+@dataclass
+class WordSpan:
+ word: str
+ start: float # seconds
+ end: float
+ score: float # mean letter posterior, a rough alignment confidence
+
+
+def words_of(transcript: str) -> list[str]:
+ return [w for w in re.sub(r"[^a-z' ]+", " ", transcript.lower().replace("’", "'")).split() if re.search(r"[a-z]", w)]
+
+
+class WordAligner:
+ def __init__(self, model_id: str = ALIGNER_MODEL):
+ from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
+
+ self.processor = Wav2Vec2Processor.from_pretrained(model_id)
+ self.model = Wav2Vec2ForCTC.from_pretrained(model_id).eval()
+ self.vocab = self.processor.tokenizer.get_vocab()
+ self.blank = self.processor.tokenizer.pad_token_id
+ self.upper = all(k.isupper() for k in self.vocab if len(k) == 1 and k.isalpha())
+
+ @torch.no_grad()
+ def emissions(self, audio: np.ndarray, window_s: float = 20.0, overlap_s: float = 1.0) -> torch.Tensor:
+ """Frame log-posteriors; long audio is processed in overlapping windows to bound memory."""
+ win, hop = int(window_s * 16000), int((window_s - overlap_s) * 16000)
+ if len(audio) <= win:
+ x = self.processor(audio, sampling_rate=16000, return_tensors="pt").input_values
+ return torch.log_softmax(self.model(x).logits[0], -1)
+ # place every window's frames by its sample offset (320 samples per frame) rather than by counting,
+ # because a 20 s window yields 999 frames, not 1000; overlaps are split at their midpoint
+ parts, written, half = [], 0, int(overlap_s / 2 / SECONDS_PER_FRAME)
+ for start in range(0, len(audio), hop):
+ chunk = audio[start:start + win]
+ x = self.processor(chunk, sampling_rate=16000, return_tensors="pt").input_values
+ lp = torch.log_softmax(self.model(x).logits[0], -1)
+ base = start // 320
+ last = start + win >= len(audio)
+ t0 = max(0, written - base)
+ t1 = len(lp) if last else len(lp) - half
+ if t1 > t0:
+ parts.append(lp[t0:t1])
+ written = base + t1
+ if last:
+ break
+ return torch.cat(parts)
+
+ def align(self, audio: np.ndarray, transcript: str) -> list[WordSpan]:
+ import torchaudio.functional as AF
+
+ words = words_of(transcript)
+ if not words:
+ return []
+ delim = self.vocab.get("|")
+ ids, owner = [], []
+ for wi, w in enumerate(words):
+ for ch in (w.upper() if self.upper else w):
+ if ch in self.vocab:
+ ids.append(self.vocab[ch])
+ owner.append(wi)
+ if delim is not None and wi < len(words) - 1:
+ ids.append(delim)
+ owner.append(-1)
+ lp = self.emissions(audio)
+ if len(ids) > len(lp):
+ raise ValueError("the transcript is longer than the audio can hold")
+ labels, scores = AF.forced_align(lp.unsqueeze(0), torch.tensor([ids], dtype=torch.int32), blank=self.blank)
+ spans = AF.merge_tokens(labels[0], scores[0].exp())
+ if len(spans) != len(ids):
+ raise RuntimeError("alignment lost letters")
+ out = []
+ for wi, w in enumerate(words):
+ mine = [s for s, o in zip(spans, owner) if o == wi]
+ if not mine:
+ continue
+ out.append(WordSpan(w, mine[0].start * SECONDS_PER_FRAME, mine[-1].end * SECONDS_PER_FRAME,
+ float(np.mean([s.score for s in mine]))))
+ return out
diff --git a/backend/pg/asr.py b/backend/pg/asr.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6bbcdc8da1c447d48d4842d5dd2024e6addfa52
--- /dev/null
+++ b/backend/pg/asr.py
@@ -0,0 +1,88 @@
+"""Find target words in unscripted speech (podcasts, interviews) that has no transcript.
+
+Whisper transcribes with word timestamps; each hit of a target word is then re-aligned against its
+neighbouring words with the letter aligner, because ASR word times are only approximate, and hits
+whose alignment is poor are dropped instead of being scored.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+from dataclasses import asdict, dataclass
+from pathlib import Path
+
+import numpy as np
+
+from .align import WordAligner, WordSpan, words_of
+
+ASR_MODEL = "openai/whisper-small"
+CACHE_DIR = Path(os.environ.get("PG_CACHE", Path(__file__).resolve().parents[1] / "data" / "cache" / "asr"))
+
+
+@dataclass
+class Hit:
+ span: WordSpan # refined position of the target word
+ context: str # the words around it, as transcribed
+
+
+class Transcriber:
+ def __init__(self, model_id: str = ASR_MODEL):
+ from transformers import pipeline
+
+ self.model_id = model_id
+ self.pipe = pipeline("automatic-speech-recognition", model=model_id, device="cpu")
+
+ def words(self, audio: np.ndarray) -> list[WordSpan]:
+ """Word spans for the whole recording. Transcripts are cached on disk (keyed by the audio), because
+ transcribing an hour of speech on a CPU takes about an hour and a survey reuses it for every sound."""
+ key = hashlib.sha1(np.ascontiguousarray(audio, dtype=np.float32).tobytes()).hexdigest()[:20]
+ cache = CACHE_DIR / f"{self.model_id.replace('/', '_')}_{key}.json"
+ if cache.exists():
+ return [WordSpan(**w) for w in json.loads(cache.read_text(encoding="utf-8"))]
+ spans = self._transcribe(audio)
+ try:
+ cache.parent.mkdir(parents=True, exist_ok=True)
+ cache.write_text(json.dumps([asdict(w) for w in spans]), encoding="utf-8")
+ except OSError:
+ pass
+ return spans
+
+ def _transcribe(self, audio: np.ndarray) -> list[WordSpan]:
+ out = self.pipe(
+ {"raw": audio, "sampling_rate": 16000},
+ return_timestamps="word",
+ chunk_length_s=30,
+ generate_kwargs={"language": "en", "task": "transcribe"},
+ )
+ spans = []
+ for chunk in out.get("chunks", []):
+ start, end = chunk["timestamp"]
+ for w in words_of(chunk["text"]):
+ if start is not None:
+ spans.append(WordSpan(w, float(start), float(end if end is not None else start + 0.3), 1.0))
+ return spans
+
+
+def find_targets(audio: np.ndarray, asr_words: list[WordSpan], targets: set[str], aligner: WordAligner,
+ context: int = 2, pad_s: float = 0.15, min_score: float = 0.2) -> list[Hit]:
+ """Re-align every transcribed occurrence of a target word inside a short window of its neighbours."""
+ hits = []
+ for i, w in enumerate(asr_words):
+ if w.word not in targets:
+ continue
+ lo, hi = max(0, i - context), min(len(asr_words), i + context + 1)
+ window = asr_words[lo:hi]
+ t0 = max(0.0, window[0].start - pad_s)
+ t1 = min(len(audio) / 16000, window[-1].end + pad_s)
+ segment = audio[int(t0 * 16000):int(t1 * 16000)]
+ text = " ".join(x.word for x in window)
+ try:
+ spans = aligner.align(segment, text)
+ except (ValueError, RuntimeError):
+ continue
+ mine = spans[i - lo] if len(spans) == len(window) else None
+ if mine is None or mine.word != w.word or mine.score < min_score:
+ continue
+ hits.append(Hit(WordSpan(w.word, t0 + mine.start, t0 + mine.end, mine.score), text))
+ return hits
diff --git a/backend/pg/audio.py b/backend/pg/audio.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f7bdf7963bfe81ef5b25f62618b04f14689f9de
--- /dev/null
+++ b/backend/pg/audio.py
@@ -0,0 +1,61 @@
+"""Load any common audio format as 16 kHz mono float32 and trim leading/trailing silence."""
+from __future__ import annotations
+
+import io
+import shutil
+import subprocess
+
+import numpy as np
+
+SR = 16000
+
+
+def load(source, sr: int = SR) -> np.ndarray:
+ """source: a path, raw bytes, or a file-like object."""
+ data = source
+ if hasattr(source, "read"):
+ data = source.read()
+ try:
+ import soundfile as sf
+
+ audio, rate = sf.read(io.BytesIO(data) if isinstance(data, (bytes, bytearray)) else data, dtype="float32", always_2d=True)
+ audio = audio.mean(1)
+ except Exception:
+ audio, rate = _ffmpeg(data, sr), sr
+ if rate != sr:
+ from scipy.signal import resample_poly
+
+ g = np.gcd(rate, sr)
+ audio = resample_poly(audio, sr // g, rate // g).astype("float32")
+ return np.ascontiguousarray(audio, dtype=np.float32)
+
+
+def _ffmpeg(data, sr: int) -> np.ndarray:
+ """Decode formats libsndfile cannot read (mp3, m4a, webm/opus from browsers)."""
+ exe = shutil.which("ffmpeg")
+ if exe is None:
+ raise RuntimeError("this audio format needs ffmpeg, which is not installed")
+ cmd = [exe, "-nostdin", "-loglevel", "error", "-i", "pipe:0" if isinstance(data, (bytes, bytearray)) else str(data),
+ "-f", "f32le", "-ac", "1", "-ar", str(sr), "pipe:1"]
+ proc = subprocess.run(cmd, input=data if isinstance(data, (bytes, bytearray)) else None, capture_output=True, check=False)
+ if proc.returncode != 0:
+ raise RuntimeError(f"could not decode audio: {proc.stderr.decode(errors='replace').strip()[:300]}")
+ return np.frombuffer(proc.stdout, dtype=np.float32).copy()
+
+
+def trim(audio: np.ndarray, sr: int = SR, threshold_db: float = 35.0, pad_s: float = 0.15) -> tuple[np.ndarray, float]:
+ """Cut silence before the first and after the last frame within threshold_db of the peak level.
+ Returns the trimmed audio and its start offset in seconds."""
+ hop = int(0.01 * sr)
+ if len(audio) < hop * 3:
+ return audio, 0.0
+ frames = audio[: len(audio) // hop * hop].reshape(-1, hop)
+ rms = np.sqrt((frames ** 2).mean(1) + 1e-12)
+ db = 20 * np.log10(rms / rms.max())
+ voiced = np.where(db > -threshold_db)[0]
+ if len(voiced) == 0:
+ return audio, 0.0
+ pad = int(pad_s * sr)
+ start = max(0, voiced[0] * hop - pad)
+ end = min(len(audio), (voiced[-1] + 1) * hop + pad)
+ return audio[start:end], start / sr
diff --git a/backend/pg/calibrate.py b/backend/pg/calibrate.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d40ad08f72d251d46b37f4d36abf87349f553bb
--- /dev/null
+++ b/backend/pg/calibrate.py
@@ -0,0 +1,84 @@
+"""Calibrate the variant classifier on human-labelled tokens.
+
+The phone model has systematic biases (on Nigerian speech it hears many dental stops [d̪] as [ð]).
+Per unit we fit a temperature T and an offset b_v per variant so that the posterior is
+softmax(-nll_v / T + b_v), by maximum likelihood of the human labels with a small L2 penalty on
+the offsets. Leave-one-speaker-out evaluation shows whether a calibration carries over to
+speakers it was not fitted on. Result files live in pg/kb/calibration.json.
+"""
+from __future__ import annotations
+
+import json
+import math
+from collections import defaultdict
+from pathlib import Path
+
+import numpy as np
+
+KB = Path(__file__).resolve().parent / "kb" / "calibration.json"
+
+
+def _matrix(rows: list[dict], labels: list[str]) -> np.ndarray:
+ big = 1e4
+ return np.array([[r["nll"].get(l) if r["nll"].get(l) is not None else big for l in labels] for r in rows], dtype=float)
+
+
+def _posteriors(nll: np.ndarray, temperature: float, offsets: np.ndarray) -> np.ndarray:
+ z = -nll / temperature + offsets
+ z -= z.max(1, keepdims=True)
+ p = np.exp(z)
+ return p / p.sum(1, keepdims=True)
+
+
+def fit(rows: list[dict], labels: list[str], class_of: dict[str, str], l2: float = 0.5) -> dict:
+ """rows: [{"nll": {label: nll}, "gold": class}]; class_of maps each label to its class."""
+ from scipy.optimize import minimize
+
+ nll = _matrix(rows, labels)
+ member = np.array([[class_of[l] == r["gold"] for l in labels] for r in rows], dtype=float)
+ keep = member.sum(1) > 0
+ nll, member = nll[keep], member[keep]
+
+ def loss(theta):
+ t, b = math.exp(theta[0]), np.concatenate([[0.0], theta[1:]])
+ p = _posteriors(nll, t, b)
+ return -np.log((p * member).sum(1) + 1e-12).mean() + l2 * (theta[1:] ** 2).sum() / len(nll)
+
+ theta0 = np.zeros(len(labels))
+ res = minimize(loss, theta0, method="L-BFGS-B")
+ t = math.exp(res.x[0])
+ return {"temperature": round(t, 4), "offsets": {l: round(float(b), 4) for l, b in zip(labels, np.concatenate([[0.0], res.x[1:]]))}}
+
+
+def predict(row: dict, calib: dict, class_of: dict[str, str]) -> tuple[str, float]:
+ labels = list(calib["offsets"])
+ nll = _matrix([row], labels)
+ p = _posteriors(nll, calib["temperature"], np.array([calib["offsets"][l] for l in labels]))[0]
+ by_class = defaultdict(float)
+ for l, x in zip(labels, p):
+ by_class[class_of[l]] += x
+ best = max(by_class, key=by_class.get)
+ return best, by_class[best]
+
+
+def leave_one_speaker_out(rows: list[dict], labels: list[str], class_of: dict[str, str], l2: float = 0.5) -> dict:
+ """Accuracy of the raw argmax vs the calibrated classifier on each speaker, fitted on the others."""
+ speakers = sorted({r["speaker"] for r in rows})
+ raw = cal = n = 0
+ for spk in speakers:
+ train = [r for r in rows if r["speaker"] != spk]
+ test = [r for r in rows if r["speaker"] == spk]
+ calib = fit(train, labels, class_of, l2)
+ ident = {"temperature": 1.0, "offsets": {l: 0.0 for l in labels}}
+ for r in test:
+ raw += predict(r, ident, class_of)[0] == r["gold"]
+ cal += predict(r, calib, class_of)[0] == r["gold"]
+ n += 1
+ return {"tokens": n, "speakers": len(speakers), "raw_accuracy": raw / n, "calibrated_accuracy": cal / n}
+
+
+def load(path: Path = KB) -> dict:
+ if not path.exists():
+ return {}
+ with open(path, encoding="utf-8") as f:
+ return json.load(f).get("units", {})
diff --git a/backend/pg/cluster.py b/backend/pg/cluster.py
new file mode 100644
index 0000000000000000000000000000000000000000..22647dae4b290ba0d2f28b09337002cfd587118a
--- /dev/null
+++ b/backend/pg/cluster.py
@@ -0,0 +1,106 @@
+"""Two-level clustering of tokens of the unit under study, and the contrastiveness matrix.
+
+Primary clusters are phonological categories (the variant each token was judged to realise).
+Secondary clusters split each category by acoustic similarity (cosine distance between
+self-supervised speech features of the segment), exposing sub-variants and outliers.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import numpy as np
+
+
+def _unit(x: np.ndarray) -> np.ndarray:
+ n = np.linalg.norm(x, axis=1, keepdims=True)
+ return x / np.where(n == 0, 1, n)
+
+
+@dataclass
+class Clustering:
+ primary: list[str] # per token
+ secondary: list[str] # per token, e.g. "t.1"
+ categories: list[str] # primary cluster names, most frequent first
+ contrast: np.ndarray # cosine similarity between category centroids (categories x categories)
+ separation: dict[str, float] # mean silhouette of each category (higher = more distinct)
+
+
+def kmeans_cosine(x: np.ndarray, k: int, seed: int = 0) -> np.ndarray:
+ from sklearn.cluster import KMeans
+
+ return KMeans(n_clusters=k, n_init=10, random_state=seed).fit_predict(_unit(x))
+
+
+def _best_split(x: np.ndarray, k_max: int, min_size: int, seed: int):
+ from sklearn.metrics import silhouette_score
+
+ best_labels, best_score = None, -1.0
+ for k in range(2, min(k_max, len(x) // min_size) + 1):
+ labels = kmeans_cosine(x, k, seed)
+ if np.bincount(labels).min() < min_size:
+ continue
+ score = silhouette_score(_unit(x), labels, metric="cosine")
+ if score > best_score:
+ best_labels, best_score = labels, score
+ return best_labels, best_score
+
+
+def _reference(x: np.ndarray, rng) -> np.ndarray:
+ """A structureless sample with the same spread: one Gaussian aligned with x's principal axes."""
+ mean = x.mean(0)
+ _, s, vt = np.linalg.svd(x - mean, full_matrices=False)
+ sd = s / np.sqrt(max(len(x) - 1, 1))
+ return mean + (rng.standard_normal((len(x), len(sd))) * sd) @ vt
+
+
+def choose_k(x: np.ndarray, k_max: int, min_size: int = 3, seed: int = 0, margin: float = 0.1) -> np.ndarray:
+ """Split into k (2..k_max) clusters only if the best split's cosine silhouette clearly beats that of
+ structureless reference data with the same principal-axis spread (gap-statistic style); else one cluster."""
+ x = np.asarray(x, dtype=np.float64)
+ n = len(x)
+ labels, score = _best_split(x, k_max, min_size, seed)
+ if labels is None:
+ return np.zeros(n, dtype=int)
+ rng = np.random.default_rng(seed)
+ null = max(_best_split(_reference(x, rng), k_max, min_size, seed)[1] for _ in range(3))
+ if score < null + margin:
+ return np.zeros(n, dtype=int)
+ return labels
+
+
+def two_level(labels: list[str], embeddings: np.ndarray | None, max_sub: int = 3) -> Clustering:
+ counts = {c: labels.count(c) for c in dict.fromkeys(labels)}
+ categories = sorted(counts, key=lambda c: -counts[c])
+ secondary = list(labels)
+ contrast = np.eye(len(categories))
+ separation = {c: float("nan") for c in categories}
+ if embeddings is not None and len(embeddings) == len(labels):
+ x = np.asarray(embeddings, dtype=np.float64)
+ # centre first: raw self-supervised features share a large common direction, so uncentred
+ # cosine similarities are all high (0.7-0.95) whatever the sounds
+ x = _unit(x - x.mean(0))
+ lab = np.array(labels)
+ for c in categories:
+ idx = np.where(lab == c)[0]
+ sub = choose_k(x[idx], max_sub) if len(idx) >= 6 else np.zeros(len(idx), dtype=int)
+ # number sub-clusters by size so ".1" is always the core of the category
+ order = {s: r + 1 for r, s in enumerate(sorted(set(sub), key=lambda s: -(sub == s).sum()))}
+ for i, s in zip(idx, sub):
+ secondary[i] = f"{c}.{order[s]}"
+ centroids = np.stack([x[lab == c].mean(0) for c in categories])
+ contrast = _unit(centroids) @ _unit(centroids).T
+ if len(categories) > 1:
+ from sklearn.metrics import silhouette_samples
+
+ sil = silhouette_samples(x, lab, metric="cosine")
+ separation = {c: float(sil[lab == c].mean()) for c in categories}
+ return Clustering(labels, secondary, categories, contrast, separation)
+
+
+def purity(pred: list, truth: list) -> float:
+ """Share of tokens whose cluster's majority truth label matches their own (1.0 = clusters are pure)."""
+ total = 0
+ for c in set(pred):
+ members = [t for p, t in zip(pred, truth) if p == c]
+ total += max(members.count(t) for t in set(members))
+ return total / len(pred)
diff --git a/backend/pg/diarize.py b/backend/pg/diarize.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee619cd14f87c7a6554854ad0fe53947be7cfb8c
--- /dev/null
+++ b/backend/pg/diarize.py
@@ -0,0 +1,215 @@
+"""Speaker separation (diarization) for recordings with several speakers, such as podcasts and interviews.
+
+Every target word must be credited to the person who said it, or "every speaker counts equally", the
+minimum-speaker rule and the speaker resampling in the stability check all treat a whole panel as one person.
+Short overlapping windows of speech are turned into speaker embeddings (SpeechBrain's ECAPA-TDNN model trained
+for speaker verification on VoxCeleb), averaged with their neighbours, grouped by agglomerative clustering on
+cosine distance, refined and smoothed over time, and each word is given the label of the windows it falls in.
+On made-up conversations of 2-5 SLR70 Nigerian speakers this credited every sampled word to the right speaker
+(eval/diarize_eval.py); WavLM (microsoft/wavlm-base-plus-sv) managed 71-100% and is kept as an option. The speaker labels are anonymous (S1, S2, ... in order of first
+speaking); they say who spoke together, not who the person is.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+from collections import Counter
+from dataclasses import asdict, dataclass
+from pathlib import Path
+
+import numpy as np
+
+SPEAKER_MODEL = "speechbrain/spkrec-ecapa-voxceleb"
+WAVLM_MODEL = "microsoft/wavlm-base-plus-sv"
+# cosine distance at which clusters stop merging, tuned per model on eval/diarize_eval.py conversations
+THRESHOLDS = {SPEAKER_MODEL: 0.9, WAVLM_MODEL: 0.7}
+CACHE_DIR = Path(os.environ.get("PG_CACHE", Path(__file__).resolve().parents[1] / "data" / "cache" / "diarize"))
+SR = 16000
+
+
+@dataclass
+class Turn:
+ start: float
+ end: float
+ speaker: str
+
+
+@dataclass
+class Diarization:
+ turns: list[Turn]
+ speakers: int
+
+ def speaker_at(self, start: float, end: float, reach: float = 2.0) -> str | None:
+ """The speaker who talks most during [start, end]; else the nearest turn within reach seconds."""
+ overlap = Counter()
+ for t in self.turns:
+ o = min(end, t.end) - max(start, t.start)
+ if o > 0:
+ overlap[t.speaker] += o
+ if overlap:
+ return overlap.most_common(1)[0][0]
+ mid = (start + end) / 2
+ near = min(self.turns, key=lambda t: min(abs(mid - t.start), abs(mid - t.end)), default=None)
+ if near is not None and min(abs(mid - near.start), abs(mid - near.end)) <= reach:
+ return near.speaker
+ return None
+
+
+def speech_windows(audio: np.ndarray, speech: list[tuple[float, float]] | None = None, win_s: float = 1.5,
+ hop_s: float = 0.75, min_cover: float = 0.5) -> list[tuple[float, float]]:
+ """Windows that are mostly speech. Speech regions come from word times when known, else from frame energy."""
+ total = len(audio) / SR
+ step = 0.01
+ voiced = np.zeros(int(total / step) + 1, dtype=bool)
+ if speech:
+ for s, e in speech:
+ voiced[int(max(0.0, s) / step):int(min(total, e) / step) + 1] = True
+ else:
+ hop = int(step * SR)
+ frames = audio[: len(audio) // hop * hop].reshape(-1, hop)
+ db = 20 * np.log10(np.sqrt((frames ** 2).mean(1) + 1e-12))
+ voiced[: len(db)] = db > np.percentile(db, 30) + 6 # well above the noise floor
+ out, t = [], 0.0
+ while t + win_s <= total + 1e-6:
+ a, b = int(t / step), int((t + win_s) / step)
+ if voiced[a:b].mean() >= min_cover:
+ out.append((round(t, 3), round(t + win_s, 3)))
+ t += hop_s
+ return out
+
+
+class Diarizer:
+ def __init__(self, model_id: str = SPEAKER_MODEL):
+ import torch
+
+ self.torch = torch
+ self.model_id = model_id
+ if model_id.startswith("speechbrain/"):
+ from speechbrain.inference.speaker import EncoderClassifier
+
+ self.model = EncoderClassifier.from_hparams(source=model_id, run_opts={"device": "cpu"},
+ savedir=str(CACHE_DIR.parent / "speechbrain" / model_id.split("/")[1]))
+ self.extractor = None
+ else:
+ from transformers import AutoFeatureExtractor, WavLMForXVector
+
+ self.extractor = AutoFeatureExtractor.from_pretrained(model_id)
+ self.model = WavLMForXVector.from_pretrained(model_id).eval()
+
+ def embed(self, audio: np.ndarray, windows: list[tuple[float, float]], batch: int = 16) -> np.ndarray:
+ out = []
+ with self.torch.inference_mode():
+ for i in range(0, len(windows), batch):
+ clips = [audio[int(s * SR):int(e * SR)] for s, e in windows[i:i + batch]]
+ if self.extractor is None:
+ n = min(len(c) for c in clips)
+ wavs = self.torch.from_numpy(np.stack([c[:n] for c in clips]))
+ out.append(self.model.encode_batch(wavs).squeeze(1).numpy())
+ else:
+ inputs = self.extractor(clips, sampling_rate=SR, return_tensors="pt", padding=True)
+ out.append(self.model(**inputs).embeddings.numpy())
+ emb = np.concatenate(out) if out else np.zeros((0, 192), dtype=np.float32)
+ return emb / (np.linalg.norm(emb, axis=1, keepdims=True) + 1e-9)
+
+ def __call__(self, audio: np.ndarray, speech: list[tuple[float, float]] | None = None,
+ num_speakers: int | None = None, threshold: float | None = None) -> Diarization:
+ threshold = threshold or THRESHOLDS.get(self.model_id, 0.9)
+ key = hashlib.sha1(np.ascontiguousarray(audio, dtype=np.float32).tobytes()).hexdigest()[:20]
+ spec = f"{num_speakers or 'auto'}_{threshold}_{'words' if speech else 'energy'}"
+ cache = CACHE_DIR / f"{self.model_id.replace('/', '_')}_{key}_{spec}.json"
+ if cache.exists():
+ d = json.loads(cache.read_text(encoding="utf-8"))
+ return Diarization([Turn(**t) for t in d["turns"]], d["speakers"])
+ windows = speech_windows(audio, speech)
+ result = cluster(windows, self.embed(audio, windows), num_speakers, threshold)
+ try:
+ cache.parent.mkdir(parents=True, exist_ok=True)
+ cache.write_text(json.dumps({"turns": [asdict(t) for t in result.turns], "speakers": result.speakers}),
+ encoding="utf-8")
+ except OSError:
+ pass
+ return result
+
+
+def cluster(windows: list[tuple[float, float]], emb: np.ndarray, num_speakers: int | None = None,
+ threshold: float = 0.9, min_share: float = 0.03, smooth: int = 5, centre: bool = True,
+ refine: int = 5, context: int = 1) -> Diarization:
+ """Group windows by speaker. With num_speakers unknown, clusters merge until their average cosine
+ distance exceeds threshold; clusters holding under min_share of the speech are folded into the nearest.
+ The embeddings are centred first: they share a large common part (channel, language), which otherwise
+ makes everyone look alike. Each window is then averaged with `context` neighbours on each side within the
+ same stretch of speech, since a voice is recognised better from ~3 s than from 1.5 s."""
+ if len(windows) == 0:
+ return Diarization([], 0)
+ if centre and len(emb) > 1:
+ emb = emb - emb.mean(0)
+ emb = emb / (np.linalg.norm(emb, axis=1, keepdims=True) + 1e-9)
+ if context > 0 and len(emb) > 1:
+ starts = np.array([s for s, _ in windows])
+ hop = float(np.median(np.diff(starts))) if len(starts) > 1 else 0.75
+ avg = np.empty_like(emb)
+ for i in range(len(emb)):
+ lo, hi = max(0, i - context), min(len(emb), i + context + 1)
+ near = [j for j in range(lo, hi) if abs(starts[j] - starts[i]) <= context * hop + 0.01]
+ avg[i] = emb[near].mean(0)
+ emb = avg / (np.linalg.norm(avg, axis=1, keepdims=True) + 1e-9)
+ if len(windows) == 1 or num_speakers == 1:
+ labels = np.zeros(len(windows), dtype=int)
+ else:
+ from sklearn.cluster import AgglomerativeClustering
+
+ ac = AgglomerativeClustering(n_clusters=min(num_speakers, len(windows)) if num_speakers else None,
+ distance_threshold=None if num_speakers else threshold,
+ metric="cosine", linkage="average")
+ labels = ac.fit_predict(emb)
+ labels = _fold_small(labels, emb, min_share, keep=num_speakers)
+ for _ in range(refine): # move each window to the speaker whose average voice it is closest to
+ names = sorted(set(labels.tolist()))
+ cents = np.stack([emb[labels == c].mean(0) for c in names])
+ new = np.array(names)[np.argmax(emb @ cents.T, axis=1)]
+ if (new == labels).all():
+ break
+ labels = new
+ labels = _smooth(labels, windows, smooth)
+ # S1, S2, ... in order of first speaking
+ order = {lab: f"S{i + 1}" for i, lab in enumerate(dict.fromkeys(labels.tolist()))}
+ turns = []
+ for (s, e), lab in zip(windows, labels):
+ name = order[lab]
+ if turns and turns[-1].speaker == name and s <= turns[-1].end + 0.01:
+ turns[-1].end = e
+ else:
+ turns.append(Turn(s, e, name))
+ # where windows of two speakers overlap, split the overlap halfway
+ for a, b in zip(turns, turns[1:]):
+ if a.speaker != b.speaker and b.start < a.end:
+ a.end = b.start = round((a.end + b.start) / 2, 3)
+ return Diarization(turns, len(order))
+
+
+def _fold_small(labels: np.ndarray, emb: np.ndarray, min_share: float, keep: int | None) -> np.ndarray:
+ labels = labels.copy()
+ while True:
+ counts = Counter(labels.tolist())
+ if len(counts) <= max(1, keep or 1):
+ return labels
+ small = min(counts, key=counts.get)
+ if counts[small] >= min_share * len(labels):
+ return labels
+ cents = {c: emb[labels == c].mean(0) for c in counts if c != small}
+ mine = emb[labels == small].mean(0)
+ labels[labels == small] = max(cents, key=lambda c: float(cents[c] @ mine))
+
+
+def _smooth(labels: np.ndarray, windows: list[tuple[float, float]], k: int) -> np.ndarray:
+ """Majority vote over neighbouring windows within the same stretch of speech; turns rarely last under ~2 s."""
+ if k <= 1 or len(labels) < 3:
+ return labels
+ out = labels.copy()
+ half = k // 2
+ for i in range(len(labels)):
+ lo, hi = max(0, i - half), min(len(labels), i + half + 1)
+ near = [labels[j] for j in range(lo, hi) if abs(windows[j][0] - windows[i][0]) <= half * 1.0 + 0.01]
+ out[i] = Counter(near).most_common(1)[0][0] if Counter(near).most_common(1)[0][1] > 1 else labels[i]
+ return out
diff --git a/backend/pg/kb/__init__.py b/backend/pg/kb/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/backend/pg/kb/build_typology.py b/backend/pg/kb/build_typology.py
new file mode 100644
index 0000000000000000000000000000000000000000..cacb772efc044492f0fdff7adf34f93aa2eaedfa
--- /dev/null
+++ b/backend/pg/kb/build_typology.py
@@ -0,0 +1,93 @@
+"""Rebuild typology.json from PHOIBLE (python -m pg.kb.build_typology).
+
+world_frequency: share of the world's languages whose inventory has the segment (exact match,
+non-marginal phonemes, each language weighted equally across its inventories).
+substrate: share of each Nigerian substrate language's PHOIBLE inventories that have the segment
+(broad match, so dental t̪ counts as t and length is ignored).
+"""
+from __future__ import annotations
+
+import csv
+import json
+import unicodedata
+from collections import defaultdict
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+PHOIBLE = HERE.parents[1] / "data" / "resources" / "phoible" / "phoible.csv"
+SUBSTRATE = {"Hausa": "haus1257", "Igbo": "nucl1417", "Yoruba": "yoru1245"}
+
+SEGMENTS = ["p", "b", "t", "d", "t̪", "d̪", "k", "ɡ", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h", "tʃ", "dʒ", "m", "n",
+ "ŋ", "l", "ɹ", "r", "w", "j", "ɸ", "kp", "ɡb",
+ "i", "ɪ", "e", "ɛ", "æ", "a", "ɑ", "ɒ", "ɔ", "o", "ʊ", "u", "ʌ", "ɐ", "ə", "ɜ", "ɚ", "ɝ",
+ "iː", "uː", "ɑː", "ɔː", "ɜː", "eɪ", "aɪ", "ɔɪ", "əʊ", "oʊ", "aʊ", "ɪə", "eə", "ɛə", "ʊə"]
+# PHOIBLE spells some segments differently
+PHOIBLE_FORM = {"tʃ": "t̠ʃ", "dʒ": "d̠ʒ", "ɡb": "ɡb", "kp": "kp"}
+
+REFERENCE = {
+ "about": "RP reference phonemes (Britfone symbols) used to decide whether a variant merges with another phoneme.",
+ "consonants": ["p", "b", "t", "d", "k", "ɡ", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h", "tʃ", "dʒ", "m", "n", "ŋ",
+ "l", "ɹ", "w", "j"],
+ "short_vowels": ["ɪ", "ɛ", "æ", "ɐ", "ɒ", "ʊ", "ə"],
+ "long_vowels": ["iː", "ɑː", "ɔː", "uː", "ɜː"],
+ "diphthongs": ["eɪ", "aɪ", "ɔɪ", "əʊ", "aʊ", "ɪə", "ɛə", "ʊə"],
+ # phonetic symbols a recogniser or transcriber may use, mapped to the RP phoneme they would merge with;
+ # Nigerian monophthongs [e] and [o] are absent on purpose: they are not RP phonemes, so they merge with nothing
+ "maps_to": {"t̪": "t", "d̪": "d", "r": "ɹ", "ɾ": "ɹ", "g": "ɡ", "ʌ": "ɐ", "a": "æ", "ɔ": "ɒ", "ɑ": "ɑː", "i": "iː",
+ "u": "uː", "ɜ": "ɜː", "ɝ": "ɜː", "ɚ": "ɜː", "əː": "ɜː", "oʊ": "əʊ", "eə": "ɛə", "e": None, "o": None},
+ "core_note": "Lingua Franca Core (Jenkins 2000; Walker 2010): consonant contrasts are core except those involving θ and ð; "
+ "vowel quantity (long or diphthong vs short) is core; vowel quality is not, except the NURSE vowel.",
+}
+
+
+def _norm(s: str) -> str:
+ return unicodedata.normalize("NFC", s.replace("g", "ɡ"))
+
+
+def _broad(s: str) -> str:
+ s = unicodedata.normalize("NFD", s).replace("t̠ʃ", "tʃ").replace("d̠ʒ", "dʒ")
+ s = "".join(c for c in s if not unicodedata.combining(c) and c not in "ːˑʰʲʷʼ")
+ return unicodedata.normalize("NFC", s.replace("g", "ɡ"))
+
+
+def build(phoible: Path = PHOIBLE) -> dict:
+ inv_segs, inv_lang = defaultdict(set), {}
+ with open(phoible, encoding="utf-8") as f:
+ for row in csv.DictReader(f):
+ if row["Marginal"] == "TRUE" or not row["Glottocode"] or row["Glottocode"] == "NA":
+ continue
+ inv = row["InventoryID"]
+ inv_lang[inv] = row["Glottocode"]
+ for alt in row["Phoneme"].split("|"): # UPSID writes place-ambiguous phonemes as t̪|t
+ inv_segs[inv].add(_norm(alt))
+ by_lang = defaultdict(list)
+ for inv, lang in inv_lang.items():
+ by_lang[lang].append(inv_segs[inv])
+ world = {}
+ for seg in SEGMENTS:
+ form = _norm(PHOIBLE_FORM.get(seg, seg))
+ share = sum(sum(form in s for s in invs) / len(invs) for invs in by_lang.values()) / len(by_lang)
+ world[seg] = round(share, 4)
+ substrate = {}
+ for name, glotto in SUBSTRATE.items():
+ invs = [{_broad(x) for x in s} for s in by_lang.get(glotto, [])]
+ substrate[name] = {seg: round(sum(_broad(seg) in s for s in invs) / len(invs), 3) if invs else None for seg in SEGMENTS}
+ return {
+ "source": {
+ "phoible": "PHOIBLE 2.0 (Moran & McCloy eds., doi:10.5281/zenodo.2626687), data CC BY 4.0, file backend/data/resources/phoible/phoible.csv",
+ "languages_counted": len(by_lang),
+ "substrate_glottocodes": SUBSTRATE,
+ },
+ "world_frequency": world,
+ "substrate": substrate,
+ "reference": REFERENCE,
+ }
+
+
+if __name__ == "__main__":
+ out = build()
+ (HERE / "typology.json").write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
+ w = out["world_frequency"]
+ print({k: w[k] for k in ("θ", "ð", "t", "t̪", "s", "z", "f", "ɪ", "ɜ", "əʊ", "o", "ɔ")})
+ for lang, pres in out["substrate"].items():
+ print(lang, {k: pres[k] for k in ("θ", "t", "s", "z", "f", "v", "ɔ", "o", "ɪ", "əʊ")})
diff --git a/backend/pg/kb/calibration.json b/backend/pg/kb/calibration.json
new file mode 100644
index 0000000000000000000000000000000000000000..22c7bb73d4494e4051f79a4d815cd652e5caccda
--- /dev/null
+++ b/backend/pg/kb/calibration.json
@@ -0,0 +1,19 @@
+{
+ "about": "Per-unit temperature and variant offsets fitted by pg/calibrate.py on human-labelled Nigerian tokens (Speech Accent Archive, phonetician IPA). Kept only where they raise Cohen's kappa on held-out speakers with a speaker-bootstrap interval above zero. Refit with eval/fit_calibration.py when more labels exist.",
+ "model": "facebook/wav2vec2-xlsr-53-espeak-cv-ft",
+ "date": "2026-10-20",
+ "units": {
+ "TH-voiced": {
+ "temperature": 1.4131,
+ "offsets": {
+ "ð": 0.0,
+ "d": 2.2165,
+ "z": -0.0481,
+ "v": -1.4434,
+ "θ": 0.6117,
+ "t": -0.5229
+ },
+ "fitted_on": "129 human-labelled tokens from 22 speakers"
+ }
+ }
+}
\ No newline at end of file
diff --git a/backend/pg/kb/fetch.py b/backend/pg/kb/fetch.py
new file mode 100644
index 0000000000000000000000000000000000000000..3abd715478db45038fddbc93aeb1db411cd3cee3
--- /dev/null
+++ b/backend/pg/kb/fetch.py
@@ -0,0 +1,41 @@
+"""Download the pronouncing lexicons the pipeline needs (python -m pg.kb.fetch).
+
+Pinned to the commits the knowledge base was built and tested with. CMUdict: BSD-style licence;
+Britfone: MIT. Both are fetched into backend/data/resources/lexicons (git-ignored).
+"""
+from __future__ import annotations
+
+import sys
+import urllib.request
+from pathlib import Path
+
+RESOURCES = Path(__file__).resolve().parents[2] / "data" / "resources"
+FILES = {
+ "lexicons/cmudict/cmudict.dict":
+ "https://raw.githubusercontent.com/cmusphinx/cmudict/74790861f652b15e4ac49015a90074ad62a27690/cmudict.dict",
+ "lexicons/cmudict/LICENSE":
+ "https://raw.githubusercontent.com/cmusphinx/cmudict/74790861f652b15e4ac49015a90074ad62a27690/LICENSE",
+ "lexicons/britfone/britfone.main.3.0.1.csv":
+ "https://raw.githubusercontent.com/JoseLlarena/Britfone/1062be14adc96c358f2087ac5449d72130c7a6f4/britfone.main.3.0.1.csv",
+ "lexicons/britfone/LICENSE.txt":
+ "https://raw.githubusercontent.com/JoseLlarena/Britfone/1062be14adc96c358f2087ac5449d72130c7a6f4/LICENSE.txt",
+}
+
+
+def ensure(resources: Path = RESOURCES, quiet: bool = True) -> None:
+ for rel, url in FILES.items():
+ dest = Path(resources) / rel
+ if dest.exists() and dest.stat().st_size > 0:
+ continue
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ if not quiet:
+ print(f"downloading {url}", file=sys.stderr)
+ tmp = dest.with_suffix(dest.suffix + ".part")
+ with urllib.request.urlopen(url, timeout=60) as r, open(tmp, "wb") as f:
+ f.write(r.read())
+ tmp.replace(dest)
+
+
+if __name__ == "__main__":
+ ensure(quiet=False)
+ print("lexicons ready in", RESOURCES / "lexicons")
diff --git a/backend/pg/kb/typology.json b/backend/pg/kb/typology.json
new file mode 100644
index 0000000000000000000000000000000000000000..0b0181439f14a9d84e29d43c23bbda9c8488ba5d
--- /dev/null
+++ b/backend/pg/kb/typology.json
@@ -0,0 +1,350 @@
+{
+ "source": {
+ "phoible": "PHOIBLE 2.0 (Moran & McCloy eds., doi:10.5281/zenodo.2626687), data CC BY 4.0, file backend/data/resources/phoible/phoible.csv",
+ "languages_counted": 2175,
+ "substrate_glottocodes": {
+ "Hausa": "haus1257",
+ "Igbo": "nucl1417",
+ "Yoruba": "yoru1245"
+ }
+ },
+ "world_frequency": {
+ "p": 0.8412,
+ "b": 0.6132,
+ "t": 0.7575,
+ "d": 0.487,
+ "t̪": 0.271,
+ "d̪": 0.1529,
+ "k": 0.9035,
+ "ɡ": 0.5493,
+ "f": 0.4069,
+ "v": 0.2568,
+ "θ": 0.0341,
+ "ð": 0.0481,
+ "s": 0.7018,
+ "z": 0.2904,
+ "ʃ": 0.3284,
+ "ʒ": 0.1314,
+ "h": 0.5412,
+ "tʃ": 0.3801,
+ "dʒ": 0.2614,
+ "m": 0.9636,
+ "n": 0.8482,
+ "ŋ": 0.6342,
+ "l": 0.7225,
+ "ɹ": 0.0153,
+ "r": 0.467,
+ "w": 0.8392,
+ "j": 0.8951,
+ "ɸ": 0.0459,
+ "kp": 0.1354,
+ "ɡb": 0.1361,
+ "i": 0.9386,
+ "ɪ": 0.1383,
+ "e": 0.6372,
+ "ɛ": 0.3617,
+ "æ": 0.0611,
+ "a": 0.8864,
+ "ɑ": 0.0685,
+ "ɒ": 0.0156,
+ "ɔ": 0.3534,
+ "o": 0.6228,
+ "ʊ": 0.1305,
+ "u": 0.8961,
+ "ʌ": 0.0426,
+ "ɐ": 0.0204,
+ "ə": 0.213,
+ "ɜ": 0.0094,
+ "ɚ": 0.0001,
+ "ɝ": 0.0,
+ "iː": 0.3251,
+ "uː": 0.3023,
+ "ɑː": 0.0325,
+ "ɔː": 0.1074,
+ "ɜː": 0.0013,
+ "eɪ": 0.0023,
+ "aɪ": 0.0032,
+ "ɔɪ": 0.0018,
+ "əʊ": 0.001,
+ "oʊ": 0.0008,
+ "aʊ": 0.0017,
+ "ɪə": 0.0011,
+ "eə": 0.0007,
+ "ɛə": 0.001,
+ "ʊə": 0.0001
+ },
+ "substrate": {
+ "Hausa": {
+ "p": 0.0,
+ "b": 1.0,
+ "t": 1.0,
+ "d": 1.0,
+ "t̪": 1.0,
+ "d̪": 1.0,
+ "k": 1.0,
+ "ɡ": 1.0,
+ "f": 0.2,
+ "v": 0.0,
+ "θ": 0.0,
+ "ð": 0.0,
+ "s": 1.0,
+ "z": 1.0,
+ "ʃ": 1.0,
+ "ʒ": 0.2,
+ "h": 1.0,
+ "tʃ": 0.8,
+ "dʒ": 0.8,
+ "m": 1.0,
+ "n": 1.0,
+ "ŋ": 0.0,
+ "l": 1.0,
+ "ɹ": 0.0,
+ "r": 0.8,
+ "w": 1.0,
+ "j": 1.0,
+ "ɸ": 0.6,
+ "kp": 0.0,
+ "ɡb": 0.0,
+ "i": 1.0,
+ "ɪ": 0.2,
+ "e": 1.0,
+ "ɛ": 0.0,
+ "æ": 0.0,
+ "a": 1.0,
+ "ɑ": 0.0,
+ "ɒ": 0.0,
+ "ɔ": 0.0,
+ "o": 1.0,
+ "ʊ": 0.2,
+ "u": 1.0,
+ "ʌ": 0.0,
+ "ɐ": 0.0,
+ "ə": 0.4,
+ "ɜ": 0.0,
+ "ɚ": 0.0,
+ "ɝ": 0.0,
+ "iː": 1.0,
+ "uː": 1.0,
+ "ɑː": 0.0,
+ "ɔː": 0.0,
+ "ɜː": 0.0,
+ "eɪ": 0.0,
+ "aɪ": 0.0,
+ "ɔɪ": 0.0,
+ "əʊ": 0.0,
+ "oʊ": 0.0,
+ "aʊ": 0.0,
+ "ɪə": 0.0,
+ "eə": 0.0,
+ "ɛə": 0.0,
+ "ʊə": 0.0
+ },
+ "Igbo": {
+ "p": 1.0,
+ "b": 1.0,
+ "t": 1.0,
+ "d": 1.0,
+ "t̪": 1.0,
+ "d̪": 1.0,
+ "k": 1.0,
+ "ɡ": 1.0,
+ "f": 1.0,
+ "v": 0.75,
+ "θ": 0.0,
+ "ð": 0.0,
+ "s": 1.0,
+ "z": 1.0,
+ "ʃ": 0.5,
+ "ʒ": 0.0,
+ "h": 0.75,
+ "tʃ": 1.0,
+ "dʒ": 1.0,
+ "m": 1.0,
+ "n": 1.0,
+ "ŋ": 1.0,
+ "l": 1.0,
+ "ɹ": 0.25,
+ "r": 0.25,
+ "w": 1.0,
+ "j": 1.0,
+ "ɸ": 0.0,
+ "kp": 0.25,
+ "ɡb": 0.25,
+ "i": 1.0,
+ "ɪ": 0.25,
+ "e": 0.75,
+ "ɛ": 0.75,
+ "æ": 0.0,
+ "a": 1.0,
+ "ɑ": 0.0,
+ "ɒ": 0.0,
+ "ɔ": 0.75,
+ "o": 1.0,
+ "ʊ": 0.75,
+ "u": 1.0,
+ "ʌ": 0.0,
+ "ɐ": 0.0,
+ "ə": 0.0,
+ "ɜ": 0.0,
+ "ɚ": 0.0,
+ "ɝ": 0.0,
+ "iː": 1.0,
+ "uː": 1.0,
+ "ɑː": 0.0,
+ "ɔː": 0.75,
+ "ɜː": 0.0,
+ "eɪ": 0.0,
+ "aɪ": 0.0,
+ "ɔɪ": 0.0,
+ "əʊ": 0.0,
+ "oʊ": 0.0,
+ "aʊ": 0.0,
+ "ɪə": 0.0,
+ "eə": 0.0,
+ "ɛə": 0.0,
+ "ʊə": 0.0
+ },
+ "Yoruba": {
+ "p": 0.333,
+ "b": 1.0,
+ "t": 1.0,
+ "d": 1.0,
+ "t̪": 1.0,
+ "d̪": 1.0,
+ "k": 1.0,
+ "ɡ": 1.0,
+ "f": 1.0,
+ "v": 0.0,
+ "θ": 0.0,
+ "ð": 0.0,
+ "s": 1.0,
+ "z": 0.0,
+ "ʃ": 1.0,
+ "ʒ": 0.0,
+ "h": 1.0,
+ "tʃ": 0.0,
+ "dʒ": 1.0,
+ "m": 1.0,
+ "n": 0.667,
+ "ŋ": 0.0,
+ "l": 1.0,
+ "ɹ": 0.0,
+ "r": 0.667,
+ "w": 1.0,
+ "j": 1.0,
+ "ɸ": 0.0,
+ "kp": 1.0,
+ "ɡb": 1.0,
+ "i": 1.0,
+ "ɪ": 0.0,
+ "e": 1.0,
+ "ɛ": 1.0,
+ "æ": 0.0,
+ "a": 1.0,
+ "ɑ": 0.0,
+ "ɒ": 0.0,
+ "ɔ": 1.0,
+ "o": 1.0,
+ "ʊ": 0.0,
+ "u": 1.0,
+ "ʌ": 0.0,
+ "ɐ": 0.0,
+ "ə": 0.0,
+ "ɜ": 0.0,
+ "ɚ": 0.0,
+ "ɝ": 0.0,
+ "iː": 1.0,
+ "uː": 1.0,
+ "ɑː": 0.0,
+ "ɔː": 1.0,
+ "ɜː": 0.0,
+ "eɪ": 0.0,
+ "aɪ": 0.0,
+ "ɔɪ": 0.0,
+ "əʊ": 0.0,
+ "oʊ": 0.0,
+ "aʊ": 0.0,
+ "ɪə": 0.0,
+ "eə": 0.0,
+ "ɛə": 0.0,
+ "ʊə": 0.0
+ }
+ },
+ "reference": {
+ "about": "RP reference phonemes (Britfone symbols) used to decide whether a variant merges with another phoneme.",
+ "consonants": [
+ "p",
+ "b",
+ "t",
+ "d",
+ "k",
+ "ɡ",
+ "f",
+ "v",
+ "θ",
+ "ð",
+ "s",
+ "z",
+ "ʃ",
+ "ʒ",
+ "h",
+ "tʃ",
+ "dʒ",
+ "m",
+ "n",
+ "ŋ",
+ "l",
+ "ɹ",
+ "w",
+ "j"
+ ],
+ "short_vowels": [
+ "ɪ",
+ "ɛ",
+ "æ",
+ "ɐ",
+ "ɒ",
+ "ʊ",
+ "ə"
+ ],
+ "long_vowels": [
+ "iː",
+ "ɑː",
+ "ɔː",
+ "uː",
+ "ɜː"
+ ],
+ "diphthongs": [
+ "eɪ",
+ "aɪ",
+ "ɔɪ",
+ "əʊ",
+ "aʊ",
+ "ɪə",
+ "ɛə",
+ "ʊə"
+ ],
+ "maps_to": {
+ "t̪": "t",
+ "d̪": "d",
+ "r": "ɹ",
+ "ɾ": "ɹ",
+ "g": "ɡ",
+ "ʌ": "ɐ",
+ "a": "æ",
+ "ɔ": "ɒ",
+ "ɑ": "ɑː",
+ "i": "iː",
+ "u": "uː",
+ "ɜ": "ɜː",
+ "ɝ": "ɜː",
+ "ɚ": "ɜː",
+ "əː": "ɜː",
+ "oʊ": "əʊ",
+ "eə": "ɛə",
+ "e": null,
+ "o": null
+ },
+ "core_note": "Lingua Franca Core (Jenkins 2000; Walker 2010): consonant contrasts are core except those involving θ and ð; vowel quantity (long or diphthong vs short) is core; vowel quality is not, except the NURSE vowel."
+ }
+}
\ No newline at end of file
diff --git a/backend/pg/kb/units.json b/backend/pg/kb/units.json
new file mode 100644
index 0000000000000000000000000000000000000000..a9bd88f45d52d167b78c0dc2a2d2971d13b19ba7
--- /dev/null
+++ b/backend/pg/kb/units.json
@@ -0,0 +1,262 @@
+{
+ "about": "Units of pronunciation that Preference Grammar compares, the realisations to test for in the audio, and the reference judgements for the knowledge-based tenets (I-Ac; Ped-C lists). The PG sources assign these by expert judgement; entries marked provisional are defaults chosen from the cited literature and must be confirmed by the PG experts.",
+ "units": {
+ "TH-voiceless": {
+ "label": "
",
+ "phoneme": "θ",
+ "candidates": [
+ "θ",
+ "t",
+ "s",
+ "f",
+ "z",
+ "d"
+ ],
+ "international": [
+ "θ",
+ "t",
+ "t̪",
+ "f"
+ ],
+ "pedagogic_difficult": [],
+ "notes": "I-Ac: the Lingua Franca Core treats /θ/ as non-core and lists [t], [f] and [s] as substitutes without choosing; stopping ([t], [t̪]) is an established norm in Irish, Caribbean and Liberian English and in ICAO radiotelephony ('tree' for three), TH-fronting ([f]) in London English. No L1-variety norm uses [s] or [z]. This reproduces Ugorji's operability table for 'think'. ICE-Nigeria word-initial /θ/: [θ] 47%, [t] 49%, [s] 4% (Oyebola, Ho & Li 2019).",
+ "sources": [
+ "Ugorji 2010: 58 (tableau for
in 'think')",
+ "Jenkins 2000: 138, via Rosewarne & Basso 2017: 171-172",
+ "Walker 2010",
+ "Wells 1982 via 'Th-stopping'",
+ "Oyebola, Ho & Li 2019"
+ ],
+ "validation": {
+ "status": "validated",
+ "kappa": 0.68,
+ "accuracy": 0.82,
+ "majority_baseline": 0.58,
+ "balanced_accuracy": 0.84,
+ "share_error": 0.08,
+ "calibrated": false,
+ "note": "kappa 0.68 on 85 tokens from 22 Nigerian speakers (Speech Accent Archive; one paragraph, so new words are untested)"
+ }
+ },
+ "TH-voiced": {
+ "label": "
",
+ "phoneme": "ð",
+ "candidates": [
+ "ð",
+ "d",
+ "z",
+ "v",
+ "θ",
+ "t"
+ ],
+ "international": [
+ "ð",
+ "d",
+ "d̪",
+ "v"
+ ],
+ "pedagogic_difficult": [],
+ "notes": "Provisional: by analogy with /θ/ (LFC non-core; stopping established in Irish, Caribbean and Liberian English; fronting in London English). Nigerian realisations: [d] in the South, [z] among Hausa speakers when reading (Udofot; Muhammad-Gombe 2019).",
+ "sources": [
+ "Jenkins 2000 via Rosewarne & Basso 2017",
+ "Udofot n.d.",
+ "Muhammad-Gombe 2019"
+ ],
+ "validation": {
+ "status": "validated",
+ "kappa": 0.64,
+ "accuracy": 0.81,
+ "majority_baseline": 0.53,
+ "balanced_accuracy": 0.66,
+ "share_error": 0.09,
+ "calibrated": true,
+ "note": "kappa 0.64 on 129 tokens from 22 Nigerian speakers (Speech Accent Archive; one paragraph, so new words are untested)"
+ }
+ },
+ "NURSE": {
+ "label": "NURSE",
+ "phoneme": "ɜː",
+ "lexical_set": "NURSE",
+ "candidates": [
+ "ɜː",
+ "ɛ",
+ "a",
+ "ɔ",
+ "e",
+ "ə"
+ ],
+ "international": [
+ "ɜː",
+ "ɝ",
+ "ɜ",
+ "əː"
+ ],
+ "pedagogic_difficult": [],
+ "notes": "The NURSE quality is part of the Lingua Franca Core. Nigerian English measurements (9 Igbo speakers): [ɛ] 40%, [a] 31%, [ɔ] 16%, [ɜ] 8%, [e] 5%, largely spelling-led (Jamakovic & Fuchs 2019). Ugorji's national model: model з/ε; developmental ε/a/з.",
+ "sources": [
+ "Jenkins 2000; Walker 2010",
+ "Jamakovic & Fuchs 2019",
+ "Ugorji, ICAEISD 2024 slides (national model)"
+ ],
+ "validation": {
+ "status": "not validated",
+ "kappa": 0.23,
+ "accuracy": 0.43,
+ "majority_baseline": 0.41,
+ "balanced_accuracy": 0.51,
+ "share_error": 0.41,
+ "calibrated": false,
+ "note": "kappa 0.23 on 86 tokens from 21 Nigerian speakers (Speech Accent Archive; one paragraph, so new words are untested)"
+ }
+ },
+ "STRUT": {
+ "label": "STRUT",
+ "phoneme": "ʌ",
+ "lexical_set": "STRUT",
+ "candidates": [
+ "ʌ",
+ "ɔ",
+ "a",
+ "ə"
+ ],
+ "international": [
+ "ʌ",
+ "ɐ"
+ ],
+ "pedagogic_difficult": [],
+ "notes": "Provisional international list (RP/GA qualities). Nigerian English: [ɔ] (basic Southern), [a] (basic Hausa), [ʌ] at the sophisticated level (Jowitt 2019: 41 via Udofot); national model ʌ/ɒ.",
+ "sources": [
+ "Jowitt 2019 via Udofot n.d.",
+ "Ugorji, ICAEISD 2024 slides (national model)"
+ ],
+ "validation": {
+ "status": "not validated",
+ "note": "no human-labelled test yet"
+ }
+ },
+ "KIT": {
+ "label": "KIT",
+ "phoneme": "ɪ",
+ "lexical_set": "KIT",
+ "candidates": [
+ "ɪ",
+ "i",
+ "e"
+ ],
+ "international": [
+ "ɪ"
+ ],
+ "pedagogic_difficult": [],
+ "notes": "Provisional. Vowel length (KIT vs FLEECE) is core in the LFC. Nigerian English realises KIT and FLEECE alike as [i] (Jamakovic & Fuchs 2019); national model ɪ, developmental ɪ/i.",
+ "sources": [
+ "Walker 2010",
+ "Jamakovic & Fuchs 2019",
+ "Ugorji, ICAEISD 2024 slides (national model)"
+ ],
+ "validation": {
+ "status": "validated",
+ "kappa": 0.55,
+ "accuracy": 0.81,
+ "majority_baseline": 0.76,
+ "balanced_accuracy": 0.71,
+ "share_error": 0.08,
+ "calibrated": false,
+ "note": "kappa 0.55 on 112 tokens from 22 Nigerian speakers (Speech Accent Archive; one paragraph, so new words are untested)"
+ }
+ },
+ "FLEECE": {
+ "label": "FLEECE",
+ "phoneme": "iː",
+ "lexical_set": "FLEECE",
+ "candidates": [
+ "iː",
+ "ɪ"
+ ],
+ "international": [
+ "iː",
+ "i"
+ ],
+ "pedagogic_difficult": [],
+ "notes": "Provisional. Nigerian English [i]; national model i.",
+ "sources": [
+ "Jamakovic & Fuchs 2019",
+ "Ugorji, ICAEISD 2024 slides (national model)"
+ ],
+ "validation": {
+ "status": "not validated",
+ "kappa": 0.06,
+ "accuracy": 0.9,
+ "majority_baseline": 0.92,
+ "balanced_accuracy": 0.52,
+ "share_error": 0.05,
+ "calibrated": false,
+ "note": "kappa 0.06 on 183 tokens from 22 Nigerian speakers (Speech Accent Archive; one paragraph, so new words are untested)"
+ }
+ },
+ "GOAT": {
+ "label": "GOAT",
+ "phoneme": "əʊ",
+ "lexical_set": "GOAT",
+ "candidates": [
+ "o",
+ "əʊ",
+ "ɔ"
+ ],
+ "international": [
+ "əʊ",
+ "oʊ",
+ "o",
+ "oː"
+ ],
+ "pedagogic_difficult": [],
+ "notes": "Ugorji (2010) evaluates /o/, /əʊ/, /ɒ/ for GOAT: /o/ wins with no violations; /əʊ/ violates FreQ, Pho-S, Ped-C; /ɒ/ violates I-Ac, ContR, FreQ, DisaM (Jowitt 2015: 8). Ugorji's /ɒ/ is phonetically [ɔ]. Monophthongal GOAT is an established norm in Scottish, Irish, Welsh and Northern English (provisional: check Wells 1982). Measured Nigerian English: [o] 50%, [ɔ] 16% (Jamakovic & Fuchs 2019); /o/ 91% (Eka 1985).",
+ "sources": [
+ "Ugorji 2010 via Jowitt 2015: 8",
+ "Jamakovic & Fuchs 2019",
+ "Eka 1985 via Jowitt 2015"
+ ],
+ "validation": {
+ "status": "not validated",
+ "kappa": 0.16,
+ "accuracy": 0.72,
+ "majority_baseline": 0.87,
+ "balanced_accuracy": 0.6,
+ "share_error": 0.13,
+ "calibrated": false,
+ "note": "kappa 0.16 on 68 tokens from 22 Nigerian speakers (Speech Accent Archive; one paragraph, so new words are untested)"
+ }
+ },
+ "FACE": {
+ "label": "FACE",
+ "phoneme": "eɪ",
+ "lexical_set": "FACE",
+ "candidates": [
+ "e",
+ "eɪ",
+ "ɛ"
+ ],
+ "international": [
+ "eɪ",
+ "e",
+ "eː"
+ ],
+ "pedagogic_difficult": [],
+ "notes": "Provisional. Monophthongal FACE is an established norm in Scottish, Irish, Welsh and Northern English. Nigerian English [e] about 51% (Jamakovic & Fuchs 2019); /e/ about 95% (Eka 1985); Jowitt proposes /e/ for Nigerian RP; national model e/eɪ.",
+ "sources": [
+ "Jamakovic & Fuchs 2019",
+ "Jowitt 2015",
+ "Ugorji, ICAEISD 2024 slides (national model)"
+ ],
+ "validation": {
+ "status": "not validated",
+ "kappa": 0.13,
+ "accuracy": 0.54,
+ "majority_baseline": 0.72,
+ "balanced_accuracy": 0.42,
+ "share_error": 0.17,
+ "calibrated": false,
+ "note": "kappa 0.13 on 89 tokens from 22 Nigerian speakers (Speech Accent Archive; one paragraph, so new words are untested)"
+ }
+ }
+ }
+}
diff --git a/backend/pg/lexicon.py b/backend/pg/lexicon.py
new file mode 100644
index 0000000000000000000000000000000000000000..54c27352e2edc3e56cffd105db847cb3e96dc1e2
--- /dev/null
+++ b/backend/pg/lexicon.py
@@ -0,0 +1,207 @@
+"""Pronouncing lexicons in IPA, used for canonical forms and for Disambiguity (homophones/minimal pairs).
+
+Supports CMUdict (ARPABET, General American), Britfone (RP-like IPA) and open-dict ipa-dict files.
+"""
+from __future__ import annotations
+
+import csv
+import pickle
+import re
+import unicodedata
+from collections import defaultdict
+from dataclasses import dataclass, field
+from pathlib import Path
+
+ARPABET_TO_IPA = {
+ "AA": "ɑ", "AE": "æ", "AH": "ʌ", "AO": "ɔ", "AW": "aʊ", "AY": "aɪ", "EH": "ɛ", "ER": "ɝ", "EY": "eɪ",
+ "IH": "ɪ", "IY": "i", "OW": "oʊ", "OY": "ɔɪ", "UH": "ʊ", "UW": "u",
+ "B": "b", "CH": "tʃ", "D": "d", "DH": "ð", "F": "f", "G": "ɡ", "HH": "h", "JH": "dʒ", "K": "k", "L": "l",
+ "M": "m", "N": "n", "NG": "ŋ", "P": "p", "R": "ɹ", "S": "s", "SH": "ʃ", "T": "t", "TH": "θ", "V": "v",
+ "W": "w", "Y": "j", "Z": "z", "ZH": "ʒ",
+}
+_UNSTRESSED = {"AH": "ə", "ER": "ɚ"}
+
+# multi-character phones, longest first, so IPA strings can be split into segments
+MULTI = sorted(
+ ["tʃ", "dʒ", "aɪ", "aʊ", "eɪ", "oʊ", "ɔɪ", "əʊ", "ɪə", "eə", "ʊə", "ɛə", "iː", "uː", "ɑː", "ɔː", "ɜː", "ɝ", "ɚ",
+ "t̪", "d̪"],
+ key=len, reverse=True,
+)
+_STRIP = re.compile(r"[ˈˌ.\s/\[\]]")
+# symbols different lexicons use for the same reference phoneme (Britfone writes modern RP: STRUT ɐ, DRESS ɛ)
+EQUIVALENT = {"ɜː": {"ɝ", "ɜ"}, "iː": {"i"}, "uː": {"u"}, "ɔː": {"ɔ"}, "ɑː": {"ɑ"}, "əʊ": {"oʊ"}, "e": {"ɛ"},
+ "ɛ": {"e"}, "ʌ": {"ɐ"}, "ɐ": {"ʌ"}, "eə": {"ɛə"}, "ɛə": {"eə"}}
+
+
+def same_phoneme(a: str) -> set[str]:
+ return {a} | EQUIVALENT.get(a, set())
+
+
+def normalise_ipa(s: str) -> str:
+ s = unicodedata.normalize("NFD", s)
+ s = s.replace("g", "ɡ").replace("ɫ", "l").replace("r", "ɹ").replace("ʤ", "dʒ").replace("ʧ", "tʃ")
+ s = s.replace("ʼ", "").replace("'", "")
+ return unicodedata.normalize("NFC", _STRIP.sub("", s))
+
+
+def segments(ipa: str) -> list[str]:
+ """Split an IPA string into phone segments (diphthongs, affricates and length marks kept together)."""
+ s = normalise_ipa(ipa)
+ out, i = [], 0
+ while i < len(s):
+ for m in MULTI:
+ if s.startswith(m, i):
+ out.append(m)
+ i += len(m)
+ break
+ else:
+ ch = s[i]
+ i += 1
+ # attach combining diacritics and length to the previous segment
+ while i < len(s) and (unicodedata.combining(s[i]) or s[i] in "ːˑʰʷʲ̃"):
+ ch += s[i]
+ i += 1
+ out.append(ch)
+ return out
+
+
+def arpabet_to_ipa(phones: list[str]) -> list[str]:
+ out = []
+ for p in phones:
+ base, stress = re.match(r"([A-Z]+)(\d?)", p).groups()
+ if base in _UNSTRESSED and stress == "0":
+ out.append(_UNSTRESSED[base])
+ else:
+ out.append(ARPABET_TO_IPA[base])
+ return out
+
+
+@dataclass
+class Lexicon:
+ name: str
+ entries: dict[str, list[tuple[str, ...]]] = field(default_factory=lambda: defaultdict(list))
+
+ def add(self, word: str, segs: list[str]):
+ word = word.lower()
+ segs = tuple(segs)
+ prons = self.entries.setdefault(word, [])
+ if segs not in prons:
+ prons.append(segs)
+
+ def pronunciations(self, word: str) -> list[tuple[str, ...]]:
+ return list(self.entries.get(word.lower(), []))
+
+ def __contains__(self, word: str) -> bool:
+ return word.lower() in self.entries
+
+ def __len__(self) -> int:
+ return len(self.entries)
+
+ def index(self) -> dict[tuple[str, ...], set[str]]:
+ """pronunciation -> words, for homophone lookups"""
+ if not hasattr(self, "_index"):
+ idx = defaultdict(set)
+ for w, prons in self.entries.items():
+ for p in prons:
+ idx[p].add(w)
+ self._index = idx
+ return self._index
+
+ def homophones(self, segs, exclude: str = "") -> set[str]:
+ return {w for w in self.index().get(tuple(segs), set()) if w != exclude.lower()}
+
+ def merger_pairs(self, a: str, b: str, words=None) -> list[tuple[str, str]]:
+ """Word pairs kept apart only by the a/b contrast, i.e. that become homophones if a merges with b."""
+ if a == b:
+ return []
+ idx = self.index()
+ pairs = []
+ for pron, ws in idx.items():
+ if a not in pron:
+ continue
+ merged = tuple(b if s == a else s for s in pron)
+ for w1 in ws:
+ if words is not None and w1 not in words:
+ continue
+ for w2 in idx.get(merged, ()):
+ if w2 != w1 and (words is None or w2 in words):
+ pairs.append((w1, w2))
+ return sorted(set(pairs))
+
+
+def load_cmudict(path) -> Lexicon:
+ lex = Lexicon("cmudict")
+ with open(path, encoding="latin-1") as f:
+ for line in f:
+ if not line.strip() or line.startswith(";;;"):
+ continue
+ line = line.split("#")[0].strip()
+ parts = line.split()
+ word = re.sub(r"\(\d+\)$", "", parts[0])
+ if not re.match(r"^[a-zA-Z][a-zA-Z'.-]*$", word):
+ continue
+ try:
+ lex.add(word, arpabet_to_ipa(parts[1:]))
+ except (AttributeError, KeyError):
+ continue
+ return lex
+
+
+def load_britfone(path) -> Lexicon:
+ lex = Lexicon("britfone")
+ with open(path, encoding="utf-8") as f:
+ for row in csv.reader(f):
+ if len(row) < 2:
+ continue
+ word = re.sub(r"\(\d+\)$", "", row[0].strip())
+ lex.add(word, segments(row[1]))
+ return lex
+
+
+def load_ipa_dict(path, name="ipa-dict") -> Lexicon:
+ lex = Lexicon(name)
+ with open(path, encoding="utf-8") as f:
+ for line in f:
+ if "\t" not in line:
+ continue
+ word, prons = line.rstrip("\n").split("\t", 1)
+ for p in prons.split(","):
+ lex.add(word, segments(p))
+ return lex
+
+
+CACHE_VERSION = 2 # bump when segments() or the loaders change, so stale parses are not reused
+
+
+def _cached(path: Path, loader, *args) -> Lexicon:
+ """Parse once, then reuse a pickle next to the source file (rebuilt when the source changes)."""
+ cache = path.with_name(f"{path.name}.v{CACHE_VERSION}.pkl")
+ if cache.exists() and cache.stat().st_mtime >= path.stat().st_mtime:
+ with open(cache, "rb") as f:
+ return pickle.load(f)
+ lex = loader(path, *args)
+ lex.entries = dict(lex.entries)
+ try:
+ with open(cache, "wb") as f:
+ pickle.dump(lex, f)
+ except OSError:
+ pass
+ return lex
+
+
+def load_default(resources: Path, names=("cmudict", "britfone", "ipa-dict-en_US", "ipa-dict-en_UK")) -> dict[str, Lexicon]:
+ """Load the lexicons present under backend/data/resources/lexicons."""
+ d = Path(resources) / "lexicons"
+ found = {}
+ for p in sorted(d.rglob("cmudict*")):
+ if p.suffix in (".dict", ".txt") or p.name.endswith("0.7b"):
+ found["cmudict"] = (p, load_cmudict)
+ break
+ for p in sorted(d.rglob("britfone.main*.csv")):
+ found["britfone"] = (p, load_britfone)
+ break
+ for tag in ("en_US", "en_UK"):
+ for p in sorted(d.rglob(f"*{tag}*.txt")):
+ found[f"ipa-dict-{tag}"] = (p, lambda path, t=tag: load_ipa_dict(path, f"ipa-dict-{t}"))
+ break
+ return {name: _cached(*found[name]) for name in names if name in found}
diff --git a/backend/pg/ot.py b/backend/pg/ot.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1d835e4ce14d9d25229a747708e7d616856914d
--- /dev/null
+++ b/backend/pg/ot.py
@@ -0,0 +1,183 @@
+"""Preference Grammar evaluation (Ugorji): attested forms compete on six ranked, violable tenets.
+
+Evaluation follows Optimality Theory's EVAL: strict domination, so a candidate is eliminated as soon
+as it has more violations than some rival on the highest-ranked tenet (or stratum of tenets) where
+they differ. Whatever survives every tenet is preferred; more than one survivor is a genuine tie.
+"""
+from __future__ import annotations
+
+import csv
+import html
+import io
+from dataclasses import dataclass, field
+
+TENETS = ("I-Ac", "ContR", "FreQ", "DisaM", "Pho-S", "Ped-C")
+TENET_NAMES = {
+ "I-Ac": "International acceptance",
+ "ContR": "Contrastiveness",
+ "FreQ": "Frequency",
+ "DisaM": "Disambiguity",
+ "Pho-S": "Phonetic simplicity",
+ "Ped-C": "Pedagogic convenience",
+}
+# column headings as printed in the PG operability table
+COLUMN_LABELS = {
+ "I-Ac": "*No I-Ac",
+ "ContR": "*No ContR",
+ "FreQ": "*No FreQ",
+ "DisaM": "DisaM",
+ "Pho-S": "*Pho-S",
+ "Ped-C": "*Ped-C",
+}
+DEFAULT_RANKING = "I-Ac >> ContR >> FreQ >> DisaM >> Pho-S >> Ped-C"
+_ALIASES = {t.lower().replace("-", ""): t for t in TENETS}
+_ALIASES.update({name.lower().replace(" ", ""): t for t, name in TENET_NAMES.items()})
+_ALIASES.update({"paedagogicconvenience": "Ped-C", "iac": "I-Ac"})
+
+
+@dataclass
+class Violation:
+ count: int = 0
+ reason: str = ""
+ source: str = "" # what the judgement rests on: data, lexicon, typology, knowledge base, expert
+
+
+@dataclass
+class Candidate:
+ form: str # the word as realised, in IPA (e.g. "tɪŋk")
+ segment: str = "" # realisation of the unit under study (e.g. "t")
+ tokens: int = 0
+ share: float = 0.0
+ violations: dict[str, Violation] = field(default_factory=dict)
+
+ def marks(self, tenet: str) -> int:
+ return self.violations.get(tenet, Violation()).count
+
+
+@dataclass
+class Tableau:
+ unit: str # the unit under study, e.g. "
" or "NURSE"
+ ranking: list[list[str]]
+ candidates: list[Candidate]
+ winners: list[Candidate]
+ eliminated_at: dict[str, int] # candidate form -> index of the stratum that eliminated it
+
+ @property
+ def tie(self) -> bool:
+ return len(self.winners) > 1
+
+ def columns(self) -> list[str]:
+ return [t for stratum in self.ranking for t in stratum]
+
+ def cell(self, cand: Candidate, tenet: str) -> str:
+ """Violation marks for one cell; '!' follows the mark that proved fatal."""
+ n = cand.marks(tenet)
+ stratum = next(i for i, s in enumerate(self.ranking) if tenet in s)
+ if self.eliminated_at.get(cand.form) != stratum or n == 0:
+ return "*" * n
+ # within the fatal stratum the decisive mark is the first one beyond the survivors' total
+ best = self._best_in_stratum(stratum)
+ before = sum(cand.marks(t) for t in self.ranking[stratum][: self.ranking[stratum].index(tenet)])
+ fatal_at = best - before # 0-based index of the fatal mark inside this cell
+ if 0 <= fatal_at < n:
+ return "*" * (fatal_at + 1) + "!" + "*" * (n - fatal_at - 1)
+ return "*" * n
+
+ def shaded(self, cand: Candidate, tenet: str) -> bool:
+ """Cells below the point where the candidate was already decided are irrelevant (shaded)."""
+ stratum = next(i for i, s in enumerate(self.ranking) if tenet in s)
+ out = self.eliminated_at.get(cand.form)
+ return out is not None and stratum > out
+
+ def _best_in_stratum(self, stratum: int) -> int:
+ alive = [c for c in self.candidates if self.eliminated_at.get(c.form, len(self.ranking)) >= stratum]
+ return min(sum(c.marks(t) for t in self.ranking[stratum]) for c in alive)
+
+ def to_rows(self) -> list[dict]:
+ rows = []
+ for c in self.candidates:
+ row = {"candidate": c.form, "segment": c.segment, "tokens": c.tokens, "share": round(c.share, 4),
+ "preferred": c in self.winners}
+ for t in self.columns():
+ row[COLUMN_LABELS[t]] = self.cell(c, t)
+ rows.append(row)
+ return rows
+
+ def to_csv(self) -> str:
+ buf = io.StringIO()
+ rows = self.to_rows()
+ writer = csv.DictWriter(buf, fieldnames=list(rows[0]) if rows else ["candidate"])
+ writer.writeheader()
+ writer.writerows(rows)
+ return buf.getvalue()
+
+ def to_markdown(self) -> str:
+ cols = self.columns()
+ head = f"| {self.unit} | " + " | ".join(COLUMN_LABELS[t] for t in cols) + " |"
+ lines = [head, "|" + "---|" * (len(cols) + 1)]
+ for i, c in enumerate(self.candidates):
+ label = f"{chr(97 + i)}. {'☞ ' if c in self.winners else ''}{c.form}"
+ cells = [self.cell(c, t) for t in cols]
+ lines.append(f"| {label} | " + " | ".join(cells) + " |")
+ return "\n".join(lines)
+
+ def to_html(self) -> str:
+ cols = self.columns()
+ out = ['
', f"
{html.escape(self.unit)}
"]
+ out += [f'
{html.escape(COLUMN_LABELS[t])}
' for t in cols]
+ out.append("
")
+ for i, c in enumerate(self.candidates):
+ win = c in self.winners
+ out.append(f'
{chr(97 + i)}. {"☞ " if win else ""}{html.escape(c.form)}
')
+ for t in cols:
+ v = c.violations.get(t, Violation())
+ cls = "shaded" if self.shaded(c, t) else ""
+ tip = html.escape(f"{v.reason} [{v.source}]" if v.reason else "")
+ out.append(f'
{html.escape(self.cell(c, t))}
')
+ out.append("
")
+ out.append("
")
+ return "".join(out)
+
+
+def parse_ranking(ranking=DEFAULT_RANKING) -> list[list[str]]:
+ """Accept 'A >> B >> C', ['A', 'B'], or [['A', 'B'], ['C']] (tenets in one stratum are unranked
+ with respect to each other and their marks are pooled). Tenets left out are deleted."""
+ if isinstance(ranking, str):
+ strata = [part.split(",") for part in ranking.split(">>")]
+ else:
+ strata = [s if isinstance(s, (list, tuple)) else [s] for s in ranking]
+ parsed, seen = [], set()
+ for stratum in strata:
+ names = []
+ for raw in stratum:
+ key = str(raw).strip().lower().replace("-", "").replace(" ", "").replace("*no", "").replace("*", "")
+ if not key:
+ continue
+ if key not in _ALIASES:
+ raise ValueError(f"unknown tenet {raw!r}; expected one of {', '.join(TENETS)}")
+ tenet = _ALIASES[key]
+ if tenet in seen:
+ raise ValueError(f"tenet {tenet} appears twice in the ranking")
+ seen.add(tenet)
+ names.append(tenet)
+ if names:
+ parsed.append(names)
+ if not parsed:
+ raise ValueError("the ranking must keep at least one tenet")
+ return parsed
+
+
+def evaluate(candidates: list[Candidate], ranking=DEFAULT_RANKING, unit: str = "") -> Tableau:
+ strata = parse_ranking(ranking)
+ if not candidates:
+ raise ValueError("no candidates to evaluate")
+ alive = list(candidates)
+ eliminated_at: dict[str, int] = {}
+ for i, stratum in enumerate(strata):
+ totals = [sum(c.marks(t) for t in stratum) for c in alive]
+ best = min(totals)
+ for c, total in zip(alive, totals):
+ if total > best:
+ eliminated_at[c.form] = i
+ alive = [c for c, total in zip(alive, totals) if total == best]
+ return Tableau(unit=unit, ranking=strata, candidates=list(candidates), winners=alive, eliminated_at=eliminated_at)
diff --git a/backend/pg/phones.py b/backend/pg/phones.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccb8a419a1b982a85a739ca13628584cdf3375c2
--- /dev/null
+++ b/backend/pg/phones.py
@@ -0,0 +1,240 @@
+"""Acoustic phone evidence from a CTC phone recogniser.
+
+Text-to-IPA only gives dictionary forms; Preference Grammar needs the forms speakers actually
+produced. A multilingual CTC phone model gives per-frame phone posteriors, and competing
+pronunciations of a word are compared by their CTC likelihood (a forced choice among the
+variants under study), which is far more reliable than free phone decoding.
+"""
+from __future__ import annotations
+
+import itertools
+import json
+import math
+from dataclasses import dataclass
+
+import numpy as np
+import torch
+
+DEFAULT_MODEL = "facebook/wav2vec2-xlsr-53-espeak-cv-ft"
+FRAME_RATE = 50 # wav2vec2 emits one frame per 20 ms
+
+# lexicon symbols that some phone vocabularies spell differently
+FALLBACKS = {
+ "ɝ": ["ɜː", "ɚ", "ɜ"], "ɚ": ["ə"], "ɜ": ["ɜː"], "ɜː": ["ɜ"], "i": ["iː"], "iː": ["i"], "u": ["uː"], "uː": ["u"],
+ "ɑ": ["ɑː"], "ɑː": ["ɑ"], "ɔ": ["ɔː"], "ɔː": ["ɔ"], "ɒ": ["ɔ"], "əʊ": ["oʊ"], "oʊ": ["əʊ"], "o": ["oʊ"],
+ "e": ["ɛ"], "ɛ": ["e"], "ɹ": ["r"], "r": ["ɹ"], "ɡ": ["g"], "t̪": ["t"], "d̪": ["d"], "ɪə": ["iə"],
+ "eə": ["ɛɹ", "ɛ"], "ʊə": ["ʊɹ"], "ɐ": ["ʌ"],
+}
+
+
+@dataclass
+class Evidence:
+ logp: np.ndarray # (frames, vocab) log posteriors
+ hidden: np.ndarray | None # (frames, dim) features from one transformer layer, for clustering
+
+ def crop(self, start: int, end: int) -> "Evidence":
+ start, end = max(0, start), min(len(self.logp), end)
+ return Evidence(self.logp[start:end], None if self.hidden is None else self.hidden[start:end])
+
+
+class PhoneModel:
+ def __init__(self, model_id: str = DEFAULT_MODEL, hidden_layer: int | None = None):
+ from huggingface_hub import hf_hub_download
+ from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2ForCTC
+
+ self.model_id = model_id
+ self.extractor = Wav2Vec2FeatureExtractor.from_pretrained(model_id)
+ self.model = Wav2Vec2ForCTC.from_pretrained(model_id).eval()
+ with open(hf_hub_download(model_id, "vocab.json"), encoding="utf-8") as f:
+ vocab = json.load(f)
+ if vocab and isinstance(next(iter(vocab.values())), dict): # multilingual vocab files nest by language
+ vocab = next(iter(vocab.values()))
+ self.tok2id = vocab
+ self.id2tok = {i: t for t, i in vocab.items()}
+ self.blank = self.model.config.pad_token_id
+ self.special = {i for t, i in vocab.items() if t.startswith("<") and t.endswith(">")} | {self.blank}
+ self.hidden_layer = hidden_layer
+
+ @torch.no_grad()
+ def run(self, audio: np.ndarray, sr: int = 16000) -> Evidence:
+ inputs = self.extractor(audio, sampling_rate=sr, return_tensors="pt")
+ out = self.model(inputs.input_values, output_hidden_states=self.hidden_layer is not None)
+ logp = torch.log_softmax(out.logits[0].float(), dim=-1).numpy()
+ hidden = None
+ if self.hidden_layer is not None:
+ hidden = out.hidden_states[self.hidden_layer][0].float().numpy()
+ return Evidence(logp, hidden)
+
+ def has(self, seg: str) -> bool:
+ return seg in self.tok2id
+
+ def to_ids(self, segs: list[str]) -> list[int]:
+ ids = []
+ for s in segs:
+ if s in self.tok2id:
+ ids.append(self.tok2id[s])
+ continue
+ alt = next((a for a in FALLBACKS.get(s, []) if a in self.tok2id), None)
+ if alt is not None:
+ ids.append(self.tok2id[alt])
+ continue
+ # split unknown clusters (e.g. diphthongs) into known symbols
+ parts, i = [], 0
+ while i < len(s):
+ for j in range(len(s), i, -1):
+ if s[i:j] in self.tok2id:
+ parts.append(self.tok2id[s[i:j]])
+ i = j
+ break
+ else:
+ raise KeyError(f"phone {s!r} cannot be expressed in {self.model_id}'s vocabulary")
+ ids.extend(parts)
+ return ids
+
+ def greedy(self, ev: Evidence) -> list[tuple[str, int, int]]:
+ """Free phone decoding: (phone, first frame, last frame) per emitted phone."""
+ best = ev.logp.argmax(-1)
+ out, prev = [], None
+ for t, k in enumerate(best):
+ k = int(k)
+ if k != prev and k not in self.special:
+ out.append([self.id2tok[k], t, t])
+ elif k == prev and out and k not in self.special:
+ out[-1][2] = t
+ prev = k
+ return [tuple(x) for x in out]
+
+ def nll(self, ev: Evidence, ids: list[int]) -> float:
+ """Negative CTC log-likelihood of a phone sequence (inf when it cannot fit the frames)."""
+ if not ids:
+ return float(-ev.logp[:, self.blank].sum())
+ lp = torch.from_numpy(ev.logp).unsqueeze(1)
+ loss = torch.nn.functional.ctc_loss(
+ lp, torch.tensor([ids]), torch.tensor([lp.shape[0]]), torch.tensor([len(ids)]),
+ blank=self.blank, reduction="sum", zero_infinity=False,
+ )
+ return float(loss)
+
+ def align(self, ev: Evidence, ids: list[int]) -> list[tuple[int, int]]:
+ """Frame span of each phone in ids, by CTC forced alignment."""
+ import torchaudio.functional as AF
+
+ emissions = torch.from_numpy(ev.logp).unsqueeze(0)
+ labels, _ = AF.forced_align(emissions, torch.tensor([ids], dtype=torch.int32), blank=self.blank)
+ labels = labels[0].tolist()
+ spans, k, prev = [], -1, self.blank
+ for t, lab in enumerate(labels):
+ if lab != self.blank and (lab != prev or prev == self.blank):
+ k += 1
+ spans.append([t, t])
+ elif lab != self.blank:
+ spans[k][1] = t
+ prev = lab
+ if len(spans) != len(ids):
+ raise RuntimeError("alignment did not recover every phone")
+ return [tuple(s) for s in spans]
+
+
+@dataclass
+class SlotScore:
+ label: str # the variant (e.g. "t")
+ segs: tuple[str, ...] # the full word as scored
+ nll: float
+ posterior: float
+
+
+# spellings a phone model may prefer for the same variant class; a class is scored by its best spelling
+SPELLINGS = {
+ "t": [["t"], ["t̪"]], "d": [["d"], ["d̪"]], "s": [["s"], ["s̪"]], "ɜː": [["ɜː"], ["ɜ"], ["ɚ"]],
+ "ɔ": [["ɔ"], ["ɔː"], ["ɒ"]], "a": [["a"], ["aː"], ["æ"], ["ɑ"], ["ɑː"]], "ɛ": [["ɛ"], ["ɛː"]],
+ "e": [["e"], ["eː"]], "o": [["o"], ["oː"]], "iː": [["iː"], ["i"]], "i": [["i"], ["iː"]],
+ "əʊ": [["əʊ"], ["oʊ"]], "eɪ": [["eɪ"], ["ei"]], "ʌ": [["ʌ"], ["ɐ"]], "uː": [["uː"], ["u"]],
+}
+
+
+def score_slot(model: PhoneModel, ev: Evidence, word: list[str], slot: int, variants: dict,
+ context: dict[int, list[list[str]]] | None = None, temperature: float = 1.0,
+ offsets: dict[str, float] | None = None) -> list[SlotScore]:
+ """Forced choice among the variants for word[slot].
+
+ variants maps a label to the segments that replace word[slot] ([] for deletion), or to a list of
+ alternative spellings (lists of segments), scored by the best one. context optionally lists
+ alternative realisations for other slots (e.g. KIT as ɪ or i); each variant is scored with its
+ best-fitting context so accent features elsewhere in the word do not bias the comparison."""
+ context = context or {}
+ others = [i for i in range(len(word)) if i != slot]
+ alts = [context.get(i, [[word[i]]]) for i in others]
+ scores = []
+ for label, reps in variants.items():
+ if not reps or isinstance(reps[0], str):
+ reps = [reps]
+ best_nll, best_segs = math.inf, None
+ for rep in reps:
+ for combo in itertools.product(*alts):
+ segs = []
+ for i in range(len(word)):
+ if i == slot:
+ segs.extend(rep)
+ else:
+ segs.extend(combo[others.index(i)])
+ try:
+ ids = model.to_ids(segs)
+ except KeyError:
+ continue
+ v = model.nll(ev, ids)
+ if v < best_nll:
+ best_nll, best_segs = v, tuple(segs)
+ scores.append(SlotScore(label, best_segs or tuple(), best_nll, 0.0))
+ # calibrated score: -nll / T + offset (offsets correct the model's systematic biases; see calibrate.py)
+ offsets = offsets or {}
+ logits = [-s.nll / temperature + offsets.get(s.label, 0.0) if math.isfinite(s.nll) else -math.inf for s in scores]
+ top = max(logits)
+ if math.isfinite(top):
+ weights = [math.exp(z - top) if math.isfinite(z) else 0.0 for z in logits]
+ total = sum(weights)
+ for s, w in zip(scores, weights):
+ s.posterior = w / total
+ order = sorted(range(len(scores)), key=lambda i: (-logits[i], scores[i].nll))
+ return [scores[i] for i in order]
+
+
+# phones an outside-the-candidates realisation may be reported as: plain IPA consonants and vowels,
+# not the multilingual vocabulary's tone-numbered or language-specific tokens
+_OPEN_SET_OK = set("pbtdkɡqʔmnŋɲɳfvθðszʃʒçxɣχhɦlɹrɾɻjwʋɸβaeiouæɑɒɔəɛɜɪʊʌɐɨʉøœy") | {"tʃ", "dʒ", "ts", "kp", "ɡb", "t̪"}
+
+
+def classify_slot(model: PhoneModel, ev: Evidence, word: list[str], slot: int, candidates: list[str],
+ context: dict[int, list[list[str]]] | None = None, temperature: float = 1.0,
+ open_set: int = 0, offsets: dict[str, float] | None = None, margin: float = 1.0) -> list[SlotScore]:
+ """Score the unit's candidate variants (each over its usual spellings).
+
+ With open_set > 0, the phones the model hears most in the slot are scored too, so a realisation
+ outside the candidate set can be reported under its own symbol; an outside phone is kept only if it
+ beats every candidate by `margin` nats. Off by default: on the Nigerian gold set it never improved
+ accuracy. If no candidate fits the frames (clip shorter than the word), every score is infinite and
+ every posterior 0; callers should drop such tokens."""
+ variants = {c: SPELLINGS.get(c, [[c]]) for c in candidates}
+ scores = score_slot(model, ev, word, slot, variants, context, temperature, offsets)
+ if open_set <= 0 or not math.isfinite(scores[0].nll):
+ return scores
+ try:
+ ids = model.to_ids(list(scores[0].segs))
+ spans = model.align(ev, ids)
+ before = len(model.to_ids([s for i, s in enumerate(scores[0].segs) if i < slot]))
+ lo, hi = spans[before][0], spans[before][1] + 1
+ except (KeyError, RuntimeError, IndexError):
+ return scores
+ known = {seg for reps in variants.values() for rep in reps for seg in rep}
+ mass = np.exp(ev.logp[lo:hi]).mean(0)
+ extra = {}
+ for k in np.argsort(-mass):
+ tok = model.id2tok[int(k)]
+ if int(k) in model.special or tok in known or tok in extra or tok not in _OPEN_SET_OK:
+ continue
+ extra[tok] = [tok]
+ if len(extra) >= open_set:
+ break
+ outside = score_slot(model, ev, word, slot, extra, context, temperature, offsets) if extra else []
+ best_known = scores[0].nll
+ winners = {o.label: extra[o.label] for o in outside if o.nll < best_known - margin * temperature}
+ return score_slot(model, ev, word, slot, {**variants, **winners}, context, temperature, offsets) if winners else scores
diff --git a/backend/pg/pipeline.py b/backend/pg/pipeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ed709ce4e7a1adafb0a63649c87e1f196da3f54
--- /dev/null
+++ b/backend/pg/pipeline.py
@@ -0,0 +1,508 @@
+"""End-to-end Preference Grammar analysis.
+
+recordings of target words -> where the words are -> which variant of the unit each speaker produced
+-> two-level clusters -> candidates with violation marks -> operability table -> preferred form.
+"""
+from __future__ import annotations
+
+import math
+import random
+import re
+from collections import Counter, defaultdict
+from dataclasses import asdict, dataclass, field, replace
+from pathlib import Path
+
+import numpy as np
+
+from . import audio as audio_io
+from . import calibrate as calibration
+from . import lexicon
+from .cluster import Clustering, two_level
+from .ot import DEFAULT_RANKING, Candidate, Tableau, evaluate
+from .phones import DEFAULT_MODEL, FRAME_RATE, Evidence, PhoneModel, classify_slot
+from .tenets import Settings, Unit, _overrides as _raw_overrides, assess, common_words, load_typology, load_units, share_dependent, tiers
+
+RESOURCES = Path(__file__).resolve().parents[1] / "data" / "resources"
+
+
+@dataclass
+class Recording:
+ name: str
+ audio: np.ndarray
+ speaker: str = ""
+ transcript: str = "" # empty: the recording is just the target word; "auto": find the words by ASR
+ diarize: bool | None = None # separate speakers inside the recording; None: yes for "auto" recordings with no speaker id
+ num_speakers: int | None = None # how many people talk in it, if known (else estimated)
+
+
+@dataclass
+class Token:
+ recording: str
+ speaker: str
+ word: str
+ start: float
+ end: float
+ variant: str
+ posterior: float
+ scores: dict
+ realised: str # the best-fitting form of the whole word, in IPA
+ heard: str # free phone decoding of the word, for comparison
+ primary: str = ""
+ secondary: str = ""
+ review: bool = False
+ nll: dict = field(default_factory=dict) # raw CTC scores per variant, for recalibration
+
+
+@dataclass
+class Analysis:
+ words: list[str]
+ unit: Unit
+ canonical: dict
+ tokens: list[Token]
+ clustering: Clustering | None
+ candidates: list[Candidate]
+ tableau: Tableau | None
+ preferred: list[str]
+ warnings: list[str] = field(default_factory=list)
+ stability: dict | None = None # how often each variant wins when speakers are resampled
+ superfluous: list[Candidate] = field(default_factory=list) # attested too rarely to compete
+
+ def to_dict(self) -> dict:
+ tab = self.tableau
+ return {
+ "words": self.words,
+ "unit": asdict(self.unit),
+ "canonical": self.canonical,
+ "tokens": [asdict(t) for t in self.tokens],
+ "clusters": None if self.clustering is None else {
+ "categories": self.clustering.categories,
+ "contrast_matrix": np.round(self.clustering.contrast, 4).tolist(),
+ "separation": {k: (None if math.isnan(v) else round(v, 4)) for k, v in self.clustering.separation.items()},
+ "subclusters": dict(Counter(self.clustering.secondary)),
+ },
+ "candidates": [
+ {"form": c.form, "segment": c.segment, "tokens": c.tokens, "share": round(c.share, 4),
+ "tier": (tiers(tab) if tab else {}).get(c.segment, ""),
+ "violations": {t: asdict(v) for t, v in c.violations.items()}}
+ for c in self.candidates
+ ],
+ "superfluous": [{"form": c.form, "segment": c.segment, "tokens": c.tokens, "share": round(c.share, 4)}
+ for c in self.superfluous],
+ "tableau": None if tab is None else {
+ "ranking": tab.ranking, "rows": tab.to_rows(), "markdown": tab.to_markdown(), "html": tab.to_html(),
+ "tie": tab.tie,
+ },
+ "preferred": self.preferred,
+ "stability": self.stability,
+ "warnings": self.warnings,
+ }
+
+
+class Analyzer:
+ def __init__(self, phone_model: str = DEFAULT_MODEL, hidden_layer: int | None = 12, resources: Path = RESOURCES):
+ from .kb.fetch import ensure
+
+ ensure(resources)
+ self.phones = PhoneModel(phone_model, hidden_layer=hidden_layer)
+ self.lexicons = lexicon.load_default(resources, names=("britfone", "cmudict"))
+ self.units = load_units()
+ self.typology = load_typology()
+ self.calibration = calibration.load()
+ self._aligner = None
+ self._transcriber = None
+ self._diarizer = None
+ self._turns = {}
+ self._vocabulary = None
+
+ @property
+ def aligner(self):
+ if self._aligner is None:
+ from .align import WordAligner
+
+ self._aligner = WordAligner()
+ return self._aligner
+
+ @property
+ def transcriber(self):
+ if self._transcriber is None:
+ from .asr import Transcriber
+
+ self._transcriber = Transcriber()
+ return self._transcriber
+
+ @property
+ def diarizer(self):
+ if self._diarizer is None:
+ from .diarize import Diarizer
+
+ self._diarizer = Diarizer()
+ return self._diarizer
+
+ def speaker_turns(self, rec: Recording):
+ """Who speaks when in a recording with several speakers (None when it is not to be separated)."""
+ wanted = rec.diarize if rec.diarize is not None else (rec.transcript.strip().lower() == "auto" and not rec.speaker)
+ if not wanted:
+ return None
+ key = (rec.name, len(rec.audio), rec.num_speakers)
+ if key not in self._turns:
+ speech = None
+ if rec.transcript.strip().lower() == "auto":
+ speech = [(w.start, w.end) for w in self.transcriber.words(rec.audio)]
+ self._turns[key] = self.diarizer(rec.audio, speech, rec.num_speakers)
+ return self._turns[key]
+
+ def merger_neighbours(self, canonical: dict, unit: Unit) -> dict[str, str]:
+ """Real words a variant pronunciation of each target word sounds like (three [tɹiː] -> 'tree'),
+ so ASR transcripts that wrote the variant as another word still yield the token."""
+ if self._vocabulary is None:
+ self._vocabulary = common_words(20000)
+ out = {}
+ for word, segs in canonical.items():
+ for slot in self.slots(segs, unit):
+ for c in unit.candidates:
+ if c in lexicon.same_phoneme(unit.phoneme):
+ continue
+ for lex in self.lexicons.values():
+ for alt in lexicon.same_phoneme(c):
+ form = segs[:slot] + [alt] + segs[slot + 1:]
+ for w in lex.homophones(form, exclude=word):
+ if w not in canonical and (self._vocabulary is None or w in self._vocabulary):
+ out[w] = word
+ return out
+
+ def _evidence(self, audio: np.ndarray, start: float, end: float, context_s: float = 1.0, margin: int = 2) -> Evidence:
+ """Phone evidence for one word: the model hears a second of context either side (bounded memory
+ on long recordings) and the frames are then cut to the word."""
+ lo = max(0, int((start - context_s) * 16000))
+ hi = min(len(audio), int((end + context_s) * 16000))
+ ev = self.phones.run(audio[lo:hi])
+ offset = lo / 16000
+ return ev.crop(int((start - offset) * FRAME_RATE) - margin, int(math.ceil((end - offset) * FRAME_RATE)) + margin)
+
+ def pronunciations(self, word: str) -> list[list[str]]:
+ for name in ("britfone", "cmudict"):
+ lex = self.lexicons.get(name)
+ if lex and lex.pronunciations(word):
+ return [list(p) for p in lex.pronunciations(word)]
+ raise KeyError(f"'{word}' is not in the pronouncing lexicons; give its pronunciation explicitly")
+
+ def canonical(self, word: str, unit: Unit | None = None) -> list[str]:
+ """The reference pronunciation; with a unit, the first one containing it (lexicons list weak forms
+ such as 'will' [wəl] first)."""
+ prons = self.pronunciations(word)
+ if unit is not None:
+ for p in prons:
+ if self.slots(p, unit):
+ return p
+ return prons[0]
+
+ def slots(self, segs: list[str], unit: Unit) -> list[int]:
+ match = lexicon.same_phoneme(unit.phoneme)
+ return [i for i, s in enumerate(segs) if s in match]
+
+ def units_in(self, word: str) -> list[Unit]:
+ segs = self.canonical(word)
+ return [u for u in self.units.values() if self.slots(segs, u)]
+
+ def _context(self, segs: list[str], slot: int) -> dict[int, list[list[str]]]:
+ """Plausible alternative realisations for the other vowels/units of the word, so an accent
+ feature elsewhere in the word cannot bias the decision about the slot under study."""
+ ctx = {}
+ for i, s in enumerate(segs):
+ if i == slot:
+ continue
+ for u in self.units.values():
+ if s in lexicon.same_phoneme(u.phoneme):
+ ctx[i] = [[s]] + [[c] for c in u.candidates[:3] if c != s]
+ break
+ while math.prod(len(v) for v in ctx.values()) > 64:
+ ctx.pop(next(iter(ctx)))
+ return ctx
+
+ def _token(self, rec: Recording, word: str, segs: list[str], slot: int, unit: Unit, ev: Evidence,
+ start: float, end: float, settings: Settings, speaker: str | None = None) -> tuple[Token, np.ndarray | None]:
+ calib = self.calibration.get(unit.key, {}) if settings.calibrated else {}
+ scores = classify_slot(self.phones, ev, segs, slot, unit.candidates, context=self._context(segs, slot),
+ temperature=calib.get("temperature", 1.0), offsets=calib.get("offsets"))
+ best = scores[0]
+ if not math.isfinite(best.nll):
+ return None, None
+ heard = " ".join(p for p, _, _ in self.phones.greedy(ev))
+ emb = None
+ if ev.hidden is not None and math.isfinite(best.nll):
+ ids = self.phones.to_ids(list(best.segs))
+ try:
+ spans = self.phones.align(ev, ids)
+ # the slot's phones sit after the phones of the segments before it
+ before = len(self.phones.to_ids(list(best.segs[:slot])))
+ n = len(self.phones.to_ids([best.label]))
+ lo, hi = spans[before][0], spans[before + n - 1][1] + 1
+ emb = ev.hidden[lo:hi].mean(0)
+ except (RuntimeError, IndexError, KeyError):
+ emb = None
+ tok = Token(rec.name, speaker or rec.speaker or rec.name, word, round(start, 3), round(end, 3), best.label,
+ round(best.posterior, 4), {s.label: round(s.posterior, 4) for s in scores},
+ "".join(best.segs), heard,
+ nll={s.label: (round(s.nll, 4) if math.isfinite(s.nll) else None) for s in scores})
+ tok.review = best.posterior < settings.review_below
+ return tok, emb
+
+ def analyse(self, recordings: list[Recording], words: list[str], unit_key: str | None = None,
+ ranking=DEFAULT_RANKING, settings: Settings | None = None, max_candidates: int = 5) -> Analysis:
+ settings = settings or Settings()
+ words = [w.lower().strip() for w in words if w.strip()]
+ if not words:
+ raise ValueError("give at least one target word")
+ prons = {w: self.pronunciations(w) for w in words}
+ if unit_key:
+ if unit_key not in self.units:
+ raise ValueError(f"unknown unit {unit_key!r}; choose one of {', '.join(self.units)}")
+ unit = self.units[unit_key]
+ else:
+ shared = [u for u in self.units.values() if all(any(self.slots(p, u) for p in prons[w]) for w in words)]
+ if not shared:
+ raise ValueError("no unit in the knowledge base occurs in every target word; choose one")
+ unit = shared[0]
+ canonical = {w: self.canonical(w, unit) for w in words}
+ missing = [w for w in words if not self.slots(canonical[w], unit)]
+ if missing:
+ raise ValueError(f"{unit.label} (/{unit.phoneme}/) does not occur in: {', '.join(missing)}")
+ warnings, tokens, embeddings = [], [], []
+ unfit = 0
+ per_word = Counter()
+
+ def add(tok, emb, low_alignment=False):
+ nonlocal unfit
+ if tok is None:
+ unfit += 1
+ return
+ tok.review = tok.review or low_alignment
+ tokens.append(tok)
+ embeddings.append(emb)
+
+ validation = unit.validation or {}
+ if validation.get("status") != "validated":
+ warnings.append(f"{unit.label}: the variant classifier is not validated for this unit "
+ f"({validation.get('note', 'no human-labelled test yet')}); check tokens by ear before relying on the shares")
+ for rec in recordings:
+ if not rec.transcript.strip():
+ clip, offset = audio_io.trim(rec.audio)
+ if len(clip) > settings.max_word_seconds * 16000:
+ warnings.append(f"{rec.name}: {len(clip) / 16000:.0f} s is too long for a single-word recording; "
+ "give its transcript (or 'auto') so the target words can be located")
+ continue
+ word = words[0] if len(words) == 1 else _guess_word(rec.name, words)
+ if word is None:
+ warnings.append(f"{rec.name}: several target words given; name the file after its word or add a transcript")
+ continue
+ ev = self.phones.run(clip)
+ for slot in self.slots(canonical[word], unit):
+ add(*self._token(rec, word, canonical[word], slot, unit, ev, offset, offset + len(clip) / 16000, settings))
+ continue
+ if rec.transcript.strip().lower() == "auto":
+ from .asr import find_targets
+
+ # also search for words a stopped/fronted realisation could be transcribed as (three -> tree)
+ aliases = self.merger_neighbours(canonical, unit)
+ hits = find_targets(rec.audio, self.transcriber.words(rec.audio), set(canonical) | set(aliases), self.aligner)
+ spans = []
+ for h in hits:
+ if h.span.word in aliases:
+ h.span.word = aliases[h.span.word]
+ spans.append(h.span)
+ if not spans:
+ warnings.append(f"{rec.name}: no target word was heard clearly in the automatic transcript")
+ continue
+ else:
+ spans = [s for s in self.aligner.align(rec.audio, rec.transcript) if s.word in canonical]
+ if not spans:
+ warnings.append(f"{rec.name}: none of the target words occur in its transcript")
+ continue
+ turns = self.speaker_turns(rec)
+ if turns is not None:
+ warnings.append(f"{rec.name}: speakers separated automatically ({turns.speakers} found"
+ f"{'' if rec.num_speakers is None else ', as given'}); labels are anonymous")
+ if settings.max_tokens_per_word:
+ spans = _spread(spans, settings.max_tokens_per_word, per_word)
+ for span in spans:
+ if settings.max_tokens_per_word and per_word[span.word] >= settings.max_tokens_per_word:
+ continue
+ per_word[span.word] += 1
+ speaker = None
+ if turns is not None:
+ who = turns.speaker_at(span.start, span.end)
+ speaker = f"{rec.speaker or rec.name}:{who or 'unknown'}"
+ ev = self._evidence(rec.audio, span.start, span.end)
+ for slot in self.slots(canonical[span.word], unit):
+ add(*self._token(rec, span.word, canonical[span.word], slot, unit, ev, span.start, span.end, settings,
+ speaker), low_alignment=span.score < settings.min_alignment_score)
+ if unfit:
+ warnings.append(f"{unfit} token(s) dropped: the audio was too short for any candidate pronunciation of the word")
+ if not tokens:
+ return Analysis(words, unit, {w: "".join(s) for w, s in canonical.items()}, [], None, [], None, [], warnings, None)
+
+ labels = [t.variant for t in tokens]
+ emb = np.stack(embeddings) if all(e is not None for e in embeddings) else None
+ clustering = two_level(labels, emb)
+ for t, p, s in zip(tokens, clustering.primary, clustering.secondary):
+ t.primary, t.secondary = p, s
+
+ counts, share = variant_shares(tokens, settings.freq_weighting)
+ # candidate forms are shown on the target word with the most tokens
+ example_word = Counter(t.word for t in tokens).most_common(1)[0][0]
+ example = canonical[example_word]
+ slot0 = self.slots(example, unit)[0]
+ attested = []
+ for seg in sorted(counts, key=lambda s: (-share[s], -counts[s])):
+ form = "".join(example[:slot0] + [seg] + example[slot0 + 1:])
+ attested.append(Candidate(form, seg, tokens=counts[seg], share=share[seg]))
+ if self._vocabulary is None:
+ self._vocabulary = common_words(settings.disam_vocabulary)
+ assess(attested, unit, words, list(self.lexicons.values()), self.typology, settings, self._vocabulary)
+ possible = sorted({lab for t in tokens for lab, p in t.scores.items() if p > 0} - set(counts))
+ unseen = [Candidate("".join(example[:slot0] + [seg] + example[slot0 + 1:]), seg) for seg in possible]
+ assess(unseen, unit, words, list(self.lexicons.values()), self.typology, settings, self._vocabulary)
+ admitted = admit(tokens, attested, settings)
+ if not admitted:
+ warnings.append(f"no variant reached {settings.min_tokens} tokens from {settings.min_speakers} speakers; "
+ "all attested variants compete")
+ admitted = attested
+ candidates = admitted[:max_candidates]
+ superfluous = [c for c in attested if c not in candidates]
+ tableau = evaluate(candidates, ranking, unit=unit.label)
+ stability = preferred_stability(tokens, attested + unseen, unit, self.typology, ranking, settings, max_candidates)
+ return Analysis(words, unit, {w: "".join(s) for w, s in canonical.items()}, tokens, clustering, candidates,
+ tableau, [c.form for c in tableau.winners], warnings, stability, superfluous)
+
+
+def _spread(spans: list, cap: int, used: Counter) -> list:
+ """Keep at most `cap` spans of each word (fewer if some were used already), evenly spaced through the
+ recording, so a capped word samples the whole of a long recording and all its speakers, not its opening."""
+ by = defaultdict(list)
+ for s in spans:
+ by[s.word].append(s)
+ keep = set()
+ for word, group in by.items():
+ room = max(0, cap - used[word])
+ if len(group) <= room:
+ keep.update(map(id, group))
+ elif room:
+ keep.update(id(group[round(i * (len(group) - 1) / max(1, room - 1))]) for i in range(room))
+ return [s for s in spans if id(s) in keep]
+
+
+# function words with reduced (weak) forms, or
that may be voiced or voiceless: poor evidence for a sound
+SURVEY_SKIP = {"the", "a", "an", "to", "of", "and", "or", "her", "were", "with", "within", "without", "was", "for"}
+
+
+def survey(analyzer: "Analyzer", recordings: list[Recording], ranking=DEFAULT_RANKING, settings: Settings | None = None,
+ min_occurrences: int = 3, per_word_cap: int = 40) -> dict[str, Analysis]:
+ """Analyse every sound in the knowledge base from the same recordings: for each unit, the target words are
+ the words of the transcripts (or of the automatic transcript, cached) that contain that sound."""
+ from dataclasses import replace as _replace
+
+ settings = _replace(settings or Settings(), max_tokens_per_word=per_word_cap)
+ counts = Counter()
+ for rec in recordings:
+ t = rec.transcript.strip()
+ if t.lower() == "auto":
+ counts.update(w.word for w in analyzer.transcriber.words(rec.audio))
+ elif t:
+ from .align import words_of
+
+ counts.update(words_of(t))
+ results = {}
+ for key, unit in analyzer.units.items():
+ words = []
+ for w, n in counts.items():
+ if n < min_occurrences or w in SURVEY_SKIP:
+ continue
+ try:
+ prons = analyzer.pronunciations(w)
+ except KeyError:
+ continue
+ if any(analyzer.slots(p, unit) for p in prons):
+ words.append(w)
+ if not words:
+ continue
+ results[key] = analyzer.analyse(recordings, sorted(words), key, ranking, settings)
+ return results
+
+
+def admit(tokens: list[Token], attested: list[Candidate], settings: Settings) -> list[Candidate]:
+ """Variants compete only when attested often enough (min_tokens from min_speakers), so that a few
+ misheard tokens cannot introduce candidates; expert overrides admit a variant regardless."""
+ speakers = defaultdict(set)
+ for t in tokens:
+ speakers[t.variant].add(t.speaker)
+ forced = {seg for (seg, _), _ in _expert_overrides(settings)}
+ return [c for c in attested
+ if c.segment in forced or (c.tokens >= settings.min_tokens and len(speakers[c.segment]) >= settings.min_speakers)]
+
+
+def variant_shares(tokens: list[Token], weighting: str = "tokens") -> tuple[Counter, dict]:
+ """Token counts per variant and each variant's share, either of all tokens or averaged over speakers."""
+ counts = Counter(t.variant for t in tokens)
+ if weighting == "speakers":
+ by = defaultdict(Counter)
+ for t in tokens:
+ by[t.speaker][t.variant] += 1
+ share = {v: sum(c[v] / sum(c.values()) for c in by.values()) / len(by) for v in counts}
+ else:
+ total = sum(counts.values())
+ share = {v: n / total for v, n in counts.items()}
+ return counts, share
+
+
+def _draw(t: Token, rng: random.Random) -> str:
+ labels = [l for l, p in t.scores.items() if p > 0]
+ if not labels:
+ return t.variant
+ return rng.choices(labels, weights=[t.scores[l] for l in labels])[0]
+
+
+def preferred_stability(tokens: list[Token], attested: list[Candidate], unit: Unit, typology: dict, ranking,
+ settings: Settings, max_candidates: int = 5, n: int = 1000, seed: int = 0) -> dict | None:
+ """How often each variant is preferred when the speakers are resampled with replacement.
+ Each token's label is redrawn from its posterior in every resample. Only FreQ and Ped-C depend on
+ the sample; every other mark is fixed per variant."""
+ by = defaultdict(list)
+ for t in tokens:
+ by[t.speaker].append(t)
+ speakers = sorted(by)
+ if len(speakers) < 3:
+ return None
+ base = {c.segment: c for c in attested}
+ frozen = {(seg, tenet) for (seg, tenet), _ in _expert_overrides(settings)}
+ rng = random.Random(seed)
+ wins = Counter()
+ for _ in range(n):
+ drawn = [t for s in rng.choices(speakers, k=len(speakers)) for t in by[s]]
+ # each token's variant is drawn from its posterior, so classifier uncertainty is propagated too
+ sample = [replace(t, variant=_draw(t, rng)) for t in drawn]
+ counts, share = variant_shares(sample, settings.freq_weighting)
+ cands = []
+ top = max(share.values())
+ for seg in sorted(counts, key=lambda s: (-share[s], -counts[s])):
+ v = dict(base[seg].violations)
+ for tenet, mark in share_dependent(seg, share[seg], counts[seg], unit, typology, settings, top).items():
+ if (seg, tenet) not in frozen:
+ v[tenet] = mark
+ cands.append(Candidate(base[seg].form, seg, counts[seg], share[seg], v))
+ cands = admit(sample, cands, settings)[:max_candidates] or cands[:max_candidates]
+ winners = evaluate(cands, ranking).winners
+ for w in winners:
+ wins[w.segment] += 1 / len(winners)
+ return {"resamples": n, "speakers": len(speakers),
+ "preferred_rate": {seg: round(k / n, 3) for seg, k in wins.most_common()}}
+
+
+
+def _expert_overrides(settings: Settings) -> list:
+ return _raw_overrides(settings.overrides)
+
+
+def _guess_word(name: str, words: list[str]) -> str | None:
+ parts = set(re.split(r"[^a-z']+", Path(name).stem.lower()))
+ hits = [w for w in words if w in parts]
+ return max(hits, key=len) if hits else None
diff --git a/backend/pg/report.py b/backend/pg/report.py
new file mode 100644
index 0000000000000000000000000000000000000000..7cf30154f84317c3426107d78874d3e99571a44d
--- /dev/null
+++ b/backend/pg/report.py
@@ -0,0 +1,113 @@
+"""Write an Analysis to the files the PG framework calls for (CSV, VTT, JSON and an HTML report)."""
+from __future__ import annotations
+
+import csv
+import html
+import io
+import json
+from collections import defaultdict
+from pathlib import Path
+
+from .pipeline import Analysis
+
+
+def _csv(rows: list[list]) -> str:
+ buf = io.StringIO()
+ csv.writer(buf).writerows(rows)
+ return buf.getvalue()
+
+
+def tokens_csv(a: Analysis) -> str:
+ rows = [["recording", "speaker", "word", "start", "end", "variant", "posterior", "cluster", "subcluster", "review",
+ "realised", "heard", "scores"]]
+ for t in a.tokens:
+ rows.append([t.recording, t.speaker, t.word, t.start, t.end, t.variant, t.posterior, t.primary, t.secondary,
+ t.review, t.realised, t.heard, json.dumps(t.scores, ensure_ascii=False)])
+ return _csv(rows)
+
+
+def subclusters_csv(a: Analysis) -> str:
+ """Members of every sub-cluster, one column each, with the phoneme under study at cell (0,0)."""
+ groups = defaultdict(list)
+ for t in a.tokens:
+ groups[t.secondary].append(f"{t.recording}@{t.start:.2f}")
+ names = sorted(groups, key=lambda g: (-len(groups[g]), g))
+ rows = [[a.unit.phoneme] + names]
+ for i in range(max((len(v) for v in groups.values()), default=0)):
+ rows.append([""] + [groups[g][i] if i < len(groups[g]) else "" for g in names])
+ return _csv(rows)
+
+
+def contrast_csv(a: Analysis) -> str:
+ if a.clustering is None:
+ return ""
+ cats = a.clustering.categories
+ rows = [[a.unit.phoneme] + cats]
+ for i, c in enumerate(cats):
+ rows.append([c] + [round(float(x), 4) for x in a.clustering.contrast[i]])
+ return _csv(rows)
+
+
+def vtt(a: Analysis, recording: str) -> str:
+ def ts(s: float) -> str:
+ return f"{int(s // 3600):02d}:{int(s % 3600 // 60):02d}:{s % 60:06.3f}"
+
+ cues = ["WEBVTT", ""]
+ for t in (t for t in a.tokens if t.recording == recording):
+ cues += [f"{ts(t.start)} --> {ts(t.end)}", f"{t.word} [{t.realised}] {a.unit.label}={t.variant} (p={t.posterior:.2f})", ""]
+ return "\n".join(cues)
+
+
+def html_report(a: Analysis) -> str:
+ tab = a.tableau
+ rows = "".join(
+ f"
" for w in a.warnings)
+ preferred = ", ".join(html.escape(p) for p in a.preferred) or "—"
+ stab = ""
+ if a.stability:
+ rates = ", ".join(f"[{html.escape(k)}] {v:.0%}" for k, v in a.stability["preferred_rate"].items())
+ top = max(a.stability["preferred_rate"].values())
+ caution = "" if top >= 0.8 else (" Not stable: the preferred form depends on which speakers are included; "
+ "collect more speakers or check the low-confidence tokens.")
+ stab = (f"
Preferred in resamples of the {a.stability['speakers']} speakers "
+ f"({a.stability['resamples']} bootstrap draws): {rates}.{caution}
")
+ return f"""PG analysis
+
Preference Grammar analysis: {html.escape(a.unit.label)} in {html.escape(', '.join(a.words))}
+
Preferred form: {preferred}
{stab}
+
Operability table
{tab.to_html() if tab else '
No tokens.
'}
+
Ranking: {html.escape(' >> '.join(','.join(s) for s in tab.ranking)) if tab else ''}. Hover a cell for the evidence behind each mark.
+
Attested candidates
{cands}
+
Tokens
Highlighted rows are below the confidence threshold and should be checked by ear.
+
recording
speaker
word
time (s)
variant
posterior
sub-cluster
free phone decoding
{rows}
+{'
Warnings
' + warn + '
' if warn else ''}"""
+
+
+def write_all(a: Analysis, out_dir: Path) -> list[Path]:
+ out = Path(out_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ files = {
+ "analysis.json": json.dumps(a.to_dict(), ensure_ascii=False, indent=1),
+ "tokens.csv": tokens_csv(a),
+ "subclusters.csv": subclusters_csv(a),
+ "contrast_matrix.csv": contrast_csv(a),
+ "operability_table.csv": a.tableau.to_csv() if a.tableau else "",
+ "report.html": html_report(a),
+ }
+ for rec in sorted({t.recording for t in a.tokens}):
+ files[f"vtt/{Path(rec).stem}.vtt"] = vtt(a, rec)
+ written = []
+ for name, text in files.items():
+ p = out / name
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(text, encoding="utf-8")
+ written.append(p)
+ return written
diff --git a/backend/pg/review.py b/backend/pg/review.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ace9ae4a9328c177b9301b71c629b87bfde5a64
--- /dev/null
+++ b/backend/pg/review.py
@@ -0,0 +1,112 @@
+"""Human verification: export each token as a clip with a labelling page, then score the labels.
+
+python -m pg.review export