thebickersteth commited on
Commit
9b3bb37
·
verified ·
1 Parent(s): ebdd03f

Preference Grammar pipeline: one image for frontend and backend

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +5 -0
  2. .gitignore +0 -4
  3. Dockerfile +26 -18
  4. README.md +10 -247
  5. VoxPreference-frontend/.gitignore +25 -0
  6. VoxPreference-frontend/.impeccable/hook.cache.json +1 -0
  7. VoxPreference-frontend/README.md +54 -0
  8. VoxPreference-frontend/eslint.config.js +28 -0
  9. VoxPreference-frontend/index.html +13 -0
  10. VoxPreference-frontend/package-lock.json +0 -0
  11. VoxPreference-frontend/package.json +31 -0
  12. VoxPreference-frontend/src/App.css +6 -0
  13. VoxPreference-frontend/src/App.tsx +25 -0
  14. VoxPreference-frontend/src/components/AudioUploadForm.tsx +348 -0
  15. VoxPreference-frontend/src/components/Chat.tsx +132 -0
  16. VoxPreference-frontend/src/components/Modal.tsx +79 -0
  17. VoxPreference-frontend/src/components/PGAnalysis.tsx +494 -0
  18. VoxPreference-frontend/src/components/Sidebar.tsx +71 -0
  19. VoxPreference-frontend/src/components/pg/AdvancedSettings.tsx +332 -0
  20. VoxPreference-frontend/src/components/pg/AnalysisProgress.tsx +89 -0
  21. VoxPreference-frontend/src/components/pg/AnalysisResults.tsx +304 -0
  22. VoxPreference-frontend/src/components/pg/CandidateShares.tsx +119 -0
  23. VoxPreference-frontend/src/components/pg/ClusterSummary.tsx +197 -0
  24. VoxPreference-frontend/src/components/pg/Icon.tsx +61 -0
  25. VoxPreference-frontend/src/components/pg/OperabilityTable.tsx +292 -0
  26. VoxPreference-frontend/src/components/pg/RankingEditor.tsx +222 -0
  27. VoxPreference-frontend/src/components/pg/RecordingsInput.tsx +499 -0
  28. VoxPreference-frontend/src/components/pg/TierBadge.tsx +25 -0
  29. VoxPreference-frontend/src/components/pg/TokensTable.tsx +196 -0
  30. VoxPreference-frontend/src/components/pg/UnitSummary.tsx +106 -0
  31. VoxPreference-frontend/src/components/pg/ValidationBadge.tsx +23 -0
  32. VoxPreference-frontend/src/config/api.ts +23 -0
  33. VoxPreference-frontend/src/hooks/useAudioRecorder.ts +126 -0
  34. VoxPreference-frontend/src/hooks/useClipPlayer.ts +60 -0
  35. VoxPreference-frontend/src/index.css +18 -0
  36. VoxPreference-frontend/src/main.tsx +10 -0
  37. VoxPreference-frontend/src/services/api.ts +226 -0
  38. VoxPreference-frontend/src/types/pg.ts +190 -0
  39. VoxPreference-frontend/src/utils/pg.ts +390 -0
  40. VoxPreference-frontend/src/vite-env.d.ts +1 -0
  41. VoxPreference-frontend/tsconfig.app.json +26 -0
  42. VoxPreference-frontend/tsconfig.json +7 -0
  43. VoxPreference-frontend/tsconfig.node.json +24 -0
  44. VoxPreference-frontend/vite.config.ts +8 -0
  45. app.py +0 -141
  46. backend/.DS_Store +0 -0
  47. backend/README.md +11 -0
  48. backend/app.py +182 -0
  49. prepare_balanced_dataset.py → backend/eval/__init__.py +0 -0
  50. backend/eval/diarize_eval.py +125 -0
.dockerignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ VoxPreference-frontend/node_modules
2
+ VoxPreference-frontend/dist
3
+ backend/data
4
+ **/__pycache__
5
+ .git
.gitignore DELETED
@@ -1,4 +0,0 @@
1
- data/SpeechFiles
2
- dev_notes.txt
3
- .venv
4
- .DS_STORE
 
 
 
 
 
Dockerfile CHANGED
@@ -1,19 +1,27 @@
1
- FROM python:3.10.9
2
-
3
- RUN apt-get update && apt-get install -y espeak && rm -rf /var/lib/apt/lists/*
4
-
5
- RUN mkdir -p /app/hf_home && chmod -R 777 /app/hf_home
6
-
7
- RUN mkdir -p /app/numba_cache && chmod -R 777 /app/numba_cache
8
-
9
- COPY . .
10
-
11
- WORKDIR /
12
-
13
- ENV HF_HOME=/app/hf_home
14
-
15
- ENV NUMBA_CACHE_DIR=/app/numba_cache
16
-
17
- RUN pip install --no-cache-dir --upgrade -r /requirements.txt
18
-
 
 
 
 
 
 
 
 
19
  CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
1
+ # One image for the whole app: the React frontend is built, then served by the FastAPI backend.
2
+ # Works as a Hugging Face Space (sdk: docker, port 7860) or anywhere Docker runs. Needs about 3 GB of RAM.
3
+
4
+ FROM node:22-slim AS frontend
5
+ WORKDIR /frontend
6
+ COPY VoxPreference-frontend/package.json VoxPreference-frontend/package-lock.json ./
7
+ RUN npm ci
8
+ COPY VoxPreference-frontend/ ./
9
+ RUN npm run build
10
+
11
+ FROM python:3.12-slim
12
+ RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg espeak-ng && rm -rf /var/lib/apt/lists/*
13
+ WORKDIR /app/backend
14
+ # the same pins the pipeline was tested with; CPU-only PyTorch keeps the image small
15
+ COPY backend/requirements-tested.txt ./
16
+ RUN pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu -r requirements-tested.txt
17
+ COPY backend/ ./
18
+ COPY --from=frontend /frontend/dist /app/VoxPreference-frontend/dist
19
+ # lexicons and models are fetched at build time so the first analysis does not wait for downloads
20
+ ENV HF_HOME=/app/hf
21
+ 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'])"
22
+ # Hugging Face runs the container as user 1000: let it write its caches (transcripts, speaker turns)
23
+ RUN mkdir -p /app/backend/data/cache && chmod -R a+rwX /app/backend/data /app/hf
24
+ # load the models in the background as soon as the server starts
25
+ ENV PG_WARM=1
26
+ EXPOSE 7860
27
  CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,256 +1,19 @@
1
  ---
2
- title: Voxpreference
3
- emoji: 📈
4
  colorFrom: indigo
5
  colorTo: gray
6
  sdk: docker
 
7
  pinned: false
8
- short_description: speech recognition using nigerian english
9
  ---
10
 
 
11
 
12
- Read file: README.md
13
-
14
- Search files...
15
- 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:
16
-
17
- ---
18
-
19
- # Voxpreference 📈
20
-
21
- **Speech Recognition and IPA Transcription for Nigerian English**
22
-
23
- ---
24
-
25
- ## Table of Contents
26
-
27
- - [Project Overview](#project-overview)
28
- - [Features](#features)
29
- - [Architecture](#architecture)
30
- - [Demo](#demo)
31
- - [Quickstart](#quickstart)
32
- - [Running Locally (Docker)](#running-locally-docker)
33
- - [Running on Hugging Face Spaces](#running-on-hugging-face-spaces)
34
- - [API Reference](#api-reference)
35
- - [Root Endpoint `/`](#root-endpoint-)
36
- - [Health Endpoint `/health`](#health-endpoint-health)
37
- - [Transcription Endpoint `/` (POST)](#transcription-endpoint--post)
38
- - [Environment Variables](#environment-variables)
39
- - [Logging](#logging)
40
- - [Cache and Storage Management](#cache-and-storage-management)
41
- - [Development](#development)
42
- - [Finetuning the Model](#finetuning-the-model)
43
- - [Troubleshooting](#troubleshooting)
44
- - [License](#license)
45
- - [Acknowledgements](#acknowledgements)
46
-
47
- ---
48
-
49
- ## Project Overview
50
-
51
- **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.
52
-
53
- The project is designed for easy deployment on [Hugging Face Spaces](https://huggingface.co/spaces) and in Dockerized environments.
54
-
55
- ---
56
-
57
- ## Features
58
-
59
- - **Speech-to-Text**: Transcribes Nigerian English audio to text using a custom Wav2Vec2 model.
60
- - **IPA Transcription**: Converts recognized text to IPA using `phonemizer`.
61
- - **REST API**: Simple endpoints for health check and transcription.
62
- - **Production-Grade Logging**: Extensive logging for debugging and monitoring.
63
- - **Cache Management**: Configurable cache directories for model and Hugging Face data.
64
- - **Docker & Hugging Face Spaces Ready**: Optimized for containerized and cloud deployment.
65
-
66
- ---
67
-
68
- ## Architecture
69
-
70
- - **FastAPI**: Web framework for serving the API.
71
- - **Wav2Vec2**: Transformer-based ASR model, fine-tuned for Nigerian English.
72
- - **Phonemizer**: Converts text to IPA.
73
- - **Docker**: Containerization for reproducible deployment.
74
- - **Hugging Face Spaces**: Cloud hosting for public demos.
75
-
76
- ---
77
-
78
- ## Demo
79
-
80
- > **Live Demo:** [Hugging Face Spaces - Voxpreference](https://huggingface.co/spaces/thebickersteth/voxpreference)
81
-
82
- ---
83
-
84
- ## Quickstart
85
-
86
- ### Running Locally (Docker)
87
-
88
- 1. **Clone the repository:**
89
- ```bash
90
- git clone https://huggingface.co/spaces/thebickersteth/voxpreference
91
- cd voxpreference
92
- ```
93
-
94
- 2. **Build the Docker image:**
95
- ```bash
96
- docker build -t voxpreference .
97
- ```
98
-
99
- 3. **Run the container:**
100
- ```bash
101
- docker run -p 7860:7860 voxpreference
102
- ```
103
-
104
- 4. **Access the API:**
105
- - Open [http://localhost:7860](http://localhost:7860) in your browser or use `curl`/Postman.
106
-
107
- ### Running on Hugging Face Spaces
108
-
109
- 1. **Push your repository to Hugging Face Spaces** (with `sdk: docker` in your README).
110
- 2. **Spaces will automatically build and run your Dockerfile.**
111
- 3. **Access your app via the provided URL.**
112
-
113
- ---
114
-
115
- ## API Reference
116
-
117
- ### Root Endpoint `/`
118
-
119
- - **Method:** `GET`
120
- - **Description:** Welcome message and basic info.
121
- - **Response:**
122
- ```json
123
- {
124
- "message": "Welcome! This API is for transcription. Try /health or /transcribe."
125
- }
126
- ```
127
-
128
- ### Health Endpoint `/health`
129
-
130
- - **Method:** `GET`
131
- - **Description:** Health check for monitoring.
132
- - **Response:**
133
- ```json
134
- {
135
- "status": "ok"
136
- }
137
- ```
138
-
139
- ### Transcription Endpoint `/` (POST)
140
-
141
- - **Method:** `POST`
142
- - **Description:** Upload an audio file (WAV/MP3) and receive transcription and IPA.
143
- - **Request:**
144
- - **Form field:** `audioFile` (file upload)
145
- - **Response:**
146
- ```json
147
- {
148
- "success": true,
149
- "transcription": "recognized text",
150
- "ipa": "ˌɪn.təˈnæʃ.ə.nəl fəˈnɛ.tɪk ˈælfəˌbɛt",
151
- "ipa_error": null
152
- }
153
- ```
154
- - If an error occurs:
155
- ```json
156
- {
157
- "success": false,
158
- "error": "Error message"
159
- }
160
- ```
161
-
162
- #### Example `curl` Request
163
-
164
- ```bash
165
- curl -X POST "http://localhost:7860/" \
166
- -F "audioFile=@/path/to/your/audio.wav"
167
- ```
168
-
169
- ---
170
-
171
- ## Environment Variables
172
-
173
- - `LOG_LEVEL`: Set the logging level (`DEBUG`, `INFO`, `WARNING`, `ERROR`). Default: `INFO`.
174
- - `HF_HOME`: Path for Hugging Face cache (default: `/app/hf_home`).
175
- - `TRANSFORMERS_CACHE`: Path for Transformers model cache (default: `/app/cache`).
176
- - `NUMBA_CACHE_DIR`: Path for Numba cache (default: `/app/numba_cache`).
177
-
178
- ---
179
-
180
- ## Logging
181
-
182
- - Logs are output to stdout (visible in Docker logs and Hugging Face Spaces).
183
- - Log format:
184
- `YYYY-MM-DD HH:MM:SS | LEVEL | voxpreference.app | message`
185
- - All requests, responses, and errors are logged.
186
- - Set `LOG_LEVEL=DEBUG` for verbose output.
187
-
188
- ---
189
-
190
- ## Cache and Storage Management
191
-
192
- - **No audio files are saved to disk**; all processing is in-memory.
193
- - Model and Hugging Face caches are stored in `/app/hf_home` and `/app/cache`.
194
- - On startup, cache directories can be cleaned to avoid storage bloat (see `app.py` for details).
195
- - **Tip:** Monitor disk usage on Hugging Face Spaces to avoid exceeding quotas.
196
-
197
- ---
198
-
199
- ## Development
200
-
201
- ### Requirements
202
-
203
- - Python 3.9+
204
- - See `requirements.txt` for dependencies.
205
-
206
- ### Local Development (without Docker)
207
-
208
- 1. **Create a virtual environment:**
209
- ```bash
210
- python3 -m venv .venv
211
- source .venv/bin/activate
212
- ```
213
-
214
- 2. **Install dependencies:**
215
- ```bash
216
- pip install -r requirements.txt
217
- ```
218
-
219
- 3. **Run the app:**
220
- ```bash
221
- uvicorn app:app --host 0.0.0.0 --port 7860
222
- ```
223
-
224
- ---
225
-
226
- ## Finetuning the Model
227
-
228
- - See `finetune_model.py` for scripts and instructions to finetune the Wav2Vec2 model on your own Nigerian English dataset.
229
- - Training data should be in CSV format with columns for audio file paths and transcripts.
230
- - The script uses Hugging Face `datasets` and `transformers` libraries.
231
- V
232
- ---
233
-
234
- ## Troubleshooting
235
-
236
- - **Model Download Issues:** Ensure your Hugging Face token (if needed) is set up and the model is public.
237
- - **Out of Disk Space:** Clean up `/app/hf_home` and `/app/cache` or increase your Hugging Face Space storage.
238
- - **Audio Format Errors:** Only WAV/MP3 files with 16kHz sample rate are supported.
239
- - **Performance:** For large files or high concurrency, consider scaling or optimizing the Docker resource limits.
240
-
241
- ---
242
-
243
- ## License
244
-
245
- This project is licensed under the MIT License. See [LICENSE](LICENSE) for details.
246
-
247
- ---
248
-
249
- ## Acknowledgements
250
-
251
- - [Hugging Face](https://huggingface.co/) for model hosting and Spaces.
252
- - [FastAPI](https://fastapi.tiangolo.com/) for the web framework.
253
- - [Transformers](https://github.com/huggingface/transformers) for the ASR model.
254
- - [Phonemizer](https://github.com/bootphon/phonemizer) for IPA conversion.
255
- - Nigerian English speech community for data and inspiration.
256
 
 
 
 
1
  ---
2
+ title: VoxPreference
3
+ emoji: 🗣️
4
  colorFrom: indigo
5
  colorTo: gray
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
+ short_description: Preference Grammar analysis of Nigerian English speech
10
  ---
11
 
12
+ # VoxPreference
13
 
14
+ Automates Prof. C.U.C. Ugorji's Preference Grammar for Nigerian English: give target words, recordings
15
+ (single words, voice notes or whole podcasts) and a ranking of the six tenets; the app hears how each speaker
16
+ pronounced the sound, counts the variants, and returns the operability table and the preferred pronunciation.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ Source and documentation: https://github.com/Oluwademiladeogo/VoxPreference (see backend/pg/README.md).
19
+ Runs on free CPU hardware: short clips take about a minute; a long podcast takes much longer.
VoxPreference-frontend/.gitignore ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+ pnpm-debug.log*
8
+ lerna-debug.log*
9
+
10
+ node_modules
11
+ dist
12
+ dist-ssr
13
+ *.local
14
+
15
+ # Editor directories and files
16
+ .vscode/*
17
+ !.vscode/extensions.json
18
+ .idea
19
+ .DS_Store
20
+ *.suo
21
+ *.ntvs*
22
+ *.njsproj
23
+ *.sln
24
+ *.sw?
25
+ .env
VoxPreference-frontend/.impeccable/hook.cache.json ADDED
@@ -0,0 +1 @@
 
 
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}}}}}
VoxPreference-frontend/README.md ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # React + TypeScript + Vite
2
+
3
+ This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
4
+
5
+ Currently, two official plugins are available:
6
+
7
+ - [@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
8
+ - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
9
+
10
+ ## Expanding the ESLint configuration
11
+
12
+ If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
13
+
14
+ ```js
15
+ export default tseslint.config({
16
+ extends: [
17
+ // Remove ...tseslint.configs.recommended and replace with this
18
+ ...tseslint.configs.recommendedTypeChecked,
19
+ // Alternatively, use this for stricter rules
20
+ ...tseslint.configs.strictTypeChecked,
21
+ // Optionally, add this for stylistic rules
22
+ ...tseslint.configs.stylisticTypeChecked,
23
+ ],
24
+ languageOptions: {
25
+ // other options...
26
+ parserOptions: {
27
+ project: ['./tsconfig.node.json', './tsconfig.app.json'],
28
+ tsconfigRootDir: import.meta.dirname,
29
+ },
30
+ },
31
+ })
32
+ ```
33
+
34
+ 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:
35
+
36
+ ```js
37
+ // eslint.config.js
38
+ import reactX from 'eslint-plugin-react-x'
39
+ import reactDom from 'eslint-plugin-react-dom'
40
+
41
+ export default tseslint.config({
42
+ plugins: {
43
+ // Add the react-x and react-dom plugins
44
+ 'react-x': reactX,
45
+ 'react-dom': reactDom,
46
+ },
47
+ rules: {
48
+ // other rules...
49
+ // Enable its recommended typescript rules
50
+ ...reactX.configs['recommended-typescript'].rules,
51
+ ...reactDom.configs.recommended.rules,
52
+ },
53
+ })
54
+ ```
VoxPreference-frontend/eslint.config.js ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import js from '@eslint/js'
2
+ import globals from 'globals'
3
+ import reactHooks from 'eslint-plugin-react-hooks'
4
+ import reactRefresh from 'eslint-plugin-react-refresh'
5
+ import tseslint from 'typescript-eslint'
6
+
7
+ export default tseslint.config(
8
+ { ignores: ['dist'] },
9
+ {
10
+ extends: [js.configs.recommended, ...tseslint.configs.recommended],
11
+ files: ['**/*.{ts,tsx}'],
12
+ languageOptions: {
13
+ ecmaVersion: 2020,
14
+ globals: globals.browser,
15
+ },
16
+ plugins: {
17
+ 'react-hooks': reactHooks,
18
+ 'react-refresh': reactRefresh,
19
+ },
20
+ rules: {
21
+ ...reactHooks.configs.recommended.rules,
22
+ 'react-refresh/only-export-components': [
23
+ 'warn',
24
+ { allowConstantExport: true },
25
+ ],
26
+ },
27
+ },
28
+ )
VoxPreference-frontend/index.html ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>VoxPreference</title>
8
+ </head>
9
+ <body>
10
+ <div id="root"></div>
11
+ <script type="module" src="/src/main.tsx"></script>
12
+ </body>
13
+ </html>
VoxPreference-frontend/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
VoxPreference-frontend/package.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "voxpreference-frontend",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "tsc -b && vite build",
9
+ "lint": "eslint .",
10
+ "preview": "vite preview"
11
+ },
12
+ "dependencies": {
13
+ "@tailwindcss/vite": "^4.1.3",
14
+ "react": "^19.0.0",
15
+ "react-dom": "^19.0.0",
16
+ "tailwindcss": "^4.1.3"
17
+ },
18
+ "devDependencies": {
19
+ "@eslint/js": "^9.21.0",
20
+ "@types/react": "^19.0.10",
21
+ "@types/react-dom": "^19.0.4",
22
+ "@vitejs/plugin-react": "^4.3.4",
23
+ "eslint": "^9.39.4",
24
+ "eslint-plugin-react-hooks": "^5.1.0",
25
+ "eslint-plugin-react-refresh": "^0.4.19",
26
+ "globals": "^15.15.0",
27
+ "typescript": "~5.7.2",
28
+ "typescript-eslint": "^8.24.1",
29
+ "vite": "^6.4.2"
30
+ }
31
+ }
VoxPreference-frontend/src/App.css ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #root {
2
+ max-width: 1280px;
3
+ margin: 0 auto;
4
+ padding: 2rem;
5
+ text-align: center;
6
+ }
VoxPreference-frontend/src/App.tsx ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from "react";
2
+ import Chat from "./components/Chat";
3
+ import PGAnalysis from "./components/PGAnalysis";
4
+ import Sidebar, { View } from "./components/Sidebar";
5
+
6
+ function App() {
7
+ const [activeView, setActiveView] = useState<View>("pg");
8
+
9
+ return (
10
+ <div className="flex flex-col md:flex-row h-screen bg-gray-100">
11
+ <Sidebar activeView={activeView} onSelect={setActiveView} />
12
+ <main className="flex-1 min-h-0 overflow-hidden">
13
+ {/* Both views stay mounted so a long analysis survives a switch to the legacy view */}
14
+ <div className={activeView === "chat" ? "h-full" : "hidden"}>
15
+ <Chat />
16
+ </div>
17
+ <div className={activeView === "pg" ? "h-full" : "hidden"}>
18
+ <PGAnalysis />
19
+ </div>
20
+ </main>
21
+ </div>
22
+ );
23
+ }
24
+
25
+ export default App;
VoxPreference-frontend/src/components/AudioUploadForm.tsx ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useRef, FormEvent, DragEvent } from "react";
2
+ import ApiService from "../services/api";
3
+ import { API_CONFIG } from "../config/api";
4
+
5
+ interface AudioUploadFormProps {
6
+ onUploadComplete?: () => void;
7
+ }
8
+
9
+ interface ErrorState {
10
+ message: string;
11
+ type: "file" | "upload" | "validation" | "network";
12
+ }
13
+
14
+ const AudioUploadForm = ({ onUploadComplete }: AudioUploadFormProps) => {
15
+ const [fileName, setFileName] = useState("");
16
+ const [fileDescription, setFileDescription] = useState("");
17
+ const [selectedFile, setSelectedFile] = useState<File | null>(null);
18
+ const [isDragging, setIsDragging] = useState(false);
19
+ const [isUploading, setIsUploading] = useState(false);
20
+ const [uploadProgress, setUploadProgress] = useState(0);
21
+ const [uploadResult, setUploadResult] = useState<{
22
+ message: string;
23
+ success: boolean;
24
+ } | null>(null);
25
+ const [error, setError] = useState<ErrorState | null>(null);
26
+
27
+ const fileInputRef = useRef<HTMLInputElement>(null);
28
+
29
+ const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
30
+ e.preventDefault();
31
+ e.stopPropagation();
32
+ setIsDragging(true);
33
+ };
34
+
35
+ const handleDragLeave = (e: DragEvent<HTMLDivElement>) => {
36
+ e.preventDefault();
37
+ e.stopPropagation();
38
+ setIsDragging(false);
39
+ };
40
+
41
+ const handleDrop = (e: DragEvent<HTMLDivElement>) => {
42
+ e.preventDefault();
43
+ e.stopPropagation();
44
+ setIsDragging(false);
45
+
46
+ const files = e.dataTransfer.files;
47
+ if (files && files.length > 0) {
48
+ validateAndSetFile(files[0]);
49
+ }
50
+ };
51
+
52
+ const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
53
+ if (e.target.files && e.target.files.length > 0) {
54
+ validateAndSetFile(e.target.files[0]);
55
+ }
56
+ };
57
+
58
+ const validateAndSetFile = (file: File) => {
59
+ setError(null);
60
+
61
+ if (!API_CONFIG.SUPPORTED_FILE_TYPES.includes(file.type)) {
62
+ setError({
63
+ message: `Please select a valid audio file (${API_CONFIG.SUPPORTED_FILE_TYPES.join(
64
+ ", "
65
+ )})`,
66
+ type: "validation",
67
+ });
68
+ return;
69
+ }
70
+
71
+ if (file.size > API_CONFIG.MAX_FILE_SIZE) {
72
+ setError({
73
+ message: `File size exceeds ${
74
+ API_CONFIG.MAX_FILE_SIZE / (1024 * 1024)
75
+ }MB limit`,
76
+ type: "validation",
77
+ });
78
+ return;
79
+ }
80
+
81
+ setSelectedFile(file);
82
+ };
83
+
84
+ const removeFile = () => {
85
+ setSelectedFile(null);
86
+ setError(null);
87
+ if (fileInputRef.current) {
88
+ fileInputRef.current.value = "";
89
+ }
90
+ };
91
+
92
+ const handleSubmit = async (e: FormEvent) => {
93
+ e.preventDefault();
94
+ setError(null);
95
+
96
+ if (!selectedFile) {
97
+ setError({
98
+ message: "Please select an audio file",
99
+ type: "validation",
100
+ });
101
+ return;
102
+ }
103
+
104
+ if (!fileName.trim()) {
105
+ setError({
106
+ message: "Please provide a file name",
107
+ type: "validation",
108
+ });
109
+ return;
110
+ }
111
+
112
+ setIsUploading(true);
113
+ setUploadProgress(0);
114
+ setUploadResult(null);
115
+
116
+ const formData = new FormData();
117
+ formData.append("fileName", fileName);
118
+ formData.append("fileDescription", fileDescription);
119
+ formData.append("audioFile", selectedFile);
120
+
121
+ try {
122
+ await ApiService.uploadAudio(formData);
123
+ setUploadProgress(100);
124
+ setUploadResult({
125
+ message: "File uploaded successfully!",
126
+ success: true,
127
+ });
128
+
129
+ // Reset form after successful upload
130
+ setTimeout(() => {
131
+ setFileName("");
132
+ setFileDescription("");
133
+ setSelectedFile(null);
134
+ setUploadProgress(0);
135
+ setIsUploading(false);
136
+ setUploadResult(null);
137
+ if (fileInputRef.current) {
138
+ fileInputRef.current.value = "";
139
+ }
140
+ onUploadComplete?.();
141
+ }, 3000);
142
+ } catch (error) {
143
+ console.error("Error:", error);
144
+ setError({
145
+ message:
146
+ error instanceof Error ? error.message : "Unknown error occurred",
147
+ type:
148
+ error instanceof Error && error.message.includes("Network")
149
+ ? "network"
150
+ : "upload",
151
+ });
152
+ setIsUploading(false);
153
+ }
154
+ };
155
+
156
+ return (
157
+ <div className="max-w-3xl mx-auto my-10 bg-white rounded-lg shadow-md p-8">
158
+ <h1 className="text-3xl font-bold text-center text-blue-700 mb-6">
159
+ VoxPreference Audio Upload
160
+ </h1>
161
+ <p className="text-center text-gray-600 mb-8">
162
+ Upload audio files for speech recognition and analysis. Supported
163
+ formats: WAV, MP3, FLAC, OGG (max 20MB).
164
+ </p>
165
+
166
+ {error && (
167
+ <div className="mb-4 p-4 rounded-lg bg-red-50 border border-red-200">
168
+ <div className="flex items-center">
169
+ <svg
170
+ className="w-5 h-5 text-red-500 mr-2"
171
+ fill="none"
172
+ stroke="currentColor"
173
+ viewBox="0 0 24 24"
174
+ >
175
+ <path
176
+ strokeLinecap="round"
177
+ strokeLinejoin="round"
178
+ strokeWidth={2}
179
+ d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
180
+ />
181
+ </svg>
182
+ <p className="text-red-700">{error.message}</p>
183
+ </div>
184
+ </div>
185
+ )}
186
+
187
+ {uploadResult && (
188
+ <div
189
+ className={`mb-4 p-4 rounded-lg ${
190
+ uploadResult.success
191
+ ? "bg-green-50 border border-green-200"
192
+ : "bg-red-50 border border-red-200"
193
+ }`}
194
+ >
195
+ <div className="flex items-center">
196
+ {uploadResult.success ? (
197
+ <svg
198
+ className="w-5 h-5 text-green-500 mr-2"
199
+ fill="none"
200
+ stroke="currentColor"
201
+ viewBox="0 0 24 24"
202
+ >
203
+ <path
204
+ strokeLinecap="round"
205
+ strokeLinejoin="round"
206
+ strokeWidth={2}
207
+ d="M5 13l4 4L19 7"
208
+ />
209
+ </svg>
210
+ ) : (
211
+ <svg
212
+ className="w-5 h-5 text-red-500 mr-2"
213
+ fill="none"
214
+ stroke="currentColor"
215
+ viewBox="0 0 24 24"
216
+ >
217
+ <path
218
+ strokeLinecap="round"
219
+ strokeLinejoin="round"
220
+ strokeWidth={2}
221
+ d="M6 18L18 6M6 6l12 12"
222
+ />
223
+ </svg>
224
+ )}
225
+ <p
226
+ className={
227
+ uploadResult.success ? "text-green-700" : "text-red-700"
228
+ }
229
+ >
230
+ {uploadResult.message}
231
+ </p>
232
+ </div>
233
+ </div>
234
+ )}
235
+
236
+ <form
237
+ encType="multipart/form-data"
238
+ onSubmit={handleSubmit}
239
+ className="space-y-6"
240
+ >
241
+ <div className="space-y-2">
242
+ <label
243
+ htmlFor="fileName"
244
+ className="block font-semibold text-gray-700"
245
+ >
246
+ File Name
247
+ </label>
248
+ <input
249
+ type="text"
250
+ id="fileName"
251
+ value={fileName}
252
+ onChange={(e) => setFileName(e.target.value)}
253
+ placeholder="Enter a name for your audio file"
254
+ required
255
+ className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-transparent"
256
+ />
257
+ </div>
258
+
259
+ <div className="space-y-2">
260
+ <label
261
+ htmlFor="fileDescription"
262
+ className="block font-semibold text-gray-700"
263
+ >
264
+ Description
265
+ </label>
266
+ <textarea
267
+ id="fileDescription"
268
+ value={fileDescription}
269
+ onChange={(e) => setFileDescription(e.target.value)}
270
+ rows={4}
271
+ placeholder="Provide some details about this audio file (optional)"
272
+ className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-transparent"
273
+ />
274
+ </div>
275
+
276
+ <div className="space-y-2">
277
+ <label className="block font-semibold text-gray-700">
278
+ Audio File
279
+ </label>
280
+ <div
281
+ className={`relative border-2 border-dashed rounded-lg p-10 text-center cursor-pointer transition-colors duration-300 ${
282
+ isDragging
283
+ ? "border-blue-600 bg-blue-50"
284
+ : "border-gray-300 bg-gray-50 hover:bg-gray-100"
285
+ }`}
286
+ onDragOver={handleDragOver}
287
+ onDragLeave={handleDragLeave}
288
+ onDrop={handleDrop}
289
+ onClick={() => fileInputRef.current?.click()}
290
+ >
291
+ <i className="fas fa-microphone-alt text-4xl text-blue-600 mb-4 block"></i>
292
+ <p className="font-semibold mb-2">
293
+ Drag & Drop your audio file here
294
+ </p>
295
+ <p className="text-sm text-gray-600">or click to browse files</p>
296
+ <input
297
+ type="file"
298
+ ref={fileInputRef}
299
+ onChange={handleFileChange}
300
+ accept="audio/*"
301
+ required
302
+ className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
303
+ />
304
+
305
+ {selectedFile && (
306
+ <div className="mt-4 bg-blue-50 p-3 rounded-lg flex items-center justify-between">
307
+ <span className="text-sm">{selectedFile.name}</span>
308
+ <button
309
+ type="button"
310
+ onClick={(e) => {
311
+ e.stopPropagation();
312
+ removeFile();
313
+ }}
314
+ className="text-red-500 hover:text-red-700"
315
+ >
316
+ <i className="fas fa-times"></i>
317
+ </button>
318
+ </div>
319
+ )}
320
+ </div>
321
+ </div>
322
+
323
+ <button
324
+ type="submit"
325
+ disabled={isUploading || !selectedFile}
326
+ className={`w-full py-3 rounded-lg font-semibold transition-colors duration-300 ${
327
+ isUploading || !selectedFile
328
+ ? "bg-gray-400 cursor-not-allowed"
329
+ : "bg-blue-600 hover:bg-blue-700 text-white"
330
+ }`}
331
+ >
332
+ {isUploading ? "Uploading..." : "Upload Audio"}
333
+ </button>
334
+
335
+ {isUploading && (
336
+ <div className="h-2 w-full bg-gray-200 rounded-full overflow-hidden">
337
+ <div
338
+ className="h-full bg-blue-600 transition-all duration-300 ease-out"
339
+ style={{ width: `${uploadProgress}%` }}
340
+ ></div>
341
+ </div>
342
+ )}
343
+ </form>
344
+ </div>
345
+ );
346
+ };
347
+
348
+ export default AudioUploadForm;
VoxPreference-frontend/src/components/Chat.tsx ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useRef, useEffect } from "react";
2
+ import AudioUploadForm from "./AudioUploadForm";
3
+ import Modal from "./Modal";
4
+
5
+ interface Message {
6
+ id: string;
7
+ text: string;
8
+ sender: "user" | "assistant";
9
+ timestamp: Date;
10
+ }
11
+
12
+ const Chat = () => {
13
+ const [messages, setMessages] = useState<Message[]>([]);
14
+ const [inputMessage, setInputMessage] = useState("");
15
+ const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
16
+ const messagesEndRef = useRef<HTMLDivElement>(null);
17
+
18
+ const scrollToBottom = () => {
19
+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
20
+ };
21
+
22
+ useEffect(() => {
23
+ scrollToBottom();
24
+ }, [messages]);
25
+
26
+ const handleSubmit = (e: React.FormEvent) => {
27
+ e.preventDefault();
28
+ if (!inputMessage.trim()) return;
29
+
30
+ const newMessage: Message = {
31
+ id: Date.now().toString(),
32
+ text: inputMessage,
33
+ sender: "user",
34
+ timestamp: new Date(),
35
+ };
36
+
37
+ setMessages((prev) => [...prev, newMessage]);
38
+ setInputMessage("");
39
+
40
+ // Simulate assistant response
41
+ setTimeout(() => {
42
+ const assistantMessage: Message = {
43
+ id: (Date.now() + 1).toString(),
44
+ text: "I received your message. How can I help you with your audio preferences?",
45
+ sender: "assistant",
46
+ timestamp: new Date(),
47
+ };
48
+ setMessages((prev) => [...prev, assistantMessage]);
49
+ }, 1000);
50
+ };
51
+
52
+ return (
53
+ <div className="flex flex-col h-full">
54
+ <p className="px-4 py-2 border-b border-amber-300 bg-amber-50 text-sm text-amber-900">
55
+ Legacy view: it uses the old wav2vec2 model and dictionary IPA, which
56
+ shows how words are spelled in a dictionary, not how they were
57
+ pronounced.
58
+ </p>
59
+ <div className="flex-1 overflow-y-auto p-4 space-y-4">
60
+ {messages.map((message) => (
61
+ <div
62
+ key={message.id}
63
+ className={`flex ${
64
+ message.sender === "user" ? "justify-end" : "justify-start"
65
+ }`}
66
+ >
67
+ <div
68
+ className={`max-w-[70%] rounded-lg p-3 ${
69
+ message.sender === "user"
70
+ ? "bg-blue-600 text-white"
71
+ : "bg-gray-200 text-gray-800"
72
+ }`}
73
+ >
74
+ <p>{message.text}</p>
75
+ <span className="text-xs opacity-70">
76
+ {message.timestamp.toLocaleTimeString()}
77
+ </span>
78
+ </div>
79
+ </div>
80
+ ))}
81
+ <div ref={messagesEndRef} />
82
+ </div>
83
+ <form onSubmit={handleSubmit} className="p-4 border-t">
84
+ <div className="flex space-x-2">
85
+ <button
86
+ type="button"
87
+ onClick={() => setIsUploadModalOpen(true)}
88
+ className="p-2 text-gray-600 hover:text-blue-600 focus:outline-none"
89
+ title="Upload Audio File"
90
+ >
91
+ <svg
92
+ className="w-6 h-6"
93
+ fill="none"
94
+ stroke="currentColor"
95
+ viewBox="0 0 24 24"
96
+ >
97
+ <path
98
+ strokeLinecap="round"
99
+ strokeLinejoin="round"
100
+ strokeWidth={2}
101
+ d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
102
+ />
103
+ </svg>
104
+ </button>
105
+ <input
106
+ type="text"
107
+ value={inputMessage}
108
+ onChange={(e) => setInputMessage(e.target.value)}
109
+ placeholder="Type your message..."
110
+ className="flex-1 p-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
111
+ />
112
+ <button
113
+ type="submit"
114
+ className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
115
+ >
116
+ Send
117
+ </button>
118
+ </div>
119
+ </form>
120
+
121
+ <Modal
122
+ isOpen={isUploadModalOpen}
123
+ onClose={() => setIsUploadModalOpen(false)}
124
+ title="Upload Audio File"
125
+ >
126
+ <AudioUploadForm onUploadComplete={() => setIsUploadModalOpen(false)} />
127
+ </Modal>
128
+ </div>
129
+ );
130
+ };
131
+
132
+ export default Chat;
VoxPreference-frontend/src/components/Modal.tsx ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { ReactNode, useEffect, useRef } from "react";
2
+
3
+ interface ModalProps {
4
+ isOpen: boolean;
5
+ onClose: () => void;
6
+ children: ReactNode;
7
+ title: string;
8
+ }
9
+
10
+ const Modal = ({ isOpen, onClose, children, title }: ModalProps) => {
11
+ const modalRef = useRef<HTMLDivElement>(null);
12
+
13
+ useEffect(() => {
14
+ const handleClickOutside = (event: MouseEvent) => {
15
+ if (
16
+ modalRef.current &&
17
+ !modalRef.current.contains(event.target as Node)
18
+ ) {
19
+ onClose();
20
+ }
21
+ };
22
+
23
+ const handleEscape = (event: KeyboardEvent) => {
24
+ if (event.key === "Escape") {
25
+ onClose();
26
+ }
27
+ };
28
+
29
+ if (isOpen) {
30
+ // Prevent background scrolling
31
+ document.body.style.overflow = "hidden";
32
+ document.addEventListener("mousedown", handleClickOutside);
33
+ document.addEventListener("keydown", handleEscape);
34
+ }
35
+
36
+ return () => {
37
+ // Restore background scrolling
38
+ document.body.style.overflow = "unset";
39
+ document.removeEventListener("mousedown", handleClickOutside);
40
+ document.removeEventListener("keydown", handleEscape);
41
+ };
42
+ }, [isOpen, onClose]);
43
+
44
+ if (!isOpen) return null;
45
+
46
+ return (
47
+ <div className="fixed inset-0 backdrop-blur-sm bg-white/30 flex items-center justify-center z-50">
48
+ <div
49
+ ref={modalRef}
50
+ className="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto"
51
+ >
52
+ <div className="sticky top-0 bg-white z-10 flex justify-between items-center p-4 border-b">
53
+ <h2 className="text-xl font-semibold">{title}</h2>
54
+ <button
55
+ onClick={onClose}
56
+ className="text-gray-500 hover:text-gray-700"
57
+ >
58
+ <svg
59
+ className="w-6 h-6"
60
+ fill="none"
61
+ stroke="currentColor"
62
+ viewBox="0 0 24 24"
63
+ >
64
+ <path
65
+ strokeLinecap="round"
66
+ strokeLinejoin="round"
67
+ strokeWidth={2}
68
+ d="M6 18L18 6M6 6l12 12"
69
+ />
70
+ </svg>
71
+ </button>
72
+ </div>
73
+ <div className="p-4">{children}</div>
74
+ </div>
75
+ </div>
76
+ );
77
+ };
78
+
79
+ export default Modal;
VoxPreference-frontend/src/components/PGAnalysis.tsx ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { FormEvent, useEffect, useRef, useState } from "react";
2
+ import { API_CONFIG } from "../config/api";
3
+ import ApiService from "../services/api";
4
+ import {
5
+ AnalysisOutcome,
6
+ OverrideRow,
7
+ PGUnit,
8
+ PGUnitsResponse,
9
+ RankingItem,
10
+ RecordingItem,
11
+ SettingsForm,
12
+ } from "../types/pg";
13
+ import {
14
+ DEFAULT_RANKING,
15
+ DEFAULT_SETTINGS,
16
+ PG_TENETS,
17
+ buildSettings,
18
+ formatRanking,
19
+ isAutoTranscript,
20
+ isValidated,
21
+ nextId,
22
+ parseWords,
23
+ rankingItemsFrom,
24
+ rankingStrata,
25
+ validationLabel,
26
+ } from "../utils/pg";
27
+ import AdvancedSettings from "./pg/AdvancedSettings";
28
+ import AnalysisProgress from "./pg/AnalysisProgress";
29
+ import AnalysisResults from "./pg/AnalysisResults";
30
+ import Icon from "./pg/Icon";
31
+ import RankingEditor from "./pg/RankingEditor";
32
+ import RecordingsInput from "./pg/RecordingsInput";
33
+ import UnitSummary from "./pg/UnitSummary";
34
+
35
+ interface ErrorState {
36
+ message: string;
37
+ type: "validation" | "analysis" | "cancelled";
38
+ }
39
+
40
+ interface RunState {
41
+ startedAt: number;
42
+ files: number;
43
+ words: string[];
44
+ unscripted: boolean;
45
+ }
46
+
47
+ const unitOptionLabel = (unit: PGUnit) =>
48
+ `${
49
+ unit.label === unit.key
50
+ ? `${unit.key} · /${unit.phoneme}/`
51
+ : `${unit.key} · ${unit.label} /${unit.phoneme}/`
52
+ } · ${validationLabel(unit)}`;
53
+
54
+ const inputClass =
55
+ "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";
56
+ const sectionHeadingClass = "text-xl font-semibold text-gray-900";
57
+
58
+ const PGAnalysis = () => {
59
+ const [catalog, setCatalog] = useState<PGUnitsResponse | null>(null);
60
+ const [catalogError, setCatalogError] = useState<string | null>(null);
61
+ const [catalogRequest, setCatalogRequest] = useState(0);
62
+ const [wordsInput, setWordsInput] = useState("");
63
+ const [unitKey, setUnitKey] = useState("");
64
+ const [ranking, setRanking] = useState<RankingItem[]>(() =>
65
+ rankingItemsFrom(DEFAULT_RANKING, PG_TENETS)
66
+ );
67
+ const [recordings, setRecordings] = useState<RecordingItem[]>([]);
68
+ const [asr, setAsr] = useState(false);
69
+ const [diarize, setDiarize] = useState(true);
70
+ const [numSpeakers, setNumSpeakers] = useState("");
71
+ const [settings, setSettings] = useState<SettingsForm>(DEFAULT_SETTINGS);
72
+ const [overrides, setOverrides] = useState<OverrideRow[]>([]);
73
+ const [error, setError] = useState<ErrorState | null>(null);
74
+ const [run, setRun] = useState<RunState | null>(null);
75
+ const [outcome, setOutcome] = useState<AnalysisOutcome | null>(null);
76
+ const rankingEdited = useRef(false);
77
+ const abortRef = useRef<AbortController | null>(null);
78
+ const resultsHeadingRef = useRef<HTMLHeadingElement>(null);
79
+
80
+ const tenets = catalog?.tenets ?? PG_TENETS;
81
+ const defaultRanking = catalog?.default_ranking ?? DEFAULT_RANKING;
82
+ const units = catalog ? Object.values(catalog.units) : [];
83
+ const selectedUnit = unitKey ? catalog?.units[unitKey] : undefined;
84
+ const words = parseWords(wordsInput);
85
+ const unvalidated = !!selectedUnit && !isValidated(selectedUnit);
86
+ // A variant can be any IPA phone, so overrides also suggest those heard in the last run
87
+ const lastRun =
88
+ outcome && (!unitKey || outcome.data.unit.key === unitKey)
89
+ ? outcome.data
90
+ : null;
91
+ const overrideVariants = Array.from(
92
+ new Set([
93
+ ...(selectedUnit?.candidates ?? lastRun?.unit.candidates ?? []),
94
+ ...(lastRun?.tokens.map((token) => token.variant) ?? []),
95
+ ])
96
+ );
97
+
98
+ useEffect(() => {
99
+ let ignore = false;
100
+ ApiService.getPGUnits()
101
+ .then((data) => {
102
+ if (ignore) return;
103
+ setCatalog(data);
104
+ setCatalogError(null);
105
+ // Use the server's default ranking unless the user has already edited it
106
+ if (!rankingEdited.current) {
107
+ setRanking(rankingItemsFrom(data.default_ranking, data.tenets));
108
+ }
109
+ })
110
+ .catch((err) => {
111
+ if (!ignore) {
112
+ setCatalogError(
113
+ err instanceof Error ? err.message : "Unknown error occurred"
114
+ );
115
+ }
116
+ });
117
+ return () => {
118
+ ignore = true;
119
+ };
120
+ }, [catalogRequest]);
121
+
122
+ // Stop waiting for a running analysis if the view goes away
123
+ useEffect(() => () => abortRef.current?.abort(), []);
124
+
125
+ // Bring the new results to the top and move keyboard and screen-reader users there
126
+ useEffect(() => {
127
+ const heading = resultsHeadingRef.current;
128
+ if (!outcome || !heading) return;
129
+ heading.scrollIntoView({ block: "start" });
130
+ heading.focus({ preventScroll: true });
131
+ }, [outcome]);
132
+
133
+ const handleRankingChange = (items: RankingItem[]) => {
134
+ rankingEdited.current = true;
135
+ setRanking(items);
136
+ };
137
+
138
+ const handleSubmit = async (e: FormEvent) => {
139
+ e.preventDefault();
140
+ setError(null);
141
+
142
+ if (!words.length) {
143
+ setError({ message: "Enter at least one target word", type: "validation" });
144
+ return;
145
+ }
146
+ if (!recordings.length) {
147
+ setError({ message: "Add at least one recording", type: "validation" });
148
+ return;
149
+ }
150
+ const strata = rankingStrata(ranking);
151
+ if (!strata.length) {
152
+ setError({
153
+ message: "Keep at least one tenet in the ranking",
154
+ type: "validation",
155
+ });
156
+ return;
157
+ }
158
+ const built = buildSettings(settings, overrides);
159
+ if (built.error !== null) {
160
+ setError({ message: built.error, type: "validation" });
161
+ return;
162
+ }
163
+
164
+ const formData = new FormData();
165
+ recordings.forEach((item) => formData.append("files", item.file));
166
+ formData.append("words", words.join(","));
167
+ if (unitKey) formData.append("unit", unitKey);
168
+ formData.append("ranking", formatRanking(strata));
169
+ // Transcripts and speakers are keyed by file name
170
+ const transcripts = Object.fromEntries(
171
+ recordings
172
+ .filter((item) => item.transcript.trim())
173
+ .map((item) => [item.file.name, item.transcript.trim()])
174
+ );
175
+ if (Object.keys(transcripts).length) {
176
+ formData.append("transcripts", JSON.stringify(transcripts));
177
+ }
178
+ const speakers = Object.fromEntries(
179
+ recordings
180
+ .filter((item) => item.speaker.trim())
181
+ .map((item) => [item.file.name, item.speaker.trim()])
182
+ );
183
+ if (Object.keys(speakers).length) {
184
+ formData.append("speakers", JSON.stringify(speakers));
185
+ }
186
+ if (Object.keys(built.settings).length) {
187
+ formData.append("settings", JSON.stringify(built.settings));
188
+ }
189
+ formData.append("asr", asr ? "true" : "false");
190
+ formData.append("diarize", diarize ? "true" : "false");
191
+ const speakerCount = Number.parseInt(numSpeakers, 10);
192
+ if (diarize && speakerCount >= 1 && speakerCount <= 20) {
193
+ formData.append("num_speakers", String(speakerCount));
194
+ }
195
+
196
+ const controller = new AbortController();
197
+ abortRef.current = controller;
198
+ setRun({
199
+ startedAt: Date.now(),
200
+ files: recordings.length,
201
+ words,
202
+ unscripted:
203
+ recordings.some((item) => isAutoTranscript(item.transcript)) ||
204
+ (asr && recordings.some((item) => !item.transcript.trim())),
205
+ });
206
+
207
+ try {
208
+ const data = await ApiService.analyzePG(formData, controller.signal);
209
+ setOutcome({
210
+ id: nextId("analysis"),
211
+ data,
212
+ files: new Map(recordings.map((item) => [item.file.name, item.file])),
213
+ settings: built.values,
214
+ unlabelledRecordings: recordings.length - Object.keys(speakers).length,
215
+ });
216
+ } catch (err) {
217
+ console.error("Error:", err);
218
+ if (controller.signal.aborted) {
219
+ setError({
220
+ message:
221
+ "Analysis cancelled. The server may still finish the job, but its results will not be shown.",
222
+ type: "cancelled",
223
+ });
224
+ } else if (err instanceof TypeError) {
225
+ setError({
226
+ message:
227
+ "Could not reach the analysis server. Check that the backend is running and try again.",
228
+ type: "analysis",
229
+ });
230
+ } else if (err instanceof Error && err.message.startsWith("Request timed out")) {
231
+ setError({
232
+ message: `The analysis took longer than ${
233
+ API_CONFIG.PG_ANALYZE_TIMEOUT / 60000
234
+ } minutes, so the app stopped waiting. Try fewer recordings at a time.`,
235
+ type: "analysis",
236
+ });
237
+ } else {
238
+ setError({
239
+ message: err instanceof Error ? err.message : "Unknown error occurred",
240
+ type: "analysis",
241
+ });
242
+ }
243
+ } finally {
244
+ abortRef.current = null;
245
+ setRun(null);
246
+ }
247
+ };
248
+
249
+ return (
250
+ // relative: absolutely positioned descendants (sr-only text) must scroll and clip
251
+ // inside this container instead of stretching the whole page
252
+ <div className="relative h-full overflow-y-auto">
253
+ <div className="max-w-5xl mx-auto p-4 md:p-8 space-y-6">
254
+ <header className="space-y-3">
255
+ <h2 className="text-2xl md:text-3xl font-bold text-blue-700">
256
+ Preference Grammar analysis
257
+ </h2>
258
+ <p className="text-gray-700 max-w-3xl">
259
+ Preference Grammar (C.U.C. Ugorji) standardises pronunciation in
260
+ New Englishes such as Nigerian English. Recordings of target words
261
+ from many speakers show which variants of a sound people actually
262
+ produce; the variants are then ranked on six tenets to choose the
263
+ preferred pronunciation.
264
+ </p>
265
+ <details className="max-w-3xl text-sm text-gray-700">
266
+ <summary className="cursor-pointer select-none font-semibold text-blue-700 rounded focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600">
267
+ How the analysis works
268
+ </summary>
269
+ <ol className="mt-2 list-decimal pl-5 space-y-1">
270
+ <li>
271
+ The server finds each target word in the recordings and decides
272
+ which variant of the sound each speaker produced, e.g. &lt;th&gt;
273
+ in “think” as <span className="font-ipa">[θ]</span>,{" "}
274
+ <span className="font-ipa">[t]</span> or{" "}
275
+ <span className="font-ipa">[s]</span>.
276
+ </li>
277
+ <li>
278
+ The attested variants become candidates and receive violation
279
+ marks for International acceptance (I-Ac), Contrastiveness
280
+ (ContR), Frequency (FreQ), Disambiguity (DisaM), Phonetic
281
+ simplicity (Pho-S) and Pedagogic convenience (Ped-C).
282
+ </li>
283
+ <li>
284
+ The operability table checks the candidates tenet by tenet in
285
+ your ranking. A candidate drops out at its first fatal mark,
286
+ and the one left standing is the preferred pronunciation.
287
+ </li>
288
+ </ol>
289
+ </details>
290
+ </header>
291
+
292
+ <form
293
+ onSubmit={handleSubmit}
294
+ noValidate
295
+ className="bg-white rounded-lg shadow-md p-4 md:p-8 space-y-8"
296
+ >
297
+ <section aria-labelledby="pg-target-heading" className="space-y-4">
298
+ <h3 id="pg-target-heading" className={sectionHeadingClass}>
299
+ 1. What to analyse
300
+ </h3>
301
+ <div className="grid gap-4 md:grid-cols-2">
302
+ <div className="space-y-2">
303
+ <label
304
+ htmlFor="pg-words"
305
+ className="block font-semibold text-gray-700"
306
+ >
307
+ Target word(s)
308
+ </label>
309
+ <input
310
+ id="pg-words"
311
+ type="text"
312
+ value={wordsInput}
313
+ onChange={(e) => setWordsInput(e.target.value)}
314
+ placeholder="think, three, thank"
315
+ autoComplete="off"
316
+ autoCapitalize="none"
317
+ spellCheck={false}
318
+ aria-describedby="pg-words-help"
319
+ className={inputClass}
320
+ />
321
+ <p id="pg-words-help" className="text-sm text-gray-600">
322
+ Separate words with commas. Every word should contain the
323
+ sound under study.
324
+ </p>
325
+ </div>
326
+ <div className="space-y-2">
327
+ <label
328
+ htmlFor="pg-unit"
329
+ className="block font-semibold text-gray-700"
330
+ >
331
+ Sound under study
332
+ </label>
333
+ <select
334
+ id="pg-unit"
335
+ value={unitKey}
336
+ onChange={(e) => setUnitKey(e.target.value)}
337
+ className={inputClass}
338
+ >
339
+ <option value="">Infer from the words</option>
340
+ {units.map((unit) => (
341
+ <option key={unit.key} value={unit.key}>
342
+ {unitOptionLabel(unit)}
343
+ </option>
344
+ ))}
345
+ </select>
346
+ {catalogError && (
347
+ <div
348
+ role="alert"
349
+ className="flex flex-wrap items-center gap-2 text-sm text-red-700"
350
+ >
351
+ <span>{`Could not load the units from the server (${catalogError}).`}</span>
352
+ <button
353
+ type="button"
354
+ onClick={() => setCatalogRequest((n) => n + 1)}
355
+ className="font-semibold underline hover:text-red-800 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500 rounded"
356
+ >
357
+ Retry
358
+ </button>
359
+ </div>
360
+ )}
361
+ </div>
362
+ </div>
363
+ <UnitSummary unit={selectedUnit} />
364
+ </section>
365
+
366
+ <section
367
+ aria-labelledby="pg-recordings-heading"
368
+ className="space-y-4"
369
+ >
370
+ <h3 id="pg-recordings-heading" className={sectionHeadingClass}>
371
+ 2. Recordings
372
+ </h3>
373
+ <p className="text-sm text-gray-600">
374
+ Add recordings of the target words from as many speakers as you
375
+ can.{" "}
376
+ {asr
377
+ ? "Files without a transcript are searched for the target words automatically."
378
+ : "A file without a transcript is treated as a recording of a single target word."}
379
+ </p>
380
+ <RecordingsInput
381
+ items={recordings}
382
+ onChange={setRecordings}
383
+ words={words}
384
+ asr={asr}
385
+ onAsrChange={setAsr}
386
+ diarize={diarize}
387
+ onDiarizeChange={setDiarize}
388
+ numSpeakers={numSpeakers}
389
+ onNumSpeakersChange={setNumSpeakers}
390
+ />
391
+ </section>
392
+
393
+ <section aria-labelledby="pg-ranking-heading" className="space-y-4">
394
+ <h3 id="pg-ranking-heading" className={sectionHeadingClass}>
395
+ 3. Tenet ranking
396
+ </h3>
397
+ <RankingEditor
398
+ items={ranking}
399
+ onChange={handleRankingChange}
400
+ tenets={tenets}
401
+ defaultRanking={defaultRanking}
402
+ />
403
+ </section>
404
+
405
+ <AdvancedSettings
406
+ settings={settings}
407
+ onSettingsChange={setSettings}
408
+ overrides={overrides}
409
+ onOverridesChange={setOverrides}
410
+ tenets={tenets}
411
+ variants={overrideVariants}
412
+ />
413
+
414
+ {error && (
415
+ <div
416
+ role="alert"
417
+ className={`p-4 rounded-lg border ${
418
+ error.type === "cancelled"
419
+ ? "bg-gray-50 border-gray-200"
420
+ : "bg-red-50 border-red-200"
421
+ }`}
422
+ >
423
+ <div className="flex items-start">
424
+ <Icon
425
+ name="error"
426
+ className={`w-5 h-5 mr-2 shrink-0 ${
427
+ error.type === "cancelled" ? "text-gray-600" : "text-red-500"
428
+ }`}
429
+ />
430
+ <p
431
+ className={
432
+ error.type === "cancelled" ? "text-gray-800" : "text-red-700"
433
+ }
434
+ >
435
+ {error.message}
436
+ </p>
437
+ </div>
438
+ </div>
439
+ )}
440
+
441
+ <div className="space-y-4">
442
+ {unvalidated && (
443
+ <div
444
+ id="pg-unvalidated-caution"
445
+ className="flex items-start gap-2 rounded-lg border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900"
446
+ >
447
+ <Icon name="warning" className="w-5 h-5 shrink-0" />
448
+ <p>
449
+ <strong>Not validated.</strong> The classifier's labels for
450
+ this sound have not passed a human-labelled test. Treat the
451
+ shares and the preferred form as provisional and check tokens
452
+ by ear.
453
+ </p>
454
+ </div>
455
+ )}
456
+ <button
457
+ type="submit"
458
+ disabled={!!run}
459
+ aria-describedby={
460
+ unvalidated ? "pg-unvalidated-caution" : undefined
461
+ }
462
+ className={`w-full py-3 rounded-lg font-semibold transition-colors duration-300 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-blue-600 ${
463
+ run
464
+ ? "bg-gray-300 text-gray-700 cursor-not-allowed"
465
+ : "bg-blue-600 hover:bg-blue-700 text-white"
466
+ }`}
467
+ >
468
+ {run ? "Analysing..." : "Run analysis"}
469
+ </button>
470
+ {run && (
471
+ <AnalysisProgress
472
+ startedAt={run.startedAt}
473
+ files={run.files}
474
+ words={run.words}
475
+ unscripted={run.unscripted}
476
+ onCancel={() => abortRef.current?.abort()}
477
+ />
478
+ )}
479
+ </div>
480
+ </form>
481
+
482
+ {outcome && (
483
+ <AnalysisResults
484
+ outcome={outcome}
485
+ tenets={tenets}
486
+ headingRef={resultsHeadingRef}
487
+ />
488
+ )}
489
+ </div>
490
+ </div>
491
+ );
492
+ };
493
+
494
+ export default PGAnalysis;
VoxPreference-frontend/src/components/Sidebar.tsx ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export type View = "chat" | "pg";
2
+
3
+ interface SidebarProps {
4
+ onSelect: (view: View) => void;
5
+ activeView: View;
6
+ }
7
+
8
+ const Sidebar = ({ onSelect, activeView }: SidebarProps) => {
9
+ const buttonClass = (view: View) =>
10
+ `flex-1 md:w-full p-3 rounded-lg flex items-center justify-center md:justify-start space-x-2 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-400 ${
11
+ activeView === view
12
+ ? "bg-blue-600 text-white"
13
+ : "text-gray-300 hover:bg-gray-700"
14
+ }`;
15
+
16
+ return (
17
+ <div className="w-full md:w-64 shrink-0 bg-gray-800 text-white md:h-screen p-4">
18
+ <div className="mb-4 md:mb-8">
19
+ <h1 className="text-2xl font-bold">VoxPreference</h1>
20
+ <p className="text-gray-400 text-sm">Audio Preference Assistant</p>
21
+ </div>
22
+
23
+ <nav className="flex gap-2 md:block md:space-y-2">
24
+ <button
25
+ onClick={() => onSelect("pg")}
26
+ aria-current={activeView === "pg" ? "page" : undefined}
27
+ className={buttonClass("pg")}
28
+ >
29
+ <svg
30
+ className="w-5 h-5"
31
+ fill="none"
32
+ stroke="currentColor"
33
+ viewBox="0 0 24 24"
34
+ aria-hidden="true"
35
+ >
36
+ <path
37
+ strokeLinecap="round"
38
+ strokeLinejoin="round"
39
+ strokeWidth={2}
40
+ d="M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3"
41
+ />
42
+ </svg>
43
+ <span>PG analysis</span>
44
+ </button>
45
+ <button
46
+ onClick={() => onSelect("chat")}
47
+ aria-current={activeView === "chat" ? "page" : undefined}
48
+ className={buttonClass("chat")}
49
+ >
50
+ <svg
51
+ className="w-5 h-5"
52
+ fill="none"
53
+ stroke="currentColor"
54
+ viewBox="0 0 24 24"
55
+ aria-hidden="true"
56
+ >
57
+ <path
58
+ strokeLinecap="round"
59
+ strokeLinejoin="round"
60
+ strokeWidth={2}
61
+ d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
62
+ />
63
+ </svg>
64
+ <span>Transcription (legacy)</span>
65
+ </button>
66
+ </nav>
67
+ </div>
68
+ );
69
+ };
70
+
71
+ export default Sidebar;
VoxPreference-frontend/src/components/pg/AdvancedSettings.tsx ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ FreqMode,
3
+ FreqWeighting,
4
+ OverrideRow,
5
+ PGTenet,
6
+ SettingsForm,
7
+ } from "../../types/pg";
8
+ import { DEFAULT_SETTINGS, SETTING_LABELS, nextId } from "../../utils/pg";
9
+ import Icon from "./Icon";
10
+
11
+ interface AdvancedSettingsProps {
12
+ settings: SettingsForm;
13
+ onSettingsChange: (settings: SettingsForm) => void;
14
+ overrides: OverrideRow[];
15
+ onOverridesChange: (overrides: OverrideRow[]) => void;
16
+ tenets: PGTenet[];
17
+ variants: string[]; // suggested for overrides: the unit's candidates and variants heard last run
18
+ }
19
+
20
+ interface NumberField {
21
+ key: keyof typeof SETTING_LABELS;
22
+ help: string;
23
+ fraction?: boolean; // 0-1, otherwise a whole number
24
+ }
25
+
26
+ const FREQ_FIELD: NumberField = {
27
+ key: "freq_threshold",
28
+ help: "*No FreQ when a variant's share is below this (0–1).",
29
+ fraction: true,
30
+ };
31
+
32
+ const OTHER_FIELDS: NumberField[] = [
33
+ {
34
+ key: "min_tokens",
35
+ help: "A variant needs at least this many tokens to compete; rarer variants are listed as too rare to compete.",
36
+ },
37
+ {
38
+ key: "min_speakers",
39
+ help: "A variant also needs tokens from at least this many speakers to compete.",
40
+ },
41
+ {
42
+ key: "disam_min_pairs",
43
+ help: "DisaM when using the variant would make at least this many common word pairs sound alike.",
44
+ },
45
+ {
46
+ key: "phos_world_threshold",
47
+ help: "*Pho-S when fewer than this share of the world's languages have the variant (0–1). Variants absent from most substrate languages are marked regardless.",
48
+ fraction: true,
49
+ },
50
+ {
51
+ key: "review_below",
52
+ help: "Tokens whose variant posterior is below this are flagged to check by ear (0–1).",
53
+ fraction: true,
54
+ },
55
+ ];
56
+
57
+ const inputClass =
58
+ "w-full px-3 py-2 border border-gray-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-transparent";
59
+
60
+ const AdvancedSettings = ({
61
+ settings,
62
+ onSettingsChange,
63
+ overrides,
64
+ onOverridesChange,
65
+ tenets,
66
+ variants,
67
+ }: AdvancedSettingsProps) => {
68
+ const updateOverride = (id: string, changes: Partial<OverrideRow>) => {
69
+ onOverridesChange(
70
+ overrides.map((row) => (row.id === id ? { ...row, ...changes } : row))
71
+ );
72
+ };
73
+
74
+ const addOverride = () => {
75
+ onOverridesChange([
76
+ ...overrides,
77
+ {
78
+ id: nextId("override"),
79
+ segment: "",
80
+ tenet: tenets[0]?.key ?? "",
81
+ count: "1",
82
+ },
83
+ ]);
84
+ };
85
+
86
+ const numberField = (field: NumberField) => (
87
+ <div key={field.key} className="space-y-1">
88
+ <label
89
+ htmlFor={`pg-setting-${field.key}`}
90
+ className="block text-sm font-semibold text-gray-700"
91
+ >
92
+ {SETTING_LABELS[field.key]}
93
+ </label>
94
+ <input
95
+ id={`pg-setting-${field.key}`}
96
+ type="number"
97
+ inputMode={field.fraction ? "decimal" : "numeric"}
98
+ min="0"
99
+ max={field.fraction ? "1" : undefined}
100
+ step={field.fraction ? "0.05" : "1"}
101
+ value={settings[field.key]}
102
+ onChange={(e) =>
103
+ onSettingsChange({ ...settings, [field.key]: e.target.value })
104
+ }
105
+ aria-describedby={`pg-setting-${field.key}-help`}
106
+ className={inputClass}
107
+ />
108
+ <p id={`pg-setting-${field.key}-help`} className="text-xs text-gray-600">
109
+ {field.help} Default {DEFAULT_SETTINGS[field.key]}.
110
+ </p>
111
+ </div>
112
+ );
113
+
114
+ return (
115
+ <details className="rounded-lg border border-gray-200">
116
+ <summary className="cursor-pointer select-none px-4 py-3 font-semibold text-gray-800 rounded-lg hover:bg-gray-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600">
117
+ Advanced settings
118
+ <span className="ml-2 font-normal text-sm text-gray-600">
119
+ thresholds and expert overrides
120
+ </span>
121
+ </summary>
122
+
123
+ <div className="px-4 pb-4 pt-2 space-y-6">
124
+ <div className="grid gap-4 sm:grid-cols-2">
125
+ {numberField(FREQ_FIELD)}
126
+ <div className="space-y-1">
127
+ <label
128
+ htmlFor="pg-setting-freq_weighting"
129
+ className="block text-sm font-semibold text-gray-700"
130
+ >
131
+ FreQ counts
132
+ </label>
133
+ <select
134
+ id="pg-setting-freq_weighting"
135
+ value={settings.freq_weighting}
136
+ onChange={(e) =>
137
+ onSettingsChange({
138
+ ...settings,
139
+ freq_weighting: e.target.value as FreqWeighting,
140
+ })
141
+ }
142
+ aria-describedby="pg-setting-freq_weighting-help"
143
+ className={inputClass}
144
+ >
145
+ <option value="tokens">Count every token</option>
146
+ <option value="speakers">Count every speaker equally</option>
147
+ </select>
148
+ <p
149
+ id="pg-setting-freq_weighting-help"
150
+ className="text-xs text-gray-600"
151
+ >
152
+ How variant shares are worked out for FreQ and Ped-C. Counting
153
+ speakers equally stops a few talkative speakers from deciding
154
+ the result. Default: count every token.
155
+ </p>
156
+ </div>
157
+ <div className="space-y-1">
158
+ <label
159
+ htmlFor="pg-setting-freq_mode"
160
+ className="block text-sm font-semibold text-gray-700"
161
+ >
162
+ What FreQ rewards
163
+ </label>
164
+ <select
165
+ id="pg-setting-freq_mode"
166
+ value={settings.freq_mode}
167
+ onChange={(e) =>
168
+ onSettingsChange({
169
+ ...settings,
170
+ freq_mode: e.target.value as FreqMode,
171
+ })
172
+ }
173
+ aria-describedby="pg-setting-freq_mode-help"
174
+ className={inputClass}
175
+ >
176
+ <option value="threshold">
177
+ Any variant above the threshold (as in Ugorji's tables)
178
+ </option>
179
+ <option value="most_frequent">
180
+ Only the most frequent variant
181
+ </option>
182
+ </select>
183
+ <p id="pg-setting-freq_mode-help" className="text-xs text-gray-600">
184
+ With “only the most frequent variant”, ranking FreQ first makes
185
+ the commonest pronunciation the preferred one. The threshold
186
+ reading is the one that reproduces Ugorji's published “think”
187
+ table.
188
+ </p>
189
+ </div>
190
+ {OTHER_FIELDS.map(numberField)}
191
+ </div>
192
+
193
+ <div className="space-y-1">
194
+ <label className="inline-flex items-center gap-2 text-sm font-semibold text-gray-700">
195
+ <input
196
+ type="checkbox"
197
+ checked={settings.calibrated}
198
+ onChange={(e) =>
199
+ onSettingsChange({ ...settings, calibrated: e.target.checked })
200
+ }
201
+ aria-describedby="pg-setting-calibrated-help"
202
+ className="h-4 w-4 accent-blue-600"
203
+ />
204
+ Use calibration
205
+ </label>
206
+ <p id="pg-setting-calibrated-help" className="text-xs text-gray-600">
207
+ Corrects the classifier's known biases with offsets fitted on
208
+ human-labelled tokens. Untick to see the uncorrected labels.
209
+ Default: on.
210
+ </p>
211
+ </div>
212
+
213
+ <button
214
+ type="button"
215
+ onClick={() => onSettingsChange(DEFAULT_SETTINGS)}
216
+ className="inline-flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg border border-gray-300 text-gray-700 hover:bg-gray-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
217
+ >
218
+ <Icon name="reset" className="w-4 h-4" />
219
+ Restore default settings
220
+ </button>
221
+
222
+ <fieldset className="space-y-3">
223
+ <legend className="text-sm font-semibold text-gray-700">
224
+ Expert overrides
225
+ </legend>
226
+ <p className="text-sm text-gray-600">
227
+ Set how many violation marks a variant gets on a tenet. Overrides
228
+ replace the computed marks.
229
+ </p>
230
+
231
+ <datalist id="pg-override-variants">
232
+ {variants.map((variant) => (
233
+ <option key={variant} value={variant} />
234
+ ))}
235
+ </datalist>
236
+
237
+ {overrides.map((row) => (
238
+ <div
239
+ key={row.id}
240
+ className="grid grid-cols-2 sm:grid-cols-[1fr_1fr_6rem_auto] items-end gap-3"
241
+ >
242
+ <div className="space-y-1">
243
+ <label
244
+ htmlFor={`pg-override-segment-${row.id}`}
245
+ className="block text-xs font-semibold text-gray-700"
246
+ >
247
+ Variant
248
+ </label>
249
+ <input
250
+ id={`pg-override-segment-${row.id}`}
251
+ type="text"
252
+ list="pg-override-variants"
253
+ value={row.segment}
254
+ onChange={(e) =>
255
+ updateOverride(row.id, { segment: e.target.value })
256
+ }
257
+ placeholder="e.g. t"
258
+ className={`${inputClass} font-ipa`}
259
+ />
260
+ </div>
261
+ <div className="space-y-1">
262
+ <label
263
+ htmlFor={`pg-override-tenet-${row.id}`}
264
+ className="block text-xs font-semibold text-gray-700"
265
+ >
266
+ Tenet
267
+ </label>
268
+ <select
269
+ id={`pg-override-tenet-${row.id}`}
270
+ value={row.tenet}
271
+ onChange={(e) =>
272
+ updateOverride(row.id, { tenet: e.target.value })
273
+ }
274
+ className={inputClass}
275
+ >
276
+ {tenets.map((tenet) => (
277
+ <option key={tenet.key} value={tenet.key}>
278
+ {tenet.key} ({tenet.name})
279
+ </option>
280
+ ))}
281
+ </select>
282
+ </div>
283
+ <div className="space-y-1">
284
+ <label
285
+ htmlFor={`pg-override-count-${row.id}`}
286
+ className="block text-xs font-semibold text-gray-700"
287
+ >
288
+ Marks
289
+ </label>
290
+ <input
291
+ id={`pg-override-count-${row.id}`}
292
+ type="number"
293
+ inputMode="numeric"
294
+ min="0"
295
+ step="1"
296
+ value={row.count}
297
+ onChange={(e) =>
298
+ updateOverride(row.id, { count: e.target.value })
299
+ }
300
+ className={inputClass}
301
+ />
302
+ </div>
303
+ <button
304
+ type="button"
305
+ onClick={() =>
306
+ onOverridesChange(overrides.filter((o) => o.id !== row.id))
307
+ }
308
+ aria-label={`Remove override${
309
+ row.segment ? ` for [${row.segment}]` : ""
310
+ }`}
311
+ className="justify-self-start p-2 rounded text-gray-600 hover:text-red-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500"
312
+ >
313
+ <Icon name="close" />
314
+ </button>
315
+ </div>
316
+ ))}
317
+
318
+ <button
319
+ type="button"
320
+ onClick={addOverride}
321
+ className="inline-flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg border border-gray-300 text-gray-700 hover:bg-gray-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
322
+ >
323
+ <Icon name="plus" className="w-4 h-4" />
324
+ Add override
325
+ </button>
326
+ </fieldset>
327
+ </div>
328
+ </details>
329
+ );
330
+ };
331
+
332
+ export default AdvancedSettings;
VoxPreference-frontend/src/components/pg/AnalysisProgress.tsx ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState } from "react";
2
+ import { formatDuration } from "../../utils/pg";
3
+
4
+ interface AnalysisProgressProps {
5
+ startedAt: number;
6
+ files: number;
7
+ words: string[];
8
+ unscripted: boolean; // some files are transcribed by speech recognition first
9
+ onCancel: () => void;
10
+ }
11
+
12
+ // The server sends no progress events, so show what is happening and for how long
13
+ const AnalysisProgress = ({
14
+ startedAt,
15
+ files,
16
+ words,
17
+ unscripted,
18
+ onCancel,
19
+ }: AnalysisProgressProps) => {
20
+ const [now, setNow] = useState(() => Date.now());
21
+
22
+ useEffect(() => {
23
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
24
+ return () => window.clearInterval(timer);
25
+ }, []);
26
+
27
+ return (
28
+ <div className="rounded-lg border border-blue-200 bg-blue-50 p-4">
29
+ <div className="flex flex-wrap items-start gap-3">
30
+ <svg
31
+ className="w-6 h-6 shrink-0 text-blue-700 motion-safe:animate-spin"
32
+ viewBox="0 0 24 24"
33
+ fill="none"
34
+ aria-hidden="true"
35
+ >
36
+ <circle
37
+ className="opacity-25"
38
+ cx="12"
39
+ cy="12"
40
+ r="10"
41
+ stroke="currentColor"
42
+ strokeWidth="4"
43
+ />
44
+ <path
45
+ className="opacity-75"
46
+ fill="currentColor"
47
+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
48
+ />
49
+ </svg>
50
+ <div className="flex-1 min-w-[12rem] space-y-1 text-blue-900">
51
+ <p role="status" className="font-semibold">
52
+ Analysing {files} recording{files === 1 ? "" : "s"} of{" "}
53
+ {words.map((word) => `“${word}”`).join(", ")}
54
+ </p>
55
+ <p className="text-sm">
56
+ The server is locating each word, scoring every candidate variant
57
+ and building the operability table. This can take several minutes
58
+ on a CPU, and longer the first time while the phone model loads.
59
+ {unscripted &&
60
+ " Unscripted audio is transcribed by speech recognition first, which takes longer still."}{" "}
61
+ You can switch to the chat in the meantime.
62
+ </p>
63
+ <p className="text-sm">
64
+ Elapsed{" "}
65
+ <span className="font-mono tabular-nums">
66
+ {formatDuration((now - startedAt) / 1000)}
67
+ </span>
68
+ </p>
69
+ </div>
70
+ <button
71
+ type="button"
72
+ onClick={onCancel}
73
+ className="px-4 py-2 rounded-lg border border-blue-300 bg-white text-blue-800 font-semibold hover:bg-blue-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600"
74
+ >
75
+ Cancel
76
+ </button>
77
+ </div>
78
+ <div
79
+ role="progressbar"
80
+ aria-label="Analysis in progress"
81
+ className="mt-3 h-1.5 overflow-hidden rounded-full bg-blue-100"
82
+ >
83
+ <div className="h-full w-1/3 rounded-full bg-blue-600 motion-safe:animate-indeterminate motion-reduce:w-full motion-reduce:opacity-40" />
84
+ </div>
85
+ </div>
86
+ );
87
+ };
88
+
89
+ export default AnalysisProgress;
VoxPreference-frontend/src/components/pg/AnalysisResults.tsx ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Fragment, Ref, useState } from "react";
2
+ import { AnalysisOutcome, PGTenet } from "../../types/pg";
3
+ import { downloadText, fileSlug, formatPercent } from "../../utils/pg";
4
+ import CandidateShares from "./CandidateShares";
5
+ import ClusterSummary from "./ClusterSummary";
6
+ import Icon from "./Icon";
7
+ import OperabilityTable from "./OperabilityTable";
8
+ import TokensTable from "./TokensTable";
9
+ import ValidationBadge from "./ValidationBadge";
10
+
11
+ interface AnalysisResultsProps {
12
+ outcome: AnalysisOutcome;
13
+ tenets: PGTenet[];
14
+ headingRef: Ref<HTMLHeadingElement>;
15
+ }
16
+
17
+ const cardClass = "bg-white rounded-lg shadow-md p-4 md:p-6";
18
+ const headingClass = "text-xl font-semibold text-gray-900";
19
+
20
+ const AnalysisResults = ({
21
+ outcome,
22
+ tenets,
23
+ headingRef,
24
+ }: AnalysisResultsProps) => {
25
+ // Kept here rather than in the table so the choice survives new runs
26
+ const [otStyle, setOtStyle] = useState(false);
27
+ const { data, files, settings, unlabelledRecordings } = outcome;
28
+ const { unit, tableau, stability } = data;
29
+ const recordingCount = new Set(data.tokens.map((token) => token.recording))
30
+ .size;
31
+ const reviewCount = data.tokens.filter((token) => token.review).length;
32
+ const prefix = `pg-${fileSlug(data.words.join("-"))}-`;
33
+ const shareBasis =
34
+ settings.freq_weighting === "speakers" ? "of speakers' usage" : "of tokens";
35
+
36
+ // How often each variant won when the speakers and each token's variant were resampled
37
+ const rates = stability ? Object.entries(stability.preferred_rate) : [];
38
+ const topRate = rates.length
39
+ ? Math.max(...rates.map(([, rate]) => rate))
40
+ : null;
41
+
42
+ return (
43
+ <section aria-labelledby="pg-results-heading" className="space-y-6">
44
+ <div className="space-y-1">
45
+ <h2
46
+ id="pg-results-heading"
47
+ ref={headingRef}
48
+ tabIndex={-1}
49
+ className="scroll-mt-6 text-2xl font-bold text-gray-900 focus:outline-none"
50
+ >
51
+ Results
52
+ </h2>
53
+ <p className="text-gray-700">
54
+ <span className="font-ipa">{unit.label}</span>{" "}
55
+ <span className="font-ipa">/{unit.phoneme}/</span> in{" "}
56
+ {data.words.map((word, i) => (
57
+ <Fragment key={word}>
58
+ {i > 0 && ", "}“{word}”
59
+ {data.canonical[word] && (
60
+ <span className="font-ipa"> /{data.canonical[word]}/</span>
61
+ )}
62
+ </Fragment>
63
+ ))}{" "}
64
+ <ValidationBadge unit={unit} />
65
+ </p>
66
+ <p className="text-sm text-gray-600">
67
+ {data.tokens.length} token{data.tokens.length === 1 ? "" : "s"} from{" "}
68
+ {recordingCount} recording{recordingCount === 1 ? "" : "s"} ·{" "}
69
+ {reviewCount} to check by ear
70
+ </p>
71
+ </div>
72
+
73
+ <div className={cardClass}>
74
+ <h3 className={headingClass}>
75
+ Preferred pronunciation{data.preferred.length > 1 ? "s" : ""}
76
+ </h3>
77
+ {data.preferred.length > 0 ? (
78
+ <ul className="mt-3 flex flex-wrap gap-x-12 gap-y-4">
79
+ {data.preferred.map((form) => {
80
+ const candidate = data.candidates.find((c) => c.form === form);
81
+ return (
82
+ <li key={form}>
83
+ <p className="font-ipa text-5xl md:text-6xl leading-tight text-blue-800">
84
+ {form}
85
+ </p>
86
+ {candidate && (
87
+ <p className="mt-1 text-sm text-gray-700">
88
+ <span className="font-ipa">{unit.label}</span> as{" "}
89
+ <span className="font-ipa">[{candidate.segment}]</span> ·{" "}
90
+ {formatPercent(candidate.share)} {shareBasis}
91
+ </p>
92
+ )}
93
+ {candidate && stability && (
94
+ <p className="mt-1 text-sm font-semibold text-gray-900">
95
+ Preferred in{" "}
96
+ {formatPercent(
97
+ stability.preferred_rate[candidate.segment] ?? 0
98
+ )}{" "}
99
+ of resamples of the {stability.speakers} speakers
100
+ </p>
101
+ )}
102
+ </li>
103
+ );
104
+ })}
105
+ </ul>
106
+ ) : (
107
+ <p className="mt-2 text-gray-700">
108
+ No preferred form: no tokens of{" "}
109
+ <span className="font-ipa">{unit.label}</span> were found in the
110
+ recordings. See the warnings below.
111
+ </p>
112
+ )}
113
+
114
+ {stability && rates.length > 0 && (
115
+ <div className="mt-2 space-y-0.5 text-xs text-gray-600">
116
+ <p>
117
+ Resamples the speakers and the classifier's uncertainty about
118
+ each token.
119
+ </p>
120
+ <p>
121
+ Won in {stability.resamples.toLocaleString("en")} bootstrap
122
+ resamples:{" "}
123
+ {rates.map(([segment, rate], i) => (
124
+ <Fragment key={segment}>
125
+ {i > 0 && " · "}
126
+ <span className="font-ipa">[{segment}]</span>{" "}
127
+ {formatPercent(rate)}
128
+ </Fragment>
129
+ ))}
130
+ </p>
131
+ </div>
132
+ )}
133
+ {stability && unlabelledRecordings > 0 && (
134
+ <p className="mt-1 text-xs text-gray-600">
135
+ {unlabelledRecordings === files.size
136
+ ? "No speaker ids were given, so each recording counts as a separate speaker."
137
+ : `${unlabelledRecordings} recording${
138
+ unlabelledRecordings === 1 ? "" : "s"
139
+ } without a speaker id count${
140
+ unlabelledRecordings === 1 ? "s" : ""
141
+ } as separate speakers.`}
142
+ </p>
143
+ )}
144
+ {stability === null && data.tokens.length > 0 && (
145
+ <p className="mt-2 text-xs text-gray-600">
146
+ Stability is not shown: it needs recordings from at least 3
147
+ speakers.
148
+ </p>
149
+ )}
150
+
151
+ {topRate !== null && topRate < 0.8 && (
152
+ <div className="mt-4 flex items-start gap-2 rounded-lg border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900">
153
+ <Icon name="warning" className="w-5 h-5 shrink-0" />
154
+ <p>
155
+ <strong>Not stable:</strong> the preferred form depends on which
156
+ speakers are included — collect more speakers or check the
157
+ low-confidence tokens.
158
+ </p>
159
+ </div>
160
+ )}
161
+
162
+ {tableau?.tie && (
163
+ <div className="mt-4 flex items-start gap-2 rounded-lg border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900">
164
+ <Icon name="warning" className="w-5 h-5 shrink-0" />
165
+ <p>
166
+ <strong>Tie.</strong> {data.preferred.length} candidates survive
167
+ every tenet in this ranking. Restore or re-rank a tenet that
168
+ separates them, or add an expert override, then run the analysis
169
+ again.
170
+ </p>
171
+ </div>
172
+ )}
173
+ </div>
174
+
175
+ {data.warnings.length > 0 && (
176
+ <div className="rounded-lg border border-amber-300 bg-amber-50 p-4">
177
+ <h3 className="flex items-center gap-2 font-semibold text-amber-900">
178
+ <Icon name="warning" />
179
+ Warnings
180
+ </h3>
181
+ <ul className="mt-2 list-disc pl-6 space-y-1 text-sm text-amber-900">
182
+ {data.warnings.map((warning, i) => (
183
+ <li key={i}>{warning}</li>
184
+ ))}
185
+ </ul>
186
+ </div>
187
+ )}
188
+
189
+ {tableau && (
190
+ <div className={`${cardClass} space-y-3`}>
191
+ <div className="flex flex-wrap items-center justify-between gap-3">
192
+ <h3 className={headingClass}>Operability table</h3>
193
+ <label className="inline-flex items-center gap-2 text-sm text-gray-700">
194
+ <input
195
+ type="checkbox"
196
+ checked={otStyle}
197
+ onChange={(e) => setOtStyle(e.target.checked)}
198
+ className="h-4 w-4 accent-blue-600"
199
+ />
200
+ Optimality Theory style
201
+ </label>
202
+ </div>
203
+ <p className="text-sm text-gray-600">
204
+ {otStyle
205
+ ? "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."
206
+ : "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."}{" "}
207
+ Select a cell to see the evidence behind its marks.
208
+ </p>
209
+ <OperabilityTable
210
+ key={outcome.id}
211
+ tableau={tableau}
212
+ candidates={data.candidates}
213
+ unitLabel={unit.label}
214
+ tenets={tenets}
215
+ otStyle={otStyle}
216
+ />
217
+ </div>
218
+ )}
219
+
220
+ {data.candidates.length > 0 && (
221
+ <div className={`${cardClass} space-y-3`}>
222
+ <h3 className={headingClass}>Attested variants</h3>
223
+ <CandidateShares
224
+ candidates={data.candidates}
225
+ superfluous={data.superfluous ?? []}
226
+ preferred={data.preferred}
227
+ totalTokens={data.tokens.length}
228
+ settings={settings}
229
+ />
230
+ </div>
231
+ )}
232
+
233
+ {data.tokens.length > 0 && (
234
+ <div className={cardClass}>
235
+ <TokensTable
236
+ key={outcome.id}
237
+ tokens={data.tokens}
238
+ files={files}
239
+ reviewBelow={settings.review_below}
240
+ />
241
+ </div>
242
+ )}
243
+
244
+ {data.clusters && (
245
+ // Collapsed by default: the clusters are exploratory, not evidence for the result
246
+ <details className={cardClass}>
247
+ <summary className="cursor-pointer select-none rounded-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600">
248
+ <h3 className={`${headingClass} inline`}>
249
+ Acoustic clusters (exploratory)
250
+ </h3>
251
+ <span className="mt-1 block text-sm text-gray-600">
252
+ These groupings barely separate the variants; they are shown for
253
+ exploration, not as evidence.
254
+ </span>
255
+ </summary>
256
+ <div className="mt-4">
257
+ <ClusterSummary clusters={data.clusters} tokens={data.tokens} />
258
+ </div>
259
+ </details>
260
+ )}
261
+
262
+ <div className={`${cardClass} space-y-3`}>
263
+ <h3 className={headingClass}>Downloads</h3>
264
+ <p className="text-sm text-gray-600">
265
+ Tables as CSV, the report as HTML, and the whole analysis as JSON.
266
+ </p>
267
+ <ul className="flex flex-wrap gap-2">
268
+ {Object.entries(data.files).map(([name, content]) => (
269
+ <li key={name}>
270
+ <button
271
+ type="button"
272
+ onClick={() => downloadText(`${prefix}${name}`, content)}
273
+ disabled={!content}
274
+ className="inline-flex items-center gap-2 px-3 py-2 text-sm rounded-lg border border-gray-300 text-gray-800 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600"
275
+ >
276
+ <Icon name="download" className="w-4 h-4" />
277
+ {name}
278
+ {!content && <span className="text-gray-600">(empty)</span>}
279
+ </button>
280
+ </li>
281
+ ))}
282
+ <li>
283
+ <button
284
+ type="button"
285
+ onClick={() =>
286
+ downloadText(
287
+ `${prefix}analysis.json`,
288
+ // the files above are downloads of their own
289
+ JSON.stringify({ ...data, files: undefined }, null, 2)
290
+ )
291
+ }
292
+ className="inline-flex items-center gap-2 px-3 py-2 text-sm rounded-lg border border-gray-300 text-gray-800 hover:bg-gray-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600"
293
+ >
294
+ <Icon name="download" className="w-4 h-4" />
295
+ analysis.json
296
+ </button>
297
+ </li>
298
+ </ul>
299
+ </div>
300
+ </section>
301
+ );
302
+ };
303
+
304
+ export default AnalysisResults;
VoxPreference-frontend/src/components/pg/CandidateShares.tsx ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { PGCandidate, PGVariantCount, SettingsValues } from "../../types/pg";
2
+ import { formatPercent } from "../../utils/pg";
3
+ import TierBadge from "./TierBadge";
4
+
5
+ interface CandidateSharesProps {
6
+ candidates: PGCandidate[];
7
+ superfluous: PGVariantCount[];
8
+ preferred: string[];
9
+ totalTokens: number;
10
+ settings: SettingsValues;
11
+ }
12
+
13
+ // Emphasis: the preferred form in the accent colour, the other variants in gray
14
+ const CandidateShares = ({
15
+ candidates,
16
+ superfluous,
17
+ preferred,
18
+ totalTokens,
19
+ settings,
20
+ }: CandidateSharesProps) => {
21
+ const threshold = Math.min(Math.max(settings.freq_threshold, 0), 1) * 100;
22
+ const hasTiers = candidates.some((candidate) => candidate.tier);
23
+
24
+ return (
25
+ <div className="space-y-3">
26
+ <p className="text-sm text-gray-600">
27
+ {settings.freq_weighting === "speakers"
28
+ ? `Each variant's share of the speakers' usage, with every speaker counting equally (${totalTokens} tokens).`
29
+ : `Share of the ${totalTokens} token${totalTokens === 1 ? "" : "s"} realised with each variant.`}{" "}
30
+ The vertical rule marks the FreQ threshold (
31
+ {formatPercent(settings.freq_threshold)}): variants below it get *No
32
+ FreQ.
33
+ </p>
34
+ <ul className="space-y-3">
35
+ {candidates.map((candidate) => {
36
+ const isPreferred = preferred.includes(candidate.form);
37
+ return (
38
+ <li key={candidate.form}>
39
+ <div className="flex items-baseline justify-between gap-3 text-sm">
40
+ <span className="min-w-0 flex flex-wrap items-baseline gap-x-2 gap-y-1">
41
+ <span className="font-ipa text-base text-gray-900">
42
+ [{candidate.segment}] {candidate.form}
43
+ </span>
44
+ {candidate.tier ? (
45
+ <TierBadge tier={candidate.tier} />
46
+ ) : (
47
+ isPreferred && (
48
+ <span className="text-xs font-semibold text-blue-800">
49
+ preferred
50
+ </span>
51
+ )
52
+ )}
53
+ </span>
54
+ <span className="shrink-0 tabular-nums text-gray-700">
55
+ {formatPercent(candidate.share)} ({candidate.tokens})
56
+ </span>
57
+ </div>
58
+ <div className="relative mt-1 h-3" aria-hidden="true">
59
+ <div className="absolute inset-0 rounded-r bg-gray-100" />
60
+ <div
61
+ className={`absolute inset-y-0 left-0 rounded-r ${
62
+ isPreferred ? "bg-blue-600" : "bg-gray-400"
63
+ }`}
64
+ style={{
65
+ width: `${candidate.share * 100}%`,
66
+ minWidth: candidate.share > 0 ? "2px" : undefined,
67
+ }}
68
+ />
69
+ <div
70
+ className="absolute -inset-y-1 w-px bg-gray-700"
71
+ style={{ left: `${threshold}%` }}
72
+ />
73
+ </div>
74
+ </li>
75
+ );
76
+ })}
77
+ </ul>
78
+
79
+ {hasTiers && (
80
+ <p className="text-xs text-gray-600">
81
+ Tiers: the formal standard is the preferred form; an allophone loses
82
+ but meets I-Ac and ContR, so it stays in the formal inventory; other
83
+ variants belong to the outer (informal) norm.
84
+ </p>
85
+ )}
86
+
87
+ {superfluous.length > 0 && (
88
+ <div className="border-t border-gray-200 pt-3">
89
+ <h4 className="text-sm font-semibold text-gray-800">
90
+ Also attested (too rare to compete)
91
+ </h4>
92
+ <p className="text-xs text-gray-600">
93
+ A variant needs at least {settings.min_tokens} token
94
+ {settings.min_tokens === 1 ? "" : "s"} from{" "}
95
+ {settings.min_speakers} speaker
96
+ {settings.min_speakers === 1 ? "" : "s"} to compete.
97
+ </p>
98
+ <ul className="mt-2 space-y-1 text-sm">
99
+ {superfluous.map((variant) => (
100
+ <li
101
+ key={variant.form}
102
+ className="flex items-baseline justify-between gap-3"
103
+ >
104
+ <span className="font-ipa text-base text-gray-900">
105
+ [{variant.segment}] {variant.form}
106
+ </span>
107
+ <span className="shrink-0 tabular-nums text-gray-700">
108
+ {formatPercent(variant.share)} ({variant.tokens})
109
+ </span>
110
+ </li>
111
+ ))}
112
+ </ul>
113
+ </div>
114
+ )}
115
+ </div>
116
+ );
117
+ };
118
+
119
+ export default CandidateShares;
VoxPreference-frontend/src/components/pg/ClusterSummary.tsx ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { PGClusters, PGToken } from "../../types/pg";
2
+
3
+ interface ClusterSummaryProps {
4
+ clusters: PGClusters;
5
+ tokens: PGToken[];
6
+ }
7
+
8
+ // One-hue sequential ramp (light to dark) for similarity from 0 to 1
9
+ const RAMP = [
10
+ "#cde2fb",
11
+ "#b7d3f6",
12
+ "#9ec5f4",
13
+ "#86b6ef",
14
+ "#6da7ec",
15
+ "#5598e7",
16
+ "#3987e5",
17
+ "#2a78d6",
18
+ "#256abf",
19
+ "#1c5cab",
20
+ "#184f95",
21
+ "#104281",
22
+ "#0d366b",
23
+ ];
24
+ // From this step on white text keeps at least 4.5:1 contrast; below it near-black text does
25
+ const FIRST_DARK_STEP = 8;
26
+
27
+ const rampStep = (value: number) =>
28
+ Math.round(Math.min(Math.max(value, 0), 1) * (RAMP.length - 1));
29
+
30
+ const ClusterSummary = ({ clusters, tokens }: ClusterSummaryProps) => {
31
+ const { categories, contrast_matrix, separation, subclusters } = clusters;
32
+ const counts = new Map<string, number>();
33
+ tokens.forEach((token) => {
34
+ const category = token.primary || token.variant;
35
+ counts.set(category, (counts.get(category) ?? 0) + 1);
36
+ });
37
+
38
+ const subclustersOf = (category: string) =>
39
+ Object.entries(subclusters)
40
+ .filter(
41
+ ([name]) => name === category || name.startsWith(`${category}.`)
42
+ )
43
+ .sort((a, b) => b[1] - a[1]);
44
+
45
+ return (
46
+ <div className="space-y-5">
47
+ <p className="text-sm text-gray-600">
48
+ Tokens are grouped by the variant they realise, then split by acoustic
49
+ similarity into sub-clusters: <span className="font-mono">t.1</span>{" "}
50
+ is the core of [t], higher numbers are sub-variants or outliers.
51
+ Separation is the mean silhouette (−1 to 1); higher means the variant
52
+ sounds more distinct from the others.
53
+ </p>
54
+
55
+ <div className="overflow-x-auto">
56
+ <table className="min-w-full text-sm">
57
+ <thead>
58
+ <tr className="border-b border-gray-300 text-left text-gray-700">
59
+ <th scope="col" className="py-2 pr-4 font-semibold">
60
+ Variant
61
+ </th>
62
+ <th scope="col" className="py-2 pr-4 font-semibold text-right">
63
+ Tokens
64
+ </th>
65
+ <th scope="col" className="py-2 pr-4 font-semibold text-right">
66
+ Separation
67
+ </th>
68
+ <th scope="col" className="py-2 font-semibold">
69
+ Sub-clusters
70
+ </th>
71
+ </tr>
72
+ </thead>
73
+ <tbody>
74
+ {categories.map((category) => {
75
+ const value = separation[category];
76
+ return (
77
+ <tr key={category} className="border-b border-gray-200">
78
+ <th
79
+ scope="row"
80
+ className="py-2 pr-4 text-left font-ipa text-base font-normal text-gray-900"
81
+ >
82
+ [{category}]
83
+ </th>
84
+ <td className="py-2 pr-4 text-right tabular-nums">
85
+ {counts.get(category) ?? 0}
86
+ </td>
87
+ <td className="py-2 pr-4 text-right tabular-nums">
88
+ {value === null || value === undefined
89
+ ? "—"
90
+ : value.toFixed(2)}
91
+ </td>
92
+ <td className="py-2">
93
+ <ul className="flex flex-wrap gap-1.5">
94
+ {subclustersOf(category).map(([name, count]) => (
95
+ <li
96
+ key={name}
97
+ className="rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-800"
98
+ >
99
+ <span className="font-ipa">{name}</span> · {count}
100
+ </li>
101
+ ))}
102
+ </ul>
103
+ </td>
104
+ </tr>
105
+ );
106
+ })}
107
+ </tbody>
108
+ </table>
109
+ </div>
110
+
111
+ {categories.length > 1 && (
112
+ <div className="space-y-2">
113
+ <h4 className="font-semibold text-gray-800">Contrast matrix</h4>
114
+ <p className="text-sm text-gray-600">
115
+ Cosine similarity between the average sound of each pair of
116
+ variants: 1 means identical, lower values mean the variants are
117
+ acoustically distinct.
118
+ </p>
119
+ <div className="overflow-x-auto">
120
+ <table className="border-separate border-spacing-0.5 text-sm">
121
+ <caption className="sr-only">
122
+ Cosine similarity between variant centroids
123
+ </caption>
124
+ <thead>
125
+ <tr>
126
+ <td />
127
+ {categories.map((category) => (
128
+ <th
129
+ key={category}
130
+ scope="col"
131
+ className="px-2 py-1 font-ipa text-base font-normal text-gray-900"
132
+ >
133
+ [{category}]
134
+ </th>
135
+ ))}
136
+ </tr>
137
+ </thead>
138
+ <tbody>
139
+ {categories.map((rowCategory, i) => (
140
+ <tr key={rowCategory}>
141
+ <th
142
+ scope="row"
143
+ className="px-2 py-1 text-right font-ipa text-base font-normal text-gray-900"
144
+ >
145
+ [{rowCategory}]
146
+ </th>
147
+ {categories.map((columnCategory, j) => {
148
+ const value = contrast_matrix[i]?.[j] ?? 0;
149
+ const label = `[${rowCategory}] and [${columnCategory}]: ${value.toFixed(
150
+ 2
151
+ )}`;
152
+ // Self-similarity is always 1, so the diagonal stays neutral
153
+ if (i === j) {
154
+ return (
155
+ <td
156
+ key={columnCategory}
157
+ title={label}
158
+ className="w-14 h-10 rounded text-center tabular-nums bg-gray-100 text-gray-600"
159
+ >
160
+ 1
161
+ </td>
162
+ );
163
+ }
164
+ const step = rampStep(value);
165
+ return (
166
+ <td
167
+ key={columnCategory}
168
+ title={label}
169
+ style={{ backgroundColor: RAMP[step] }}
170
+ className={`w-14 h-10 rounded text-center tabular-nums ${
171
+ step >= FIRST_DARK_STEP ? "text-white" : "text-gray-950"
172
+ }`}
173
+ >
174
+ {value.toFixed(2)}
175
+ </td>
176
+ );
177
+ })}
178
+ </tr>
179
+ ))}
180
+ </tbody>
181
+ </table>
182
+ </div>
183
+ <div className="flex items-center gap-2 text-xs text-gray-600" aria-hidden="true">
184
+ <span>0</span>
185
+ <span
186
+ className="h-2 w-32 rounded"
187
+ style={{ background: `linear-gradient(to right, ${RAMP.join(", ")})` }}
188
+ />
189
+ <span>1</span>
190
+ </div>
191
+ </div>
192
+ )}
193
+ </div>
194
+ );
195
+ };
196
+
197
+ export default ClusterSummary;
VoxPreference-frontend/src/components/pg/Icon.tsx ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Outline icons in the style of the app's other inline SVGs (24px grid, 2px stroke)
2
+ const PATHS = {
3
+ microphone: [
4
+ "M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z",
5
+ ],
6
+ upload: [
7
+ "M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12",
8
+ ],
9
+ close: ["M6 18L18 6M6 6l12 12"],
10
+ chevronUp: ["M5 15l7-7 7 7"],
11
+ chevronDown: ["M19 9l-7 7-7-7"],
12
+ download: ["M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"],
13
+ play: [
14
+ "M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z",
15
+ "M21 12a9 9 0 11-18 0 9 9 0 0118 0z",
16
+ ],
17
+ stop: [
18
+ "M21 12a9 9 0 11-18 0 9 9 0 0118 0z",
19
+ "M9 10a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z",
20
+ ],
21
+ warning: [
22
+ "M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z",
23
+ ],
24
+ error: ["M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"],
25
+ reset: [
26
+ "M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15",
27
+ ],
28
+ plus: ["M12 4v16m8-8H4"],
29
+ ear: [
30
+ "M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z",
31
+ ],
32
+ } as const;
33
+
34
+ export type IconName = keyof typeof PATHS;
35
+
36
+ interface IconProps {
37
+ name: IconName;
38
+ className?: string;
39
+ }
40
+
41
+ const Icon = ({ name, className = "w-5 h-5" }: IconProps) => (
42
+ <svg
43
+ className={className}
44
+ fill="none"
45
+ stroke="currentColor"
46
+ viewBox="0 0 24 24"
47
+ aria-hidden="true"
48
+ >
49
+ {PATHS[name].map((d) => (
50
+ <path
51
+ key={d}
52
+ strokeLinecap="round"
53
+ strokeLinejoin="round"
54
+ strokeWidth={2}
55
+ d={d}
56
+ />
57
+ ))}
58
+ </svg>
59
+ );
60
+
61
+ export default Icon;
VoxPreference-frontend/src/components/pg/OperabilityTable.tsx ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from "react";
2
+ import { PGCandidate, PGTableau, PGTableauRow, PGTenet } from "../../types/pg";
3
+ import {
4
+ TableauColumn,
5
+ candidateLetter,
6
+ describeMarks,
7
+ eliminatedAt,
8
+ formatPercent,
9
+ formatRanking,
10
+ tableauCell,
11
+ tableauColumns,
12
+ } from "../../utils/pg";
13
+ import TierBadge from "./TierBadge";
14
+
15
+ interface OperabilityTableProps {
16
+ tableau: PGTableau;
17
+ candidates: PGCandidate[];
18
+ unitLabel: string;
19
+ tenets: PGTenet[];
20
+ // Optimality Theory style: fatal marks, shading after elimination and ☞. Otherwise the
21
+ // table follows Ugorji's published PG tables: every mark, no "!", no shading, ⇒
22
+ otStyle: boolean;
23
+ }
24
+
25
+ // "*!" is the fatal mark; it is drawn in red, the other marks in ink
26
+ const Marks = ({ cell }: { cell: string }) => {
27
+ const bang = cell.indexOf("!");
28
+ if (bang < 0) return <span aria-hidden="true">{cell}</span>;
29
+ const fatalStart = Math.max(0, bang - 1);
30
+ return (
31
+ <span aria-hidden="true">
32
+ {cell.slice(0, fatalStart)}
33
+ <span className="font-bold text-red-700">
34
+ {cell.slice(fatalStart, bang + 1)}
35
+ </span>
36
+ {cell.slice(bang + 1)}
37
+ </span>
38
+ );
39
+ };
40
+
41
+ // Solid rules between ranked tenets, dashed between unranked ones.
42
+ // Cells draw only their own top and left edges (separated borders), because in the
43
+ // collapsed model a neighbour's solid border would win over a dashed one.
44
+ // The sticky candidate column draws the rule before the first tenet.
45
+ const stratumBorder = (column: TableauColumn) =>
46
+ column.startsStratum
47
+ ? column.stratum > 0
48
+ ? "border-l-2 border-l-gray-500"
49
+ : ""
50
+ : "[border-left-width:1px] [border-left-style:dashed] border-l-gray-500";
51
+
52
+ const OperabilityTable = ({
53
+ tableau,
54
+ candidates,
55
+ unitLabel,
56
+ tenets,
57
+ otStyle,
58
+ }: OperabilityTableProps) => {
59
+ const [selected, setSelected] = useState<{
60
+ row: number;
61
+ column: number;
62
+ } | null>(null);
63
+ const columns = tableauColumns(tableau, tenets);
64
+ const winnerMark = otStyle ? "☞" : "⇒";
65
+
66
+ const candidateFor = (row: PGTableauRow, index: number) =>
67
+ candidates.find((candidate) => candidate.form === row.candidate) ??
68
+ candidates[index];
69
+
70
+ const evidence = (row: PGTableauRow, index: number, column: TableauColumn) =>
71
+ candidateFor(row, index)?.violations[column.key];
72
+
73
+ // The marks as shown: PG style drops the fatal "!"
74
+ const cellText = (row: PGTableauRow, column: TableauColumn) => {
75
+ const cell = tableauCell(row, column);
76
+ return otStyle ? cell : cell.replace(/!/g, "");
77
+ };
78
+
79
+ const selectedRow = selected ? tableau.rows[selected.row] : undefined;
80
+ const selectedColumn = selected ? columns[selected.column] : undefined;
81
+ const selectedEvidence =
82
+ selected && selectedRow && selectedColumn
83
+ ? evidence(selectedRow, selected.row, selectedColumn)
84
+ : undefined;
85
+
86
+ return (
87
+ <div className="space-y-3">
88
+ <div className="overflow-x-auto rounded-lg border border-gray-300">
89
+ <table className="min-w-full border-separate border-spacing-0 text-sm">
90
+ <caption className="sr-only">
91
+ Operability table for {unitLabel}: candidates in rows, tenets in
92
+ ranking order in columns
93
+ </caption>
94
+ <thead>
95
+ <tr className="bg-gray-50">
96
+ <th
97
+ scope="col"
98
+ className="sticky left-0 z-10 bg-gray-50 border-r-2 border-r-gray-500 px-3 py-2 text-left font-ipa text-base"
99
+ >
100
+ {unitLabel}
101
+ </th>
102
+ {columns.map((column) => (
103
+ <th
104
+ key={column.key}
105
+ scope="col"
106
+ className={`px-3 py-2 text-center align-bottom ${stratumBorder(
107
+ column
108
+ )}`}
109
+ >
110
+ <span className="block font-mono whitespace-nowrap">
111
+ {column.label}
112
+ </span>
113
+ <span className="block text-xs font-normal text-gray-600">
114
+ {column.name}
115
+ </span>
116
+ </th>
117
+ ))}
118
+ </tr>
119
+ </thead>
120
+ <tbody>
121
+ {tableau.rows.map((row, r) => {
122
+ const out = otStyle ? eliminatedAt(row, columns) : null;
123
+ const letter = candidateLetter(r);
124
+ const tier = candidateFor(row, r)?.tier;
125
+ return (
126
+ <tr
127
+ key={`${row.candidate}-${r}`}
128
+ className={row.preferred ? "bg-blue-50" : "bg-white"}
129
+ >
130
+ <th
131
+ scope="row"
132
+ className={`sticky left-0 z-10 border-t border-t-gray-300 border-r-2 border-r-gray-500 px-3 py-2 text-left font-normal whitespace-nowrap ${
133
+ row.preferred ? "bg-blue-50" : "bg-white"
134
+ }`}
135
+ >
136
+ <span
137
+ className={`font-ipa text-base text-gray-900 ${
138
+ row.preferred ? "font-bold" : ""
139
+ }`}
140
+ >
141
+ {letter}.{" "}
142
+ {row.preferred && (
143
+ <span aria-hidden="true" className="text-blue-700">
144
+ {winnerMark}{" "}
145
+ </span>
146
+ )}
147
+ {row.candidate}
148
+ </span>
149
+ {row.preferred && (
150
+ <span className="sr-only"> (preferred)</span>
151
+ )}
152
+ <span className="block text-xs text-gray-600">
153
+ <span className="font-ipa">[{row.segment}]</span> ·{" "}
154
+ {formatPercent(row.share)} · {row.tokens} token
155
+ {row.tokens === 1 ? "" : "s"}
156
+ </span>
157
+ {tier && (
158
+ <span className="mt-1 block">
159
+ <TierBadge tier={tier} />
160
+ </span>
161
+ )}
162
+ </th>
163
+ {columns.map((column, c) => {
164
+ const cell = cellText(row, column);
165
+ const shaded = out !== null && column.stratum > out;
166
+ const violation = evidence(row, r, column);
167
+ const isSelected =
168
+ selected?.row === r && selected?.column === c;
169
+ return (
170
+ <td
171
+ key={column.key}
172
+ className={`border-t border-t-gray-300 p-0 ${stratumBorder(
173
+ column
174
+ )} ${shaded ? "bg-gray-200" : ""}`}
175
+ >
176
+ <button
177
+ type="button"
178
+ onClick={() =>
179
+ setSelected(isSelected ? null : { row: r, column: c })
180
+ }
181
+ aria-pressed={isSelected}
182
+ aria-label={`${letter}. ${row.candidate}, ${
183
+ column.label
184
+ } (${column.name}): ${describeMarks(cell)}${
185
+ shaded ? ", already eliminated" : ""
186
+ }. Show evidence`}
187
+ title={
188
+ violation?.reason
189
+ ? `${violation.reason} [${violation.source}]`
190
+ : undefined
191
+ }
192
+ className={`w-full min-w-16 min-h-11 px-3 py-2 font-mono text-base text-center focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-blue-600 hover:bg-blue-100/60 ${
193
+ shaded ? "text-gray-600" : "text-gray-900"
194
+ } ${isSelected ? "ring-2 ring-inset ring-blue-600" : ""}`}
195
+ >
196
+ <Marks cell={cell} />
197
+ </button>
198
+ </td>
199
+ );
200
+ })}
201
+ </tr>
202
+ );
203
+ })}
204
+ </tbody>
205
+ </table>
206
+ </div>
207
+
208
+ <p className="text-xs text-gray-600">
209
+ <span className="font-mono">*</span> violation ·{" "}
210
+ {otStyle && (
211
+ <>
212
+ <span className="font-mono font-bold text-red-700">*!</span> fatal
213
+ violation ·{" "}
214
+ <span className="inline-block w-3 h-3 align-middle bg-gray-200 border border-gray-300" />{" "}
215
+ shaded: no longer decides anything ·{" "}
216
+ </>
217
+ )}
218
+ <span aria-hidden="true">{winnerMark}</span> preferred. Ranking:{" "}
219
+ <span className="font-mono">{formatRanking(tableau.ranking)}</span>
220
+ </p>
221
+
222
+ <div
223
+ aria-live="polite"
224
+ className="rounded-lg border border-gray-200 bg-gray-50 p-3 text-sm"
225
+ >
226
+ {selected && selectedRow && selectedColumn ? (
227
+ <div className="space-y-1">
228
+ <p className="font-semibold text-gray-900">
229
+ <span className="font-ipa">
230
+ {candidateLetter(selected.row)}. {selectedRow.candidate}
231
+ </span>{" "}
232
+ · {selectedColumn.label} ({selectedColumn.name}) ·{" "}
233
+ {describeMarks(cellText(selectedRow, selectedColumn))}
234
+ </p>
235
+ <p className="text-gray-800">
236
+ {selectedEvidence?.reason || "No reason was recorded for this cell."}
237
+ </p>
238
+ {selectedEvidence?.source && (
239
+ <p className="text-xs text-gray-600">
240
+ Source: {selectedEvidence.source}
241
+ </p>
242
+ )}
243
+ </div>
244
+ ) : (
245
+ <p className="text-gray-600">
246
+ Select a cell to see the evidence behind its marks.
247
+ </p>
248
+ )}
249
+ </div>
250
+
251
+ <details className="rounded-lg border border-gray-200">
252
+ <summary className="cursor-pointer select-none px-3 py-2 text-sm font-semibold text-blue-700 rounded-lg hover:bg-gray-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600">
253
+ Evidence for every cell
254
+ </summary>
255
+ <div className="px-3 pb-3 space-y-4">
256
+ {tableau.rows.map((row, r) => (
257
+ <div key={`${row.candidate}-${r}`}>
258
+ <p className="font-semibold text-gray-900">
259
+ <span className="font-ipa">
260
+ {candidateLetter(r)}. {row.candidate}
261
+ </span>{" "}
262
+ <span className="font-normal text-gray-600">
263
+ (<span className="font-ipa">[{row.segment}]</span>)
264
+ </span>
265
+ </p>
266
+ <ul className="mt-1 space-y-1 text-sm">
267
+ {columns.map((column) => {
268
+ const violation = evidence(row, r, column);
269
+ return (
270
+ <li key={column.key} className="text-gray-800">
271
+ <span className="font-mono">{column.label}</span> ·{" "}
272
+ {describeMarks(cellText(row, column))}
273
+ {violation?.reason && <> · {violation.reason}</>}
274
+ {violation?.source && (
275
+ <span className="text-gray-600">
276
+ {" "}
277
+ ({violation.source})
278
+ </span>
279
+ )}
280
+ </li>
281
+ );
282
+ })}
283
+ </ul>
284
+ </div>
285
+ ))}
286
+ </div>
287
+ </details>
288
+ </div>
289
+ );
290
+ };
291
+
292
+ export default OperabilityTable;
VoxPreference-frontend/src/components/pg/RankingEditor.tsx ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useRef, useState } from "react";
2
+ import { PGTenet, RankingItem } from "../../types/pg";
3
+ import {
4
+ formatRanking,
5
+ moveRankingItem,
6
+ rankingItemsFrom,
7
+ rankingStrata,
8
+ } from "../../utils/pg";
9
+ import Icon from "./Icon";
10
+
11
+ interface RankingEditorProps {
12
+ items: RankingItem[];
13
+ onChange: (items: RankingItem[]) => void;
14
+ tenets: PGTenet[];
15
+ defaultRanking: string;
16
+ }
17
+
18
+ const RankingEditor = ({
19
+ items,
20
+ onChange,
21
+ tenets,
22
+ defaultRanking,
23
+ }: RankingEditorProps) => {
24
+ const [announcement, setAnnouncement] = useState("");
25
+ const buttonRefs = useRef(new Map<string, HTMLButtonElement>());
26
+ const pendingFocus = useRef<string | null>(null);
27
+
28
+ // Moving a row re-orders the DOM, so return focus to the button that moved it
29
+ useEffect(() => {
30
+ if (pendingFocus.current) {
31
+ buttonRefs.current.get(pendingFocus.current)?.focus();
32
+ pendingFocus.current = null;
33
+ }
34
+ }, [items]);
35
+
36
+ const setButtonRef = (id: string) => (element: HTMLButtonElement | null) => {
37
+ if (element) {
38
+ buttonRefs.current.set(id, element);
39
+ } else {
40
+ buttonRefs.current.delete(id);
41
+ }
42
+ };
43
+
44
+ const nameOf = (key: string) =>
45
+ tenets.find((tenet) => tenet.key === key)?.name ?? key;
46
+ const strata = rankingStrata(items);
47
+ const keptCount = items.filter((item) => item.enabled).length;
48
+
49
+ // Unranked tenets share their stratum's number
50
+ const rankOf = new Map<string, number>();
51
+ strata.forEach((stratum, i) =>
52
+ stratum.forEach((key) => rankOf.set(key, i + 1))
53
+ );
54
+
55
+ const move = (index: number, delta: -1 | 1) => {
56
+ const next = moveRankingItem(items, index, delta);
57
+ if (!next) return;
58
+ const moved = items[index];
59
+ pendingFocus.current = `${moved.key}:${delta < 0 ? "up" : "down"}`;
60
+ onChange(next);
61
+ setAnnouncement(
62
+ `${moved.key} moved to position ${index + delta + 1} of ${items.length}`
63
+ );
64
+ };
65
+
66
+ const toggleKept = (index: number) => {
67
+ const item = items[index];
68
+ onChange(
69
+ items.map((other, i) =>
70
+ i === index ? { ...other, enabled: !other.enabled } : other
71
+ )
72
+ );
73
+ setAnnouncement(
74
+ item.enabled
75
+ ? `${item.key} deleted from the ranking`
76
+ : `${item.key} restored to the ranking`
77
+ );
78
+ };
79
+
80
+ const toggleTie = (index: number) => {
81
+ onChange(
82
+ items.map((other, i) =>
83
+ i === index ? { ...other, tiedWithAbove: !other.tiedWithAbove } : other
84
+ )
85
+ );
86
+ };
87
+
88
+ const reset = () => {
89
+ onChange(rankingItemsFrom(defaultRanking, tenets));
90
+ setAnnouncement("Ranking reset to the default");
91
+ };
92
+
93
+ // Buttons at either end use aria-disabled rather than disabled, so they keep focus
94
+ // and a repeated key press does nothing instead of bouncing the tenet back
95
+ const arrowClass =
96
+ "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";
97
+
98
+ return (
99
+ <div className="space-y-3">
100
+ <p id="pg-ranking-help" className="text-sm text-gray-600">
101
+ Higher tenets dominate lower ones: a candidate is out as soon as it has
102
+ more marks than a rival on the highest tenet where they differ. Untick
103
+ a tenet to delete it, or make it unranked with the tenet above to pool
104
+ their marks.
105
+ </p>
106
+
107
+ <ol className="space-y-2" aria-describedby="pg-ranking-help">
108
+ {items.map((item, index) => {
109
+ const above = index > 0 ? items[index - 1] : undefined;
110
+ const name = nameOf(item.key);
111
+
112
+ return (
113
+ <li
114
+ key={item.key}
115
+ className={`flex items-center gap-3 rounded-lg border p-3 ${
116
+ item.enabled
117
+ ? "border-gray-300 bg-white"
118
+ : "border-dashed border-gray-300 bg-gray-50"
119
+ }`}
120
+ >
121
+ <span
122
+ aria-hidden="true"
123
+ className={`w-8 h-8 shrink-0 rounded-full flex items-center justify-center text-sm font-semibold ${
124
+ item.enabled
125
+ ? "bg-blue-100 text-blue-800"
126
+ : "bg-gray-200 text-gray-600"
127
+ }`}
128
+ >
129
+ {rankOf.get(item.key) ?? "–"}
130
+ </span>
131
+
132
+ <div className="flex-1 min-w-0">
133
+ <p className="text-gray-900">
134
+ <span
135
+ className={`font-semibold ${
136
+ item.enabled ? "" : "line-through text-gray-600"
137
+ }`}
138
+ >
139
+ {item.key}
140
+ </span>{" "}
141
+ <span className="text-sm text-gray-600">{name}</span>
142
+ {!item.enabled && (
143
+ <span className="sr-only"> (deleted)</span>
144
+ )}
145
+ </p>
146
+ <div className="mt-1 flex flex-wrap gap-x-4 gap-y-1 text-sm text-gray-700">
147
+ <label className="inline-flex items-center gap-1.5">
148
+ <input
149
+ type="checkbox"
150
+ checked={item.enabled}
151
+ onChange={() => toggleKept(index)}
152
+ disabled={item.enabled && keptCount === 1}
153
+ className="h-4 w-4 accent-blue-600"
154
+ />
155
+ Keep<span className="sr-only"> {name} in the ranking</span>
156
+ </label>
157
+ {item.enabled && above && (
158
+ <label className="inline-flex items-center gap-1.5">
159
+ <input
160
+ type="checkbox"
161
+ checked={item.tiedWithAbove}
162
+ onChange={() => toggleTie(index)}
163
+ className="h-4 w-4 accent-blue-600"
164
+ />
165
+ Unranked with {above.key}
166
+ </label>
167
+ )}
168
+ </div>
169
+ </div>
170
+
171
+ <div className="flex flex-col gap-1">
172
+ <button
173
+ type="button"
174
+ ref={setButtonRef(`${item.key}:up`)}
175
+ onClick={() => move(index, -1)}
176
+ aria-disabled={index === 0}
177
+ aria-label={`Move ${name} up`}
178
+ className={arrowClass}
179
+ >
180
+ <Icon name="chevronUp" className="w-4 h-4" />
181
+ </button>
182
+ <button
183
+ type="button"
184
+ ref={setButtonRef(`${item.key}:down`)}
185
+ onClick={() => move(index, 1)}
186
+ aria-disabled={index === items.length - 1}
187
+ aria-label={`Move ${name} down`}
188
+ className={arrowClass}
189
+ >
190
+ <Icon name="chevronDown" className="w-4 h-4" />
191
+ </button>
192
+ </div>
193
+ </li>
194
+ );
195
+ })}
196
+ </ol>
197
+
198
+ <div className="flex flex-wrap items-center justify-between gap-3">
199
+ <p className="text-sm text-gray-700 min-w-0">
200
+ Ranking sent:{" "}
201
+ <code className="font-mono text-gray-900 bg-gray-100 rounded px-2 py-1 break-words">
202
+ {formatRanking(strata)}
203
+ </code>
204
+ </p>
205
+ <button
206
+ type="button"
207
+ onClick={reset}
208
+ className="inline-flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg border border-gray-300 text-gray-700 hover:bg-gray-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
209
+ >
210
+ <Icon name="reset" className="w-4 h-4" />
211
+ Reset to default
212
+ </button>
213
+ </div>
214
+
215
+ <p className="sr-only" aria-live="polite">
216
+ {announcement}
217
+ </p>
218
+ </div>
219
+ );
220
+ };
221
+
222
+ export default RankingEditor;
VoxPreference-frontend/src/components/pg/RecordingsInput.tsx ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ ChangeEvent,
3
+ Dispatch,
4
+ DragEvent,
5
+ SetStateAction,
6
+ useRef,
7
+ useState,
8
+ } from "react";
9
+ import { API_CONFIG } from "../../config/api";
10
+ import useAudioRecorder from "../../hooks/useAudioRecorder";
11
+ import useClipPlayer from "../../hooks/useClipPlayer";
12
+ import { RecordingItem } from "../../types/pg";
13
+ import {
14
+ extensionForMimeType,
15
+ fileNameHasWord,
16
+ fileSlug,
17
+ formatDuration,
18
+ formatFileSize,
19
+ isAudioFile,
20
+ isAutoTranscript,
21
+ nextId,
22
+ transcriptHasWord,
23
+ uniqueFileName,
24
+ } from "../../utils/pg";
25
+ import Icon from "./Icon";
26
+
27
+ interface RecordingsInputProps {
28
+ items: RecordingItem[];
29
+ onChange: Dispatch<SetStateAction<RecordingItem[]>>;
30
+ words: string[];
31
+ asr: boolean; // files without a transcript are unscripted audio, searched by speech recognition
32
+ onAsrChange: (asr: boolean) => void;
33
+ diarize: boolean; // separate the speakers inside unscripted files that have no speaker id
34
+ onDiarizeChange: (diarize: boolean) => void;
35
+ numSpeakers: string; // how many people talk in each such file; empty = estimate
36
+ onNumSpeakersChange: (value: string) => void;
37
+ }
38
+
39
+ // One compact row per recording: datasets often hold dozens of clips
40
+ const ROW_COLUMNS =
41
+ "grid grid-cols-[2rem_minmax(0,1fr)_2rem] md:grid-cols-[2rem_minmax(0,1fr)_minmax(0,1.7fr)_2rem] items-center gap-x-3 gap-y-2";
42
+ const FIELD_COLUMNS = "grid gap-2 sm:grid-cols-[9rem_minmax(0,1fr)]";
43
+ const fieldClass =
44
+ "w-full px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-transparent";
45
+
46
+ const RecordingsInput = ({
47
+ items,
48
+ onChange,
49
+ words,
50
+ asr,
51
+ onAsrChange,
52
+ diarize,
53
+ onDiarizeChange,
54
+ numSpeakers,
55
+ onNumSpeakersChange,
56
+ }: RecordingsInputProps) => {
57
+ const [isDragging, setIsDragging] = useState(false);
58
+ const [error, setError] = useState<string | null>(null);
59
+ const [clipWord, setClipWord] = useState("");
60
+ const fileInputRef = useRef<HTMLInputElement>(null);
61
+ const player = useClipPlayer();
62
+
63
+ // The word a new clip is named after, so the server can tell which word it is
64
+ const recordWord = words.includes(clipWord) ? clipWord : words[0] ?? "";
65
+
66
+ const addFiles = (files: File[], origin: RecordingItem["origin"]) => {
67
+ const accepted: File[] = [];
68
+ const problems: string[] = [];
69
+ for (const file of files) {
70
+ if (!isAudioFile(file)) {
71
+ problems.push(`${file.name} is not an audio file`);
72
+ } else if (file.size > API_CONFIG.MAX_FILE_SIZE) {
73
+ problems.push(
74
+ `${file.name} is larger than ${
75
+ API_CONFIG.MAX_FILE_SIZE / (1024 * 1024)
76
+ }MB`
77
+ );
78
+ } else {
79
+ accepted.push(file);
80
+ }
81
+ }
82
+ setError(problems.length ? `${problems.join(". ")}.` : null);
83
+
84
+ const entries = accepted.map((file) => ({ id: nextId("audio"), file }));
85
+ onChange((prev) => {
86
+ const taken = new Set(prev.map((item) => item.file.name));
87
+ const added = entries.map(({ id, file }) => {
88
+ const name = uniqueFileName(file.name, taken);
89
+ taken.add(name);
90
+ return {
91
+ id,
92
+ origin,
93
+ speaker: "",
94
+ transcript: "",
95
+ file:
96
+ name === file.name
97
+ ? file
98
+ : new File([file], name, {
99
+ type: file.type,
100
+ lastModified: file.lastModified,
101
+ }),
102
+ };
103
+ });
104
+ return [...prev, ...added];
105
+ });
106
+ };
107
+
108
+ const recorder = useAudioRecorder((clip) => {
109
+ const name = `${fileSlug(recordWord || "clip")}-1.${extensionForMimeType(
110
+ clip.type
111
+ )}`;
112
+ addFiles([new File([clip], name, { type: clip.type })], "recording");
113
+ });
114
+
115
+ const updateItem = (id: string, changes: Partial<RecordingItem>) => {
116
+ onChange((prev) =>
117
+ prev.map((item) => (item.id === id ? { ...item, ...changes } : item))
118
+ );
119
+ };
120
+
121
+ const removeItem = (id: string) => {
122
+ if (player.playing === id) player.stop();
123
+ onChange((prev) => prev.filter((item) => item.id !== id));
124
+ };
125
+
126
+ const removeAll = () => {
127
+ player.stop();
128
+ onChange([]);
129
+ };
130
+
131
+ const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
132
+ e.preventDefault();
133
+ e.stopPropagation();
134
+ setIsDragging(true);
135
+ };
136
+
137
+ const handleDragLeave = (e: DragEvent<HTMLDivElement>) => {
138
+ e.preventDefault();
139
+ e.stopPropagation();
140
+ setIsDragging(false);
141
+ };
142
+
143
+ const handleDrop = (e: DragEvent<HTMLDivElement>) => {
144
+ e.preventDefault();
145
+ e.stopPropagation();
146
+ setIsDragging(false);
147
+ if (e.dataTransfer.files.length > 0) {
148
+ addFiles(Array.from(e.dataTransfer.files), "upload");
149
+ }
150
+ };
151
+
152
+ const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
153
+ if (e.target.files && e.target.files.length > 0) {
154
+ addFiles(Array.from(e.target.files), "upload");
155
+ }
156
+ // Allow the same file to be picked again after removing it
157
+ e.target.value = "";
158
+ };
159
+
160
+ const buttonClass =
161
+ "inline-flex items-center gap-2 px-4 py-2 rounded-lg font-semibold focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-blue-600 disabled:opacity-50 disabled:cursor-not-allowed";
162
+ const totalSize = items.reduce((sum, item) => sum + item.file.size, 0);
163
+
164
+ return (
165
+ <div className="space-y-4">
166
+ <div
167
+ className={`border-2 border-dashed rounded-lg p-6 text-center transition-colors duration-300 ${
168
+ isDragging ? "border-blue-600 bg-blue-50" : "border-gray-300 bg-gray-50"
169
+ }`}
170
+ onDragOver={handleDragOver}
171
+ onDragLeave={handleDragLeave}
172
+ onDrop={handleDrop}
173
+ >
174
+ <p className="font-semibold text-gray-800">
175
+ Drag & drop recordings here
176
+ </p>
177
+ <p className="text-sm text-gray-600 mt-1 mb-4">
178
+ Any common audio format (WAV, MP3, FLAC, OGG, WebM, M4A), up to{" "}
179
+ {API_CONFIG.MAX_FILE_SIZE / (1024 * 1024)}MB each.
180
+ </p>
181
+
182
+ <div className="flex flex-wrap items-center justify-center gap-3">
183
+ <button
184
+ type="button"
185
+ onClick={() => fileInputRef.current?.click()}
186
+ className={`${buttonClass} bg-white border border-gray-300 text-gray-800 hover:bg-gray-100`}
187
+ >
188
+ <Icon name="upload" />
189
+ Choose files
190
+ </button>
191
+
192
+ {recorder.state === "recording" ? (
193
+ <>
194
+ <button
195
+ type="button"
196
+ onClick={recorder.stop}
197
+ className={`${buttonClass} bg-red-600 text-white hover:bg-red-700`}
198
+ >
199
+ <Icon name="stop" />
200
+ Stop and add
201
+ </button>
202
+ <button
203
+ type="button"
204
+ onClick={recorder.discard}
205
+ className={`${buttonClass} bg-white border border-gray-300 text-gray-800 hover:bg-gray-100`}
206
+ >
207
+ Discard
208
+ </button>
209
+ </>
210
+ ) : (
211
+ <button
212
+ type="button"
213
+ onClick={recorder.start}
214
+ disabled={recorder.state === "requesting"}
215
+ className={`${buttonClass} bg-blue-600 text-white hover:bg-blue-700`}
216
+ >
217
+ <Icon name="microphone" />
218
+ {recorder.state === "requesting"
219
+ ? "Waiting for microphone..."
220
+ : "Record a clip"}
221
+ </button>
222
+ )}
223
+ </div>
224
+
225
+ {words.length > 1 && (
226
+ <div className="mt-4 flex flex-wrap items-center justify-center gap-2 text-sm">
227
+ <label htmlFor="pg-clip-word" className="text-gray-700">
228
+ Word in the next clip
229
+ </label>
230
+ <select
231
+ id="pg-clip-word"
232
+ value={recordWord}
233
+ onChange={(e) => setClipWord(e.target.value)}
234
+ disabled={recorder.state === "recording"}
235
+ className="px-2 py-1 border border-gray-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-600"
236
+ >
237
+ {words.map((word) => (
238
+ <option key={word} value={word}>
239
+ {word}
240
+ </option>
241
+ ))}
242
+ </select>
243
+ </div>
244
+ )}
245
+
246
+ {recorder.state === "recording" && (
247
+ <p
248
+ role="status"
249
+ className="mt-4 inline-flex items-center gap-2 text-sm font-semibold text-red-700"
250
+ >
251
+ <span
252
+ aria-hidden="true"
253
+ className="w-2.5 h-2.5 rounded-full bg-red-600 motion-safe:animate-pulse"
254
+ />
255
+ Recording {recordWord ? `"${recordWord}"` : "a clip"}
256
+ <span className="font-mono tabular-nums" aria-hidden="true">
257
+ {formatDuration(recorder.elapsed)}
258
+ </span>
259
+ </p>
260
+ )}
261
+
262
+ <input
263
+ ref={fileInputRef}
264
+ type="file"
265
+ accept="audio/*,.webm,.m4a,.opus"
266
+ multiple
267
+ onChange={handleFileChange}
268
+ className="hidden"
269
+ tabIndex={-1}
270
+ aria-label="Audio files"
271
+ />
272
+ </div>
273
+
274
+ {(error || recorder.error) && (
275
+ <p
276
+ role="alert"
277
+ className="p-3 rounded-lg bg-red-50 border border-red-200 text-sm text-red-700"
278
+ >
279
+ {error ?? recorder.error}
280
+ </p>
281
+ )}
282
+
283
+ <div className="rounded-lg border border-gray-200 bg-gray-50 p-3">
284
+ <label className="flex items-start gap-2 text-sm font-semibold text-gray-800">
285
+ <input
286
+ type="checkbox"
287
+ checked={asr}
288
+ onChange={(e) => onAsrChange(e.target.checked)}
289
+ aria-describedby="pg-asr-help"
290
+ className="mt-0.5 h-4 w-4 shrink-0 accent-blue-600"
291
+ />
292
+ Unscripted audio (podcast/interview): find the words automatically
293
+ </label>
294
+ <p id="pg-asr-help" className="mt-1 ml-6 text-sm text-gray-600">
295
+ Files without a transcript are transcribed by speech recognition to
296
+ find the target words. This is slower. To do this for a single file,
297
+ type “auto” as its transcript.
298
+ </p>
299
+ <label className="mt-3 ml-6 flex items-start gap-2 text-sm font-semibold text-gray-800">
300
+ <input
301
+ type="checkbox"
302
+ checked={diarize}
303
+ onChange={(e) => onDiarizeChange(e.target.checked)}
304
+ aria-describedby="pg-diarize-help"
305
+ className="mt-0.5 h-4 w-4 shrink-0 accent-blue-600"
306
+ />
307
+ Separate the speakers in each file
308
+ </label>
309
+ <p id="pg-diarize-help" className="mt-1 ml-12 text-sm text-gray-600">
310
+ A podcast has several voices. Each target word is credited to the
311
+ person who said it, so every speaker counts and the stability check
312
+ works. Applies to unscripted files with no speaker id; a file given a
313
+ speaker id counts as that one person.
314
+ </p>
315
+ {diarize && (
316
+ <label className="mt-2 ml-12 flex flex-wrap items-center gap-2 text-sm text-gray-700">
317
+ Number of speakers per file (if known)
318
+ <input
319
+ type="number"
320
+ min={1}
321
+ max={20}
322
+ inputMode="numeric"
323
+ value={numSpeakers}
324
+ onChange={(e) => onNumSpeakersChange(e.target.value)}
325
+ placeholder="estimate"
326
+ className="w-24 px-2 py-1 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-transparent"
327
+ />
328
+ </label>
329
+ )}
330
+ </div>
331
+
332
+ {words.length > 1 && !asr && (
333
+ <p className="text-sm text-gray-600">
334
+ With several target words, name each single-word file after its word
335
+ (e.g. <span className="font-mono">three-s01.wav</span>) or give it a
336
+ transcript, so the server knows which word it is.
337
+ </p>
338
+ )}
339
+
340
+ {items.length > 0 && (
341
+ <div className="space-y-2">
342
+ <div className="flex flex-wrap items-center justify-between gap-2">
343
+ <p className="text-sm font-semibold text-gray-700">
344
+ {items.length} recording{items.length === 1 ? "" : "s"} ·{" "}
345
+ {formatFileSize(totalSize)}
346
+ </p>
347
+ <button
348
+ type="button"
349
+ onClick={removeAll}
350
+ className="text-sm text-gray-700 underline hover:text-red-700 rounded focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500"
351
+ >
352
+ Remove all
353
+ </button>
354
+ </div>
355
+
356
+ <div
357
+ aria-hidden="true"
358
+ className={`hidden md:grid ${ROW_COLUMNS} px-3 text-xs font-semibold text-gray-600`}
359
+ >
360
+ <span />
361
+ <span>Recording</span>
362
+ <span className={FIELD_COLUMNS}>
363
+ <span>Speaker</span>
364
+ <span>Transcript (sentences, or “auto”)</span>
365
+ </span>
366
+ <span />
367
+ </div>
368
+
369
+ <ul className="space-y-2" aria-label="Recordings to analyse">
370
+ {items.map((item) => {
371
+ const transcript = item.transcript.trim();
372
+ // Mirror how the server reads each file, to flag the ones it would skip
373
+ const unmatched =
374
+ !asr &&
375
+ words.length > 1 &&
376
+ !transcript &&
377
+ !fileNameHasWord(item.file.name, words);
378
+ const wordMissing =
379
+ words.length > 0 &&
380
+ !!transcript &&
381
+ !isAutoTranscript(transcript) &&
382
+ !transcriptHasWord(transcript, words);
383
+ const isPlaying = player.playing === item.id;
384
+
385
+ return (
386
+ <li
387
+ key={item.id}
388
+ className="rounded-lg border border-gray-200 bg-white p-3"
389
+ >
390
+ <div className={ROW_COLUMNS}>
391
+ <button
392
+ type="button"
393
+ onClick={() =>
394
+ isPlaying ? player.stop() : player.play(item.id, item.file)
395
+ }
396
+ aria-label={`${isPlaying ? "Stop" : "Play"} ${item.file.name}`}
397
+ className="col-start-1 row-start-1 p-1 rounded text-blue-700 hover:bg-blue-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600"
398
+ >
399
+ <Icon name={isPlaying ? "stop" : "play"} className="w-6 h-6" />
400
+ </button>
401
+
402
+ <div className="col-start-2 row-start-1 min-w-0">
403
+ <p className="text-sm font-medium text-gray-900 break-all">
404
+ {item.file.name}
405
+ </p>
406
+ <p className="text-xs text-gray-600">
407
+ {item.origin === "recording" ? "Recorded here" : "Uploaded"}{" "}
408
+ · {formatFileSize(item.file.size)}
409
+ </p>
410
+ </div>
411
+
412
+ <div
413
+ className={`col-span-3 row-start-2 md:col-span-1 md:col-start-3 md:row-start-1 ${FIELD_COLUMNS}`}
414
+ >
415
+ <div>
416
+ <label
417
+ htmlFor={`pg-speaker-${item.id}`}
418
+ className="block text-xs font-semibold text-gray-700 mb-1 md:sr-only"
419
+ >
420
+ Speaker{" "}
421
+ <span className="font-normal text-gray-600">
422
+ (optional)
423
+ </span>
424
+ <span className="sr-only"> for {item.file.name}</span>
425
+ </label>
426
+ <input
427
+ id={`pg-speaker-${item.id}`}
428
+ type="text"
429
+ value={item.speaker}
430
+ onChange={(e) =>
431
+ updateItem(item.id, { speaker: e.target.value })
432
+ }
433
+ placeholder="e.g. S01"
434
+ className={fieldClass}
435
+ />
436
+ </div>
437
+ <div>
438
+ <label
439
+ htmlFor={`pg-transcript-${item.id}`}
440
+ className="block text-xs font-semibold text-gray-700 mb-1 md:sr-only"
441
+ >
442
+ Transcript{" "}
443
+ <span className="font-normal text-gray-600">
444
+ (sentences, or “auto”)
445
+ </span>
446
+ <span className="sr-only"> for {item.file.name}</span>
447
+ </label>
448
+ <input
449
+ id={`pg-transcript-${item.id}`}
450
+ type="text"
451
+ value={item.transcript}
452
+ onChange={(e) =>
453
+ updateItem(item.id, { transcript: e.target.value })
454
+ }
455
+ placeholder={
456
+ asr ? "found automatically" : "e.g. I think it will rain"
457
+ }
458
+ aria-describedby={
459
+ unmatched || wordMissing
460
+ ? `pg-recording-hint-${item.id}`
461
+ : undefined
462
+ }
463
+ className={fieldClass}
464
+ />
465
+ </div>
466
+ </div>
467
+
468
+ <button
469
+ type="button"
470
+ onClick={() => removeItem(item.id)}
471
+ aria-label={`Remove ${item.file.name}`}
472
+ className="col-start-3 row-start-1 md:col-start-4 p-1 rounded text-gray-600 hover:text-red-700 hover:bg-red-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500"
473
+ >
474
+ <Icon name="close" />
475
+ </button>
476
+ </div>
477
+
478
+ {(unmatched || wordMissing) && (
479
+ <p
480
+ id={`pg-recording-hint-${item.id}`}
481
+ className="mt-2 flex items-start gap-2 text-sm text-amber-800"
482
+ >
483
+ <Icon name="warning" className="w-4 h-4 mt-0.5 shrink-0" />
484
+ {unmatched
485
+ ? "No target word in the file name: add a transcript, or the server will skip this file."
486
+ : "The transcript does not contain a target word, so the server will skip this file."}
487
+ </p>
488
+ )}
489
+ </li>
490
+ );
491
+ })}
492
+ </ul>
493
+ </div>
494
+ )}
495
+ </div>
496
+ );
497
+ };
498
+
499
+ export default RecordingsInput;
VoxPreference-frontend/src/components/pg/TierBadge.tsx ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { tierLabel } from "../../utils/pg";
2
+
3
+ // From most to least formal; the label, not the colour, carries the meaning
4
+ const TIER_STYLES: Record<string, string> = {
5
+ "preferred (formal standard)": "bg-blue-100 text-blue-900",
6
+ "allophone (formal inventory)": "bg-gray-100 text-gray-800",
7
+ "outer (informal) norm": "bg-white text-gray-700 ring-1 ring-inset ring-gray-300",
8
+ };
9
+
10
+ const TierBadge = ({ tier }: { tier?: string }) => {
11
+ if (!tier) return null;
12
+ return (
13
+ <span
14
+ title={tier}
15
+ className={`inline-block rounded-full px-2 py-0.5 text-xs font-medium whitespace-nowrap ${
16
+ TIER_STYLES[tier] ?? "bg-gray-100 text-gray-800"
17
+ }`}
18
+ >
19
+ <span aria-hidden="true">{tierLabel(tier)}</span>
20
+ <span className="sr-only">Tier: {tier}</span>
21
+ </span>
22
+ );
23
+ };
24
+
25
+ export default TierBadge;
VoxPreference-frontend/src/components/pg/TokensTable.tsx ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from "react";
2
+ import useClipPlayer from "../../hooks/useClipPlayer";
3
+ import { PGToken } from "../../types/pg";
4
+ import Icon from "./Icon";
5
+
6
+ interface TokensTableProps {
7
+ tokens: PGToken[];
8
+ files: Map<string, File>;
9
+ reviewBelow: number;
10
+ }
11
+
12
+ const otherVariants = (token: PGToken) =>
13
+ Object.entries(token.scores)
14
+ .filter(([variant]) => variant !== token.variant)
15
+ .sort((a, b) => b[1] - a[1])
16
+ .slice(0, 2);
17
+
18
+ const headerClass =
19
+ "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";
20
+ const cellClass = "border-b border-gray-200 px-3 py-2";
21
+
22
+ const TokensTable = ({ tokens, files, reviewBelow }: TokensTableProps) => {
23
+ const [onlyReview, setOnlyReview] = useState(false);
24
+ const player = useClipPlayer();
25
+
26
+ // Play just the stretch of the recording the token was found in
27
+ const play = (index: number, token: PGToken) => {
28
+ const file = files.get(token.recording);
29
+ if (file) player.play(String(index), file, token.start, token.end);
30
+ };
31
+
32
+ const reviewCount = tokens.filter((token) => token.review).length;
33
+ const rows = tokens
34
+ .map((token, index) => ({ token, index }))
35
+ .filter(({ token }) => !onlyReview || token.review);
36
+
37
+ return (
38
+ <div className="space-y-3">
39
+ <div className="flex flex-wrap items-center justify-between gap-3">
40
+ <h3 className="text-xl font-semibold text-gray-900">Tokens</h3>
41
+ <label className="inline-flex items-center gap-2 text-sm text-gray-700">
42
+ <input
43
+ type="checkbox"
44
+ checked={onlyReview}
45
+ onChange={(e) => setOnlyReview(e.target.checked)}
46
+ disabled={reviewCount === 0}
47
+ className="h-4 w-4 accent-blue-600"
48
+ />
49
+ Only tokens to check by ear ({reviewCount})
50
+ </label>
51
+ </div>
52
+ <p className="text-sm text-gray-600">
53
+ Each row is one occurrence of the sound. Rows marked “check by ear”
54
+ have a posterior below {reviewBelow}: the model was unsure which
55
+ variant it heard, so listen and correct the data if needed.
56
+ </p>
57
+
58
+ <div className="max-h-[32rem] overflow-auto rounded-lg border border-gray-200">
59
+ <table className="min-w-full border-separate border-spacing-0 text-sm">
60
+ <caption className="sr-only">
61
+ Tokens of the sound under study, one per row
62
+ </caption>
63
+ <thead>
64
+ <tr>
65
+ <th scope="col" className={headerClass}>
66
+ <span className="sr-only">Listen</span>
67
+ </th>
68
+ <th scope="col" className={headerClass}>
69
+ Recording
70
+ </th>
71
+ <th scope="col" className={headerClass}>
72
+ Variant
73
+ </th>
74
+ <th scope="col" className={`${headerClass} text-right`}>
75
+ Posterior
76
+ </th>
77
+ <th scope="col" className={headerClass}>
78
+ Check
79
+ </th>
80
+ <th scope="col" className={headerClass}>
81
+ Next best
82
+ </th>
83
+ <th scope="col" className={headerClass}>
84
+ Word
85
+ </th>
86
+ <th scope="col" className={headerClass}>
87
+ Speaker
88
+ </th>
89
+ <th scope="col" className={headerClass}>
90
+ Time (s)
91
+ </th>
92
+ <th scope="col" className={headerClass}>
93
+ Realised
94
+ </th>
95
+ <th scope="col" className={headerClass}>
96
+ Heard
97
+ </th>
98
+ <th scope="col" className={headerClass}>
99
+ Sub-cluster
100
+ </th>
101
+ </tr>
102
+ </thead>
103
+ <tbody>
104
+ {rows.map(({ token, index }) => {
105
+ const isPlaying = player.playing === String(index);
106
+ const span = `${token.start.toFixed(2)}–${token.end.toFixed(2)}`;
107
+ return (
108
+ <tr
109
+ key={index}
110
+ className={token.review ? "bg-amber-50" : "bg-white"}
111
+ >
112
+ <td className={cellClass}>
113
+ <button
114
+ type="button"
115
+ onClick={() =>
116
+ isPlaying ? player.stop() : play(index, token)
117
+ }
118
+ disabled={!files.has(token.recording)}
119
+ aria-label={
120
+ isPlaying
121
+ ? "Stop playback"
122
+ : `Play "${token.word}" in ${token.recording}, ${span} seconds`
123
+ }
124
+ className="p-1 rounded text-blue-700 hover:bg-blue-100 disabled:opacity-40 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-600"
125
+ >
126
+ <Icon name={isPlaying ? "stop" : "play"} />
127
+ </button>
128
+ </td>
129
+ <td
130
+ className={`${cellClass} max-w-[14rem] truncate text-gray-900`}
131
+ title={token.recording}
132
+ >
133
+ {token.recording}
134
+ </td>
135
+ <td className={`${cellClass} font-ipa text-base text-gray-900`}>
136
+ [{token.variant}]
137
+ </td>
138
+ <td
139
+ className={`${cellClass} text-right tabular-nums text-gray-900`}
140
+ >
141
+ {token.posterior.toFixed(2)}
142
+ </td>
143
+ <td className={`${cellClass} whitespace-nowrap`}>
144
+ {token.review ? (
145
+ <span className="inline-flex items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 text-xs font-semibold text-amber-900">
146
+ <Icon name="ear" className="w-3.5 h-3.5" />
147
+ Check by ear
148
+ </span>
149
+ ) : (
150
+ <span className="text-xs text-gray-600">Confident</span>
151
+ )}
152
+ </td>
153
+ <td
154
+ className={`${cellClass} whitespace-nowrap text-xs text-gray-700`}
155
+ >
156
+ {otherVariants(token).map(([variant, score], i) => (
157
+ <span key={variant}>
158
+ {i > 0 && " · "}
159
+ <span className="font-ipa text-sm">[{variant}]</span>{" "}
160
+ <span className="tabular-nums">{score.toFixed(2)}</span>
161
+ </span>
162
+ ))}
163
+ </td>
164
+ <td className={`${cellClass} text-gray-800`}>{token.word}</td>
165
+ <td className={`${cellClass} text-gray-800`}>
166
+ {token.speaker}
167
+ </td>
168
+ <td
169
+ className={`${cellClass} tabular-nums whitespace-nowrap text-gray-800`}
170
+ >
171
+ {span}
172
+ </td>
173
+ <td
174
+ className={`${cellClass} whitespace-nowrap font-ipa text-base text-gray-900`}
175
+ >
176
+ {token.realised}
177
+ </td>
178
+ <td
179
+ className={`${cellClass} whitespace-nowrap font-ipa text-base text-gray-700`}
180
+ >
181
+ {token.heard}
182
+ </td>
183
+ <td className={`${cellClass} font-ipa text-gray-800`}>
184
+ {token.secondary}
185
+ </td>
186
+ </tr>
187
+ );
188
+ })}
189
+ </tbody>
190
+ </table>
191
+ </div>
192
+ </div>
193
+ );
194
+ };
195
+
196
+ export default TokensTable;
VoxPreference-frontend/src/components/pg/UnitSummary.tsx ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { PGUnit } from "../../types/pg";
2
+ import { formatPercent } from "../../utils/pg";
3
+ import ValidationBadge from "./ValidationBadge";
4
+
5
+ interface UnitSummaryProps {
6
+ unit?: PGUnit;
7
+ }
8
+
9
+ const UnitSummary = ({ unit }: UnitSummaryProps) => {
10
+ if (!unit) {
11
+ return (
12
+ <p className="text-sm text-gray-600">
13
+ The server will use the first unit whose reference sound occurs in
14
+ every target word.
15
+ </p>
16
+ );
17
+ }
18
+
19
+ const validation = unit.validation;
20
+ // The figures of the human-labelled test, where the server reports them
21
+ const figures = [
22
+ typeof validation?.accuracy === "number" &&
23
+ `accuracy ${formatPercent(validation.accuracy)}${
24
+ typeof validation.majority_baseline === "number"
25
+ ? ` (always guessing the commonest variant: ${formatPercent(
26
+ validation.majority_baseline
27
+ )})`
28
+ : ""
29
+ }`,
30
+ typeof validation?.balanced_accuracy === "number" &&
31
+ `balanced accuracy ${formatPercent(validation.balanced_accuracy)}`,
32
+ typeof validation?.share_error === "number" &&
33
+ `shares off by ${Math.round(
34
+ validation.share_error * 100
35
+ )} percentage points on average`,
36
+ ].filter(Boolean);
37
+
38
+ return (
39
+ <div className="rounded-lg border border-gray-200 bg-gray-50 p-4 text-sm space-y-3">
40
+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 items-baseline">
41
+ <dt className="text-gray-600">Reference sound</dt>
42
+ <dd className="font-ipa text-lg text-gray-900">/{unit.phoneme}/</dd>
43
+ <dt className="text-gray-600">Table label</dt>
44
+ <dd className="text-gray-900">{unit.label}</dd>
45
+ {unit.lexical_set && (
46
+ <>
47
+ <dt className="text-gray-600">Lexical set</dt>
48
+ <dd className="text-gray-900">{unit.lexical_set}</dd>
49
+ </>
50
+ )}
51
+ <dt className="text-gray-600">Classifier</dt>
52
+ <dd className="space-y-1 text-gray-900">
53
+ <ValidationBadge unit={unit} />
54
+ <p className="text-xs text-gray-700">
55
+ {validation?.note ||
56
+ "The server did not report a human-labelled test for this sound."}
57
+ </p>
58
+ {figures.length > 0 && (
59
+ <p className="text-xs text-gray-600">
60
+ Human-labelled test: {figures.join(" · ")}
61
+ {validation?.calibrated ? ", with calibration" : ""}.
62
+ </p>
63
+ )}
64
+ </dd>
65
+ </dl>
66
+
67
+ <div>
68
+ <p className="font-semibold text-gray-700">
69
+ Variants listened for in the audio
70
+ </p>
71
+ <ul className="mt-2 flex flex-wrap gap-2">
72
+ {unit.candidates.map((variant) => (
73
+ <li
74
+ key={variant}
75
+ className="inline-flex items-baseline gap-2 rounded-full border border-gray-300 bg-white px-3 py-1"
76
+ >
77
+ <span className="font-ipa text-base text-gray-900">
78
+ [{variant}]
79
+ </span>
80
+ {unit.international.includes(variant) && (
81
+ <span className="text-xs text-green-800">
82
+ internationally accepted
83
+ </span>
84
+ )}
85
+ {unit.pedagogic_difficult.includes(variant) && (
86
+ <span className="text-xs text-amber-800">hard to teach</span>
87
+ )}
88
+ </li>
89
+ ))}
90
+ </ul>
91
+ <p className="mt-2 text-xs text-gray-600">
92
+ Each token is assigned to whichever of these variants fits it best.
93
+ </p>
94
+ </div>
95
+
96
+ {unit.notes && <p className="text-gray-700">{unit.notes}</p>}
97
+ {unit.sources.length > 0 && (
98
+ <p className="text-xs text-gray-600">
99
+ Sources: {unit.sources.join("; ")}
100
+ </p>
101
+ )}
102
+ </div>
103
+ );
104
+ };
105
+
106
+ export default UnitSummary;
VoxPreference-frontend/src/components/pg/ValidationBadge.tsx ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { PGUnit } from "../../types/pg";
2
+ import { isValidated, validationLabel } from "../../utils/pg";
3
+
4
+ // Whether the classifier's labels for the unit passed a human-labelled test; the label,
5
+ // not the colour, carries the meaning
6
+ const ValidationBadge = ({ unit }: { unit: PGUnit }) => {
7
+ const validated = isValidated(unit);
8
+ return (
9
+ <span
10
+ title={unit.validation?.note || undefined}
11
+ className={`inline-block rounded-full px-2 py-0.5 text-xs font-medium whitespace-nowrap ${
12
+ validated
13
+ ? "bg-green-100 text-green-900"
14
+ : "bg-amber-100 text-amber-900 ring-1 ring-inset ring-amber-300"
15
+ }`}
16
+ >
17
+ <span className="sr-only">Classifier: </span>
18
+ {validationLabel(unit)}
19
+ </span>
20
+ );
21
+ };
22
+
23
+ export default ValidationBadge;
VoxPreference-frontend/src/config/api.ts ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // in a production build the backend serves this app, so the API is on the same address
2
+ const API_BASE_URL =
3
+ import.meta.env.VITE_API_BASE_URL ??
4
+ (import.meta.env.PROD ? "" : "http://localhost:3000");
5
+
6
+ export const API_ENDPOINTS = {
7
+ UPLOAD_AUDIO: `${API_BASE_URL}/transcribe`,
8
+ PG_UNITS: `${API_BASE_URL}/pg/units`,
9
+ PG_ANALYZE: `${API_BASE_URL}/pg/analyze`,
10
+ };
11
+
12
+ export const API_CONFIG = {
13
+ MAX_FILE_SIZE: 50 * 1024 * 1024, // 50MB
14
+ SUPPORTED_FILE_TYPES: [
15
+ "audio/wav",
16
+ "audio/mpeg",
17
+ "audio/mp3",
18
+ "audio/ogg",
19
+ "audio/flac",
20
+ ],
21
+ TIMEOUT: 5 * 60 * 1000, // 5 minutes in milliseconds
22
+ PG_ANALYZE_TIMEOUT: 30 * 60 * 1000, // 30 minutes: the phone model runs over every recording on CPU
23
+ };
VoxPreference-frontend/src/hooks/useAudioRecorder.ts ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useCallback, useEffect, useRef, useState } from "react";
2
+
3
+ type RecorderState = "idle" | "requesting" | "recording";
4
+
5
+ // Containers in order of preference; Safari only records audio/mp4
6
+ const MIME_TYPES = [
7
+ "audio/webm;codecs=opus",
8
+ "audio/webm",
9
+ "audio/ogg;codecs=opus",
10
+ "audio/mp4",
11
+ ];
12
+
13
+ export const isRecordingSupported = () =>
14
+ typeof window !== "undefined" &&
15
+ typeof MediaRecorder !== "undefined" &&
16
+ !!navigator.mediaDevices?.getUserMedia;
17
+
18
+ const useAudioRecorder = (onRecorded: (clip: Blob) => void) => {
19
+ const [state, setState] = useState<RecorderState>("idle");
20
+ const [elapsed, setElapsed] = useState(0);
21
+ const [error, setError] = useState<string | null>(null);
22
+ const recorderRef = useRef<MediaRecorder | null>(null);
23
+ const keepRef = useRef(true);
24
+ const mountedRef = useRef(false);
25
+ const onRecordedRef = useRef(onRecorded);
26
+
27
+ // Always call the latest callback, which sees the latest form state
28
+ useEffect(() => {
29
+ onRecordedRef.current = onRecorded;
30
+ });
31
+
32
+ const start = useCallback(async () => {
33
+ setError(null);
34
+ if (!isRecordingSupported()) {
35
+ setError(
36
+ "Recording is not available in this browser. It needs microphone support and a secure (https or localhost) connection."
37
+ );
38
+ return;
39
+ }
40
+
41
+ setState("requesting");
42
+ try {
43
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
44
+ // The permission prompt can outlive the component
45
+ if (!mountedRef.current) {
46
+ stream.getTracks().forEach((track) => track.stop());
47
+ return;
48
+ }
49
+ const mimeType = MIME_TYPES.find((type) =>
50
+ MediaRecorder.isTypeSupported(type)
51
+ );
52
+ const recorder = new MediaRecorder(
53
+ stream,
54
+ mimeType ? { mimeType } : undefined
55
+ );
56
+ const chunks: Blob[] = [];
57
+
58
+ recorder.ondataavailable = (event) => {
59
+ if (event.data.size > 0) chunks.push(event.data);
60
+ };
61
+ recorder.onstop = () => {
62
+ // Release the microphone so the browser stops showing it as in use
63
+ stream.getTracks().forEach((track) => track.stop());
64
+ recorderRef.current = null;
65
+ setState("idle");
66
+ if (keepRef.current && chunks.length) {
67
+ onRecordedRef.current(
68
+ new Blob(chunks, {
69
+ type: recorder.mimeType || mimeType || "audio/webm",
70
+ })
71
+ );
72
+ }
73
+ };
74
+
75
+ keepRef.current = true;
76
+ recorderRef.current = recorder;
77
+ recorder.start();
78
+ setElapsed(0);
79
+ setState("recording");
80
+ } catch (err) {
81
+ setState("idle");
82
+ setError(
83
+ err instanceof DOMException && err.name === "NotAllowedError"
84
+ ? "Microphone access was blocked. Allow it in your browser's site settings and try again."
85
+ : `Could not start recording: ${
86
+ err instanceof Error ? err.message : "unknown error"
87
+ }`
88
+ );
89
+ }
90
+ }, []);
91
+
92
+ const stop = useCallback(() => {
93
+ recorderRef.current?.stop();
94
+ }, []);
95
+
96
+ const discard = useCallback(() => {
97
+ keepRef.current = false;
98
+ recorderRef.current?.stop();
99
+ }, []);
100
+
101
+ useEffect(() => {
102
+ if (state !== "recording") return;
103
+ const startedAt = Date.now();
104
+ const timer = window.setInterval(
105
+ () => setElapsed((Date.now() - startedAt) / 1000),
106
+ 250
107
+ );
108
+ return () => window.clearInterval(timer);
109
+ }, [state]);
110
+
111
+ // Stop an unfinished recording if the component goes away
112
+ useEffect(() => {
113
+ mountedRef.current = true;
114
+ return () => {
115
+ mountedRef.current = false;
116
+ keepRef.current = false;
117
+ if (recorderRef.current?.state === "recording") {
118
+ recorderRef.current.stop();
119
+ }
120
+ };
121
+ }, []);
122
+
123
+ return { state, elapsed, error, start, stop, discard };
124
+ };
125
+
126
+ export default useAudioRecorder;
VoxPreference-frontend/src/hooks/useClipPlayer.ts ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useCallback, useEffect, useRef, useState } from "react";
2
+
3
+ // Plays one local clip at a time, optionally only the stretch from start to end (seconds)
4
+ const useClipPlayer = () => {
5
+ const [playing, setPlaying] = useState<string | null>(null);
6
+ const audioRef = useRef<HTMLAudioElement | null>(null);
7
+ const urlRef = useRef<string | null>(null);
8
+
9
+ const stop = useCallback(() => {
10
+ audioRef.current?.pause();
11
+ audioRef.current = null;
12
+ if (urlRef.current) URL.revokeObjectURL(urlRef.current);
13
+ urlRef.current = null;
14
+ setPlaying(null);
15
+ }, []);
16
+
17
+ // Release the audio when the component goes away
18
+ useEffect(() => stop, [stop]);
19
+
20
+ const play = useCallback(
21
+ (id: string, file: File, start = 0, end = Infinity) => {
22
+ stop();
23
+ const url = URL.createObjectURL(file);
24
+ const audio = new Audio(url);
25
+ urlRef.current = url;
26
+ audioRef.current = audio;
27
+
28
+ const finish = () => {
29
+ if (audioRef.current === audio) stop();
30
+ };
31
+ if (start > 0) {
32
+ // Before metadata loads this sets the start position; re-apply it once it has
33
+ audio.currentTime = start;
34
+ audio.addEventListener(
35
+ "loadedmetadata",
36
+ () => {
37
+ if (Math.abs(audio.currentTime - start) > 0.05) {
38
+ audio.currentTime = start;
39
+ }
40
+ },
41
+ { once: true }
42
+ );
43
+ }
44
+ if (Number.isFinite(end)) {
45
+ audio.addEventListener("timeupdate", () => {
46
+ if (audio.currentTime >= end) finish();
47
+ });
48
+ }
49
+ audio.addEventListener("ended", finish);
50
+ audio.addEventListener("error", finish);
51
+ audio.play().catch(finish);
52
+ setPlaying(id);
53
+ },
54
+ [stop]
55
+ );
56
+
57
+ return { playing, play, stop };
58
+ };
59
+
60
+ export default useClipPlayer;
VoxPreference-frontend/src/index.css ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @import "tailwindcss";
2
+
3
+ @theme {
4
+ /* Faces with full IPA coverage first, then system fonts that cover the common symbols */
5
+ --font-ipa: "Charis SIL", "Doulos SIL", "Gentium Plus", "Noto Sans",
6
+ "Segoe UI", "Lucida Grande", "DejaVu Sans", sans-serif;
7
+
8
+ --animate-indeterminate: indeterminate 1.6s ease-in-out infinite;
9
+
10
+ @keyframes indeterminate {
11
+ 0% {
12
+ transform: translateX(-100%);
13
+ }
14
+ 100% {
15
+ transform: translateX(300%);
16
+ }
17
+ }
18
+ }
VoxPreference-frontend/src/main.tsx ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import { StrictMode } from 'react'
2
+ import { createRoot } from 'react-dom/client'
3
+ import './index.css'
4
+ import App from './App.tsx'
5
+
6
+ createRoot(document.getElementById('root')!).render(
7
+ <StrictMode>
8
+ <App />
9
+ </StrictMode>,
10
+ )
VoxPreference-frontend/src/services/api.ts ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { API_ENDPOINTS, API_CONFIG } from "../config/api";
2
+ import { PGAnalysisResult, PGUnitsResponse } from "../types/pg";
3
+
4
+ interface ApiError extends Error {
5
+ status?: number;
6
+ statusText?: string;
7
+ data?: unknown;
8
+ isTimeout?: boolean;
9
+ }
10
+
11
+ class ApiService {
12
+ // Default timeout of 5 minutes if not specified in API_CONFIG
13
+ private static readonly DEFAULT_TIMEOUT = 5 * 60 * 1000;
14
+
15
+ private static async handleResponse(response: Response) {
16
+ if (!response.ok) {
17
+ const error: ApiError = new Error("API request failed");
18
+ error.status = response.status;
19
+ error.statusText = response.statusText;
20
+
21
+ try {
22
+ const contentType = response.headers.get("content-type");
23
+ if (contentType?.includes("application/json")) {
24
+ const errorData = await response.json();
25
+ error.data = errorData;
26
+ error.message =
27
+ errorData.message || errorData.error || "API request failed";
28
+ } else {
29
+ const text = await response.text();
30
+ if (text.includes("<!DOCTYPE")) {
31
+ error.message =
32
+ "Server error: Please check if the server is running and properly configured";
33
+ } else {
34
+ error.message = `Server error: ${response.status} ${response.statusText}`;
35
+ }
36
+ }
37
+ } catch (parseError) {
38
+ console.error("Error parsing response:", parseError);
39
+ error.message = `Server error: ${response.status} ${response.statusText}`;
40
+ }
41
+
42
+ throw error;
43
+ }
44
+
45
+ return response.json();
46
+ }
47
+
48
+ private static async fetchWithTimeout(
49
+ url: string,
50
+ options: RequestInit,
51
+ requestTimeout: number = API_CONFIG.TIMEOUT
52
+ ) {
53
+ const controller = new AbortController();
54
+ let timeoutId: number | undefined;
55
+
56
+ // Use default timeout if the requested timeout is not set or is unreasonable
57
+ const timeout =
58
+ typeof requestTimeout === "number" &&
59
+ requestTimeout > 0 &&
60
+ requestTimeout < 3600000
61
+ ? requestTimeout
62
+ : this.DEFAULT_TIMEOUT;
63
+
64
+ // Let a caller's signal (e.g. a cancel button) abort the request as well
65
+ const callerSignal = options.signal;
66
+ const abortFromCaller = () => controller.abort();
67
+ if (callerSignal?.aborted) {
68
+ controller.abort();
69
+ } else {
70
+ callerSignal?.addEventListener("abort", abortFromCaller);
71
+ }
72
+
73
+ // Create a promise that rejects after the timeout
74
+ const timeoutPromise = new Promise<never>((_, reject) => {
75
+ timeoutId = window.setTimeout(() => {
76
+ const timeoutError: ApiError = new Error(
77
+ `Request timed out after ${timeout}ms`
78
+ );
79
+ timeoutError.isTimeout = true;
80
+ reject(timeoutError);
81
+ controller.abort();
82
+ }, timeout);
83
+ });
84
+
85
+ try {
86
+ console.log(`Starting request to ${url} with timeout ${timeout}ms`);
87
+
88
+ // Race between the fetch and the timeout
89
+ const response = await Promise.race([
90
+ fetch(url, {
91
+ ...options,
92
+ signal: controller.signal,
93
+ headers: {
94
+ ...options.headers,
95
+ Accept: "application/json",
96
+ },
97
+ }),
98
+ timeoutPromise,
99
+ ]);
100
+
101
+ console.log(`Received response from ${url}`);
102
+ return this.handleResponse(response);
103
+ } catch (error) {
104
+ console.error("Request failed:", {
105
+ url,
106
+ timeout,
107
+ error:
108
+ error instanceof Error
109
+ ? {
110
+ name: error.name,
111
+ message: error.message,
112
+ isTimeout: (error as ApiError).isTimeout,
113
+ isAbortError:
114
+ error instanceof DOMException && error.name === "AbortError",
115
+ }
116
+ : "Unknown error",
117
+ });
118
+
119
+ if (error instanceof DOMException && error.name === "AbortError") {
120
+ if ((error as ApiError).isTimeout) {
121
+ throw new Error(`Request timed out after ${timeout}ms`);
122
+ }
123
+ throw new Error("Request was aborted");
124
+ }
125
+
126
+ if (error instanceof Error) {
127
+ throw error;
128
+ }
129
+
130
+ throw new Error("An unknown error occurred during the request");
131
+ } finally {
132
+ if (timeoutId !== undefined) {
133
+ window.clearTimeout(timeoutId);
134
+ }
135
+ callerSignal?.removeEventListener("abort", abortFromCaller);
136
+ }
137
+ }
138
+
139
+ static async uploadAudio(formData: FormData) {
140
+ const formDataFiles = formData.getAll("audioFile");
141
+
142
+ if (!formDataFiles.length) {
143
+ throw new Error("No audio files provided in FormData");
144
+ }
145
+
146
+ // Validate that all items are actually files and cast them
147
+ const files = formDataFiles.filter(
148
+ (file): file is File => file instanceof File
149
+ );
150
+ if (files.length !== formDataFiles.length) {
151
+ throw new Error("Invalid file data provided - all entries must be files");
152
+ }
153
+
154
+ console.log("Starting audio upload...", {
155
+ fileCount: files.length,
156
+ fileNames: files.map((f: File) => f.name),
157
+ totalSize: files.reduce((acc: number, f: File) => acc + f.size, 0),
158
+ timeout:
159
+ typeof API_CONFIG.TIMEOUT === "number"
160
+ ? API_CONFIG.TIMEOUT
161
+ : this.DEFAULT_TIMEOUT,
162
+ });
163
+
164
+ try {
165
+ const response = await this.fetchWithTimeout(API_ENDPOINTS.UPLOAD_AUDIO, {
166
+ method: "POST",
167
+ body: formData,
168
+ // Intentionally omitting Content-Type to let browser set it with boundary
169
+ });
170
+ console.log("Audio upload completed successfully");
171
+ return response;
172
+ } catch (error) {
173
+ console.error("Audio upload failed:", error);
174
+ throw error;
175
+ }
176
+ }
177
+
178
+ static async getPGUnits(): Promise<PGUnitsResponse> {
179
+ return this.fetchWithTimeout(API_ENDPOINTS.PG_UNITS, { method: "GET" });
180
+ }
181
+
182
+ static async analyzePG(
183
+ formData: FormData,
184
+ signal?: AbortSignal
185
+ ): Promise<PGAnalysisResult> {
186
+ const files = formData.getAll("files");
187
+
188
+ if (!files.length) {
189
+ throw new Error("No audio files provided in FormData");
190
+ }
191
+ if (!files.every((file) => file instanceof File)) {
192
+ throw new Error("Invalid file data provided - all entries must be files");
193
+ }
194
+
195
+ console.log("Starting PG analysis...", {
196
+ fileCount: files.length,
197
+ words: formData.get("words"),
198
+ unit: formData.get("unit"),
199
+ ranking: formData.get("ranking"),
200
+ timeout: API_CONFIG.PG_ANALYZE_TIMEOUT,
201
+ });
202
+
203
+ try {
204
+ const response = await this.fetchWithTimeout(
205
+ API_ENDPOINTS.PG_ANALYZE,
206
+ {
207
+ method: "POST",
208
+ body: formData,
209
+ signal,
210
+ // Intentionally omitting Content-Type to let browser set it with boundary
211
+ },
212
+ API_CONFIG.PG_ANALYZE_TIMEOUT
213
+ );
214
+ if (!response.success) {
215
+ throw new Error(response.error || "PG analysis failed");
216
+ }
217
+ console.log("PG analysis completed successfully");
218
+ return response;
219
+ } catch (error) {
220
+ console.error("PG analysis failed:", error);
221
+ throw error;
222
+ }
223
+ }
224
+ }
225
+
226
+ export default ApiService;
VoxPreference-frontend/src/types/pg.ts ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Shapes of the Preference Grammar (PG) endpoints, /pg/units and /pg/analyze
2
+
3
+ // Result of testing the variant classifier on human-labelled tokens of a unit
4
+ export interface PGValidation {
5
+ status: "validated" | "not validated";
6
+ kappa?: number; // Cohen's kappa against the human labels
7
+ accuracy?: number;
8
+ majority_baseline?: number; // accuracy of always guessing the commonest variant
9
+ balanced_accuracy?: number;
10
+ share_error?: number; // mean absolute error of the variant shares
11
+ calibrated?: boolean;
12
+ note: string;
13
+ }
14
+
15
+ export interface PGUnit {
16
+ key: string;
17
+ label: string; // as shown in the operability table, e.g. "<th>"
18
+ phoneme: string; // the reference segment, e.g. "θ"
19
+ candidates: string[]; // realisations tested for in the audio
20
+ international: string[]; // realisations within international norms (I-Ac)
21
+ pedagogic_difficult: string[]; // realisations marked as hard to teach (Ped-C)
22
+ lexical_set: string;
23
+ notes: string;
24
+ sources: string[];
25
+ validation?: PGValidation; // missing from older servers, which counts as not validated
26
+ }
27
+
28
+ export interface PGTenet {
29
+ key: string;
30
+ name: string;
31
+ }
32
+
33
+ export interface PGUnitsResponse {
34
+ units: Record<string, PGUnit>;
35
+ tenets: PGTenet[];
36
+ default_ranking: string;
37
+ }
38
+
39
+ export interface PGToken {
40
+ recording: string;
41
+ speaker: string;
42
+ word: string;
43
+ start: number;
44
+ end: number;
45
+ variant: string;
46
+ posterior: number;
47
+ scores: Record<string, number>;
48
+ realised: string; // best-fitting form of the whole word, in IPA
49
+ heard: string; // free phone decoding of the word
50
+ primary: string;
51
+ secondary: string;
52
+ review: boolean;
53
+ }
54
+
55
+ export interface PGClusters {
56
+ categories: string[];
57
+ contrast_matrix: number[][];
58
+ separation: Record<string, number | null>;
59
+ subclusters: Record<string, number>;
60
+ }
61
+
62
+ export interface PGViolation {
63
+ count: number;
64
+ reason: string;
65
+ source: string;
66
+ }
67
+
68
+ export interface PGCandidate {
69
+ form: string;
70
+ segment: string;
71
+ tokens: number;
72
+ share: number; // of tokens, or averaged over speakers when FreQ counts speakers
73
+ // "preferred (formal standard)" | "allophone (formal inventory)" | "outer (informal) norm"
74
+ tier?: string;
75
+ violations: Record<string, PGViolation>;
76
+ }
77
+
78
+ // A variant attested too rarely to compete (fewer than min_tokens tokens or min_speakers speakers)
79
+ export interface PGVariantCount {
80
+ form: string;
81
+ segment: string;
82
+ tokens: number;
83
+ share: number;
84
+ }
85
+
86
+ // How often each variant came out preferred when the speakers and each token's variant
87
+ // were resampled (bootstrap)
88
+ export interface PGStability {
89
+ resamples: number;
90
+ speakers: number;
91
+ preferred_rate: Record<string, number>; // segment -> share of resamples
92
+ }
93
+
94
+ // Tenet columns are keyed by their heading, e.g. "*No I-Ac", and hold the marks ("*", "*!")
95
+ export interface PGTableauRow {
96
+ candidate: string;
97
+ segment: string;
98
+ tokens: number;
99
+ share: number;
100
+ preferred: boolean;
101
+ [column: string]: string | number | boolean;
102
+ }
103
+
104
+ export interface PGTableau {
105
+ ranking: string[][];
106
+ rows: PGTableauRow[];
107
+ markdown: string;
108
+ html: string;
109
+ tie: boolean;
110
+ }
111
+
112
+ export interface PGAnalysisResult {
113
+ success: true;
114
+ words: string[];
115
+ unit: PGUnit;
116
+ canonical: Record<string, string>;
117
+ tokens: PGToken[];
118
+ clusters: PGClusters | null;
119
+ candidates: PGCandidate[];
120
+ superfluous?: PGVariantCount[];
121
+ tableau: PGTableau | null;
122
+ preferred: string[];
123
+ stability?: PGStability | null; // null with fewer than 3 speakers
124
+ warnings: string[];
125
+ files: Record<string, string>;
126
+ }
127
+
128
+ export type FreqWeighting = "tokens" | "speakers";
129
+
130
+ // "threshold": variants below the FreQ threshold get a mark; "most_frequent": every variant but the commonest does
131
+ export type FreqMode = "threshold" | "most_frequent";
132
+
133
+ export interface PGSettings {
134
+ freq_threshold?: number;
135
+ freq_weighting?: FreqWeighting;
136
+ freq_mode?: FreqMode;
137
+ min_tokens?: number;
138
+ min_speakers?: number;
139
+ disam_min_pairs?: number;
140
+ phos_world_threshold?: number;
141
+ review_below?: number;
142
+ calibrated?: boolean;
143
+ overrides?: Record<string, number>; // "<segment>|<tenet>" -> violation marks
144
+ }
145
+
146
+ // Every setting as used for a run, whether sent or left at its default
147
+ export type SettingsValues = Required<Omit<PGSettings, "overrides">>;
148
+
149
+ // Form state of the PG view
150
+
151
+ export interface RecordingItem {
152
+ id: string;
153
+ file: File;
154
+ origin: "upload" | "recording";
155
+ speaker: string;
156
+ transcript: string;
157
+ }
158
+
159
+ export interface SettingsForm {
160
+ freq_threshold: string;
161
+ freq_weighting: FreqWeighting;
162
+ freq_mode: FreqMode;
163
+ min_tokens: string;
164
+ min_speakers: string;
165
+ disam_min_pairs: string;
166
+ phos_world_threshold: string;
167
+ review_below: string;
168
+ calibrated: boolean;
169
+ }
170
+
171
+ export interface OverrideRow {
172
+ id: string;
173
+ segment: string;
174
+ tenet: string;
175
+ count: string;
176
+ }
177
+
178
+ export interface RankingItem {
179
+ key: string;
180
+ enabled: boolean;
181
+ tiedWithAbove: boolean; // unranked with the tenet listed above it (same stratum)
182
+ }
183
+
184
+ export interface AnalysisOutcome {
185
+ id: string;
186
+ data: PGAnalysisResult;
187
+ files: Map<string, File>; // the submitted recordings by name, for listening to tokens
188
+ settings: SettingsValues;
189
+ unlabelledRecordings: number; // recordings without a speaker id, which count as speakers of their own
190
+ }
VoxPreference-frontend/src/utils/pg.ts ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ OverrideRow,
3
+ PGSettings,
4
+ PGTableau,
5
+ PGTableauRow,
6
+ PGTenet,
7
+ PGUnit,
8
+ RankingItem,
9
+ SettingsForm,
10
+ SettingsValues,
11
+ } from "../types/pg";
12
+
13
+ // The six PG tenets in their default order; /pg/units sends the same list
14
+ export const PG_TENETS: PGTenet[] = [
15
+ { key: "I-Ac", name: "International acceptance" },
16
+ { key: "ContR", name: "Contrastiveness" },
17
+ { key: "FreQ", name: "Frequency" },
18
+ { key: "DisaM", name: "Disambiguity" },
19
+ { key: "Pho-S", name: "Phonetic simplicity" },
20
+ { key: "Ped-C", name: "Pedagogic convenience" },
21
+ ];
22
+
23
+ export const DEFAULT_RANKING =
24
+ "I-Ac >> ContR >> FreQ >> DisaM >> Pho-S >> Ped-C";
25
+
26
+ // Operability table headings, which are also the column keys of tableau.rows
27
+ export const TENET_COLUMN_LABELS: Record<string, string> = {
28
+ "I-Ac": "*No I-Ac",
29
+ ContR: "*No ContR",
30
+ FreQ: "*No FreQ",
31
+ DisaM: "DisaM",
32
+ "Pho-S": "*Pho-S",
33
+ "Ped-C": "*Ped-C",
34
+ };
35
+
36
+ // The server's defaults (pg/tenets.py Settings)
37
+ export const DEFAULT_SETTINGS: SettingsForm = {
38
+ freq_threshold: "0.2",
39
+ freq_weighting: "tokens",
40
+ freq_mode: "threshold",
41
+ min_tokens: "3",
42
+ min_speakers: "2",
43
+ disam_min_pairs: "1",
44
+ phos_world_threshold: "0.15",
45
+ review_below: "0.75",
46
+ calibrated: true,
47
+ };
48
+
49
+ // Short names for the output tiers, from most to least formal
50
+ const TIER_LABELS: Record<string, string> = {
51
+ "preferred (formal standard)": "Formal standard",
52
+ "allophone (formal inventory)": "Allophone",
53
+ "outer (informal) norm": "Informal norm",
54
+ };
55
+
56
+ export const tierLabel = (tier: string) => TIER_LABELS[tier] ?? tier;
57
+
58
+ // Classifier validation: a unit without a validation result (older servers) is not validated
59
+ export const isValidated = (unit: PGUnit) =>
60
+ unit.validation?.status === "validated";
61
+
62
+ export const validationLabel = (unit: PGUnit) => {
63
+ if (!isValidated(unit)) return "Not validated";
64
+ const kappa = unit.validation?.kappa;
65
+ return typeof kappa === "number"
66
+ ? `Validated (κ ${kappa.toFixed(2)})`
67
+ : "Validated";
68
+ };
69
+
70
+ let lastId = 0;
71
+ // crypto.randomUUID needs a secure context, so a counter keeps ids working over plain http
72
+ export const nextId = (prefix: string) => `${prefix}-${++lastId}`;
73
+
74
+ // Ranking: "A >> B, C" ranks A above the stratum {B, C}, whose tenets are unranked
75
+
76
+ export const parseRanking = (ranking: string): string[][] =>
77
+ ranking
78
+ .split(">>")
79
+ .map((stratum) =>
80
+ stratum
81
+ .split(",")
82
+ .map((tenet) => tenet.trim())
83
+ .filter(Boolean)
84
+ )
85
+ .filter((stratum) => stratum.length > 0);
86
+
87
+ export const rankingItemsFrom = (
88
+ ranking: string,
89
+ tenets: PGTenet[]
90
+ ): RankingItem[] => {
91
+ const known = new Set(tenets.map((tenet) => tenet.key));
92
+ const items: RankingItem[] = [];
93
+ for (const stratum of parseRanking(ranking)) {
94
+ stratum
95
+ .filter((key) => known.has(key) && !items.some((item) => item.key === key))
96
+ .forEach((key, i) =>
97
+ items.push({ key, enabled: true, tiedWithAbove: i > 0 })
98
+ );
99
+ }
100
+ // Tenets the ranking leaves out are deleted, but stay listed so they can be restored
101
+ for (const { key } of tenets) {
102
+ if (!items.some((item) => item.key === key)) {
103
+ items.push({ key, enabled: false, tiedWithAbove: false });
104
+ }
105
+ }
106
+ return items;
107
+ };
108
+
109
+ // Strata are worked out over the whole list, deleted tenets included, so deleting a
110
+ // tenet never merges the strata around it and restoring it is an exact undo
111
+ export const rankingStrata = (items: RankingItem[]): string[][] => {
112
+ const strata: RankingItem[][] = [];
113
+ items.forEach((item, i) => {
114
+ if (item.tiedWithAbove && i > 0) {
115
+ strata[strata.length - 1].push(item);
116
+ } else {
117
+ strata.push([item]);
118
+ }
119
+ });
120
+ return strata
121
+ .map((stratum) =>
122
+ stratum.filter((item) => item.enabled).map((item) => item.key)
123
+ )
124
+ .filter((stratum) => stratum.length > 0);
125
+ };
126
+
127
+ // Swap a tenet with its neighbour. Every tenet whose neighbour above changes is ranked
128
+ // strictly again, so a move never silently pulls a tenet into another stratum
129
+ export const moveRankingItem = (
130
+ items: RankingItem[],
131
+ index: number,
132
+ delta: -1 | 1
133
+ ): RankingItem[] | null => {
134
+ const target = index + delta;
135
+ if (target < 0 || target >= items.length) return null;
136
+ const next = [...items];
137
+ next[index] = items[target];
138
+ next[target] = items[index];
139
+ const below = Math.max(index, target) + 1;
140
+ return next.map((item, i) =>
141
+ i === index || i === target || i === below
142
+ ? { ...item, tiedWithAbove: false }
143
+ : item
144
+ );
145
+ };
146
+
147
+ export const formatRanking = (strata: string[][]): string =>
148
+ strata.map((stratum) => stratum.join(", ")).join(" >> ");
149
+
150
+ // Operability table
151
+
152
+ export interface TableauColumn {
153
+ key: string; // tenet key, e.g. "I-Ac"
154
+ label: string; // heading and row key, e.g. "*No I-Ac"
155
+ name: string;
156
+ stratum: number;
157
+ startsStratum: boolean;
158
+ }
159
+
160
+ export const tableauColumns = (
161
+ tableau: PGTableau,
162
+ tenets: PGTenet[]
163
+ ): TableauColumn[] =>
164
+ tableau.ranking.flatMap((stratum, s) =>
165
+ stratum.map((key, i) => ({
166
+ key,
167
+ label: TENET_COLUMN_LABELS[key] ?? key,
168
+ name: tenets.find((tenet) => tenet.key === key)?.name ?? key,
169
+ stratum: s,
170
+ startsStratum: i === 0,
171
+ }))
172
+ );
173
+
174
+ export const tableauCell = (row: PGTableauRow, column: TableauColumn) =>
175
+ String(row[column.label] ?? "");
176
+
177
+ // The stratum holding a candidate's fatal mark ("!"); cells in later strata are shaded
178
+ export const eliminatedAt = (
179
+ row: PGTableauRow,
180
+ columns: TableauColumn[]
181
+ ): number | null => {
182
+ const fatal = columns.find((column) =>
183
+ tableauCell(row, column).includes("!")
184
+ );
185
+ return fatal ? fatal.stratum : null;
186
+ };
187
+
188
+ export const describeMarks = (cell: string) => {
189
+ const count = (cell.match(/\*/g) ?? []).length;
190
+ const marks =
191
+ count === 0
192
+ ? "no violations"
193
+ : count === 1
194
+ ? "1 violation"
195
+ : `${count} violations`;
196
+ return cell.includes("!") ? `${marks}, fatal` : marks;
197
+ };
198
+
199
+ // Candidates are lettered a., b., c. as in PG operability tables
200
+ export const candidateLetter = (index: number) =>
201
+ String.fromCharCode(97 + index);
202
+
203
+ // Settings: only values that differ from the defaults are sent, so the server's own
204
+ // defaults apply otherwise and a renamed setting cannot break a request nobody customised
205
+
206
+ // Labels of the numeric settings, shared by the form and its error messages
207
+ export const SETTING_LABELS = {
208
+ freq_threshold: "FreQ threshold",
209
+ min_tokens: "Minimum tokens",
210
+ min_speakers: "Minimum speakers",
211
+ disam_min_pairs: "DisaM minimum pairs",
212
+ phos_world_threshold: "Pho-S: rare in the world's languages below",
213
+ review_below: "Review threshold",
214
+ } as const;
215
+
216
+ const NUMBER_SETTINGS = [
217
+ ["freq_threshold", "fraction"],
218
+ ["min_tokens", "count"],
219
+ ["min_speakers", "count"],
220
+ ["disam_min_pairs", "count"],
221
+ ["phos_world_threshold", "fraction"],
222
+ ["review_below", "fraction"],
223
+ ] as const;
224
+
225
+ export const buildSettings = (
226
+ form: SettingsForm,
227
+ overrides: OverrideRow[]
228
+ ):
229
+ | { settings: PGSettings; values: SettingsValues; error: null }
230
+ | { settings: null; values: null; error: string } => {
231
+ const settings: PGSettings = {};
232
+ const values: Partial<SettingsValues> = {
233
+ freq_weighting: form.freq_weighting,
234
+ freq_mode: form.freq_mode,
235
+ calibrated: form.calibrated,
236
+ };
237
+ for (const [field, kind] of NUMBER_SETTINGS) {
238
+ const label = `“${SETTING_LABELS[field]}”`;
239
+ const text = form[field].trim();
240
+ const value = Number(text);
241
+ const valid =
242
+ kind === "fraction"
243
+ ? Number.isFinite(value) && value >= 0 && value <= 1
244
+ : Number.isInteger(value) && value >= 0;
245
+ if (!text || !valid) {
246
+ return {
247
+ settings: null,
248
+ values: null,
249
+ error:
250
+ kind === "fraction"
251
+ ? `${label} must be a number from 0 to 1`
252
+ : `${label} must be a whole number (0 or more)`,
253
+ };
254
+ }
255
+ values[field] = value;
256
+ if (value !== Number(DEFAULT_SETTINGS[field])) settings[field] = value;
257
+ }
258
+ if (form.freq_weighting !== DEFAULT_SETTINGS.freq_weighting) {
259
+ settings.freq_weighting = form.freq_weighting;
260
+ }
261
+ if (form.freq_mode !== DEFAULT_SETTINGS.freq_mode) {
262
+ settings.freq_mode = form.freq_mode;
263
+ }
264
+ if (form.calibrated !== DEFAULT_SETTINGS.calibrated) {
265
+ settings.calibrated = form.calibrated;
266
+ }
267
+
268
+ const used = overrides.filter((row) => row.segment.trim());
269
+ for (const row of used) {
270
+ const count = Number(row.count);
271
+ if (!row.count.trim() || !Number.isInteger(count) || count < 0) {
272
+ return {
273
+ settings: null,
274
+ values: null,
275
+ error: `The override for [${row.segment.trim()}] needs a whole number of marks (0 or more)`,
276
+ };
277
+ }
278
+ }
279
+ if (used.length) {
280
+ settings.overrides = Object.fromEntries(
281
+ used.map((row) => [`${row.segment.trim()}|${row.tenet}`, Number(row.count)])
282
+ );
283
+ }
284
+ return { settings, values: values as SettingsValues, error: null };
285
+ };
286
+
287
+ // Words and recordings
288
+
289
+ // Commas or spaces separate words; the server lower-cases them too
290
+ export const parseWords = (input: string): string[] =>
291
+ Array.from(
292
+ new Set(
293
+ input
294
+ .split(/[\s,]+/)
295
+ .map((word) => word.trim().toLowerCase())
296
+ .filter(Boolean)
297
+ )
298
+ );
299
+
300
+ // With several target words the server matches a single-word recording to its word by file name
301
+ export const fileNameHasWord = (fileName: string, words: string[]) =>
302
+ words.some((word) => fileName.toLowerCase().includes(word));
303
+
304
+ // A transcript of "auto" asks the server to find the words by speech recognition
305
+ export const isAutoTranscript = (transcript: string) =>
306
+ transcript.trim().toLowerCase() === "auto";
307
+
308
+ // Mirrors the server's aligner, which keeps only letters a-z and apostrophes
309
+ export const transcriptHasWord = (transcript: string, words: string[]) => {
310
+ const spoken = transcript
311
+ .toLowerCase()
312
+ .replace(/’/g, "'")
313
+ .replace(/[^a-z' ]+/g, " ")
314
+ .split(" ");
315
+ return words.some((word) => spoken.includes(word));
316
+ };
317
+
318
+ const AUDIO_EXTENSIONS = /\.(wav|mp3|flac|ogg|oga|opus|webm|m4a|mp4|aac|aiff?)$/i;
319
+
320
+ export const isAudioFile = (file: File) =>
321
+ file.type.startsWith("audio/") || AUDIO_EXTENSIONS.test(file.name);
322
+
323
+ // Transcripts and speakers are keyed by file name on the server, so names must be unique
324
+ export const uniqueFileName = (name: string, taken: Set<string>) => {
325
+ if (!taken.has(name)) return name;
326
+ const dot = name.lastIndexOf(".");
327
+ const stem = dot > 0 ? name.slice(0, dot) : name;
328
+ const extension = dot > 0 ? name.slice(dot) : "";
329
+ const numbered = stem.match(/^(.*)-(\d+)$/);
330
+ const base = numbered ? numbered[1] : stem;
331
+ let n = numbered ? Number(numbered[2]) + 1 : 2;
332
+ while (taken.has(`${base}-${n}${extension}`)) n++;
333
+ return `${base}-${n}${extension}`;
334
+ };
335
+
336
+ export const extensionForMimeType = (type: string) => {
337
+ if (type.includes("ogg")) return "ogg";
338
+ if (type.includes("mp4") || type.includes("aac")) return "m4a";
339
+ if (type.includes("wav")) return "wav";
340
+ return "webm";
341
+ };
342
+
343
+ // Formatting
344
+
345
+ export const formatPercent = (share: number) => `${Math.round(share * 100)}%`;
346
+
347
+ export const formatDuration = (seconds: number) => {
348
+ const whole = Math.max(0, Math.floor(seconds));
349
+ return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}`;
350
+ };
351
+
352
+ export const formatFileSize = (bytes: number) =>
353
+ bytes < 1024 * 1024
354
+ ? `${Math.max(1, Math.round(bytes / 1024))} KB`
355
+ : `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
356
+
357
+ export const fileSlug = (text: string) =>
358
+ text
359
+ .toLowerCase()
360
+ .replace(/[^\p{L}\p{N}]+/gu, "-")
361
+ .replace(/^-+|-+$/g, "") || "analysis";
362
+
363
+ // Downloads
364
+
365
+ const BYTE_ORDER_MARK = String.fromCharCode(0xfeff);
366
+
367
+ const DOWNLOAD_TYPES: Record<string, string> = {
368
+ csv: "text/csv;charset=utf-8",
369
+ html: "text/html;charset=utf-8",
370
+ json: "application/json;charset=utf-8",
371
+ };
372
+
373
+ export const downloadText = (fileName: string, content: string) => {
374
+ const extension = fileName.split(".").pop() ?? "";
375
+ // A byte-order mark makes spreadsheet apps read the IPA in CSV files as UTF-8
376
+ const body = extension === "csv" ? `${BYTE_ORDER_MARK}${content}` : content;
377
+ const url = URL.createObjectURL(
378
+ new Blob([body], {
379
+ type: DOWNLOAD_TYPES[extension] ?? "text/plain;charset=utf-8",
380
+ })
381
+ );
382
+ const link = document.createElement("a");
383
+ link.href = url;
384
+ link.download = fileName;
385
+ document.body.appendChild(link);
386
+ link.click();
387
+ link.remove();
388
+ // Give the browser a moment to start the download before releasing the blob
389
+ window.setTimeout(() => URL.revokeObjectURL(url), 1000);
390
+ };
VoxPreference-frontend/src/vite-env.d.ts ADDED
@@ -0,0 +1 @@
 
 
1
+ /// <reference types="vite/client" />
VoxPreference-frontend/tsconfig.app.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
4
+ "target": "ES2020",
5
+ "useDefineForClassFields": true,
6
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
7
+ "module": "ESNext",
8
+ "skipLibCheck": true,
9
+
10
+ /* Bundler mode */
11
+ "moduleResolution": "bundler",
12
+ "allowImportingTsExtensions": true,
13
+ "isolatedModules": true,
14
+ "moduleDetection": "force",
15
+ "noEmit": true,
16
+ "jsx": "react-jsx",
17
+
18
+ /* Linting */
19
+ "strict": true,
20
+ "noUnusedLocals": true,
21
+ "noUnusedParameters": true,
22
+ "noFallthroughCasesInSwitch": true,
23
+ "noUncheckedSideEffectImports": true
24
+ },
25
+ "include": ["src"]
26
+ }
VoxPreference-frontend/tsconfig.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "files": [],
3
+ "references": [
4
+ { "path": "./tsconfig.app.json" },
5
+ { "path": "./tsconfig.node.json" }
6
+ ]
7
+ }
VoxPreference-frontend/tsconfig.node.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
4
+ "target": "ES2022",
5
+ "lib": ["ES2023"],
6
+ "module": "ESNext",
7
+ "skipLibCheck": true,
8
+
9
+ /* Bundler mode */
10
+ "moduleResolution": "bundler",
11
+ "allowImportingTsExtensions": true,
12
+ "isolatedModules": true,
13
+ "moduleDetection": "force",
14
+ "noEmit": true,
15
+
16
+ /* Linting */
17
+ "strict": true,
18
+ "noUnusedLocals": true,
19
+ "noUnusedParameters": true,
20
+ "noFallthroughCasesInSwitch": true,
21
+ "noUncheckedSideEffectImports": true
22
+ },
23
+ "include": ["vite.config.ts"]
24
+ }
VoxPreference-frontend/vite.config.ts ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import { defineConfig } from 'vite'
2
+ import react from '@vitejs/plugin-react'
3
+ import tailwindcss from '@tailwindcss/vite'
4
+
5
+ // https://vite.dev/config/
6
+ export default defineConfig({
7
+ plugins: [react(), tailwindcss()],
8
+ })
app.py DELETED
@@ -1,141 +0,0 @@
1
- from fastapi import FastAPI, File, UploadFile, Request, Form
2
- from fastapi.responses import JSONResponse
3
- from fastapi.middleware.cors import CORSMiddleware
4
- import io
5
- import librosa
6
- from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
7
- from text_to_ipa import convert_to_ipa
8
- import torch
9
- import os
10
- import logging
11
- import sys
12
- from typing import List
13
- import numpy as np
14
- import re
15
-
16
- os.environ["HF_HOME"] = "/app/hf_home"
17
-
18
-
19
- # Logging configuration
20
- LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
21
- logging.basicConfig(
22
- level=LOG_LEVEL,
23
- format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
24
- stream=sys.stdout
25
- )
26
- logger = logging.getLogger("voxpreference.app")
27
-
28
- logger.info("Starting Voxpreference FastAPI app...")
29
-
30
- app = FastAPI()
31
-
32
- app.add_middleware(
33
- CORSMiddleware,
34
- allow_origins=["*"],
35
- allow_credentials=True,
36
- allow_methods=["*"],
37
- allow_headers=["*"],
38
- )
39
-
40
- import os
41
- processor = Wav2Vec2Processor.from_pretrained("thebickersteth/wav2vec2-nigerian-english")
42
- model = Wav2Vec2ForCTC.from_pretrained("thebickersteth/wav2vec2-nigerian-english")
43
- # model.eval()
44
-
45
- @app.middleware("http")
46
- async def log_requests(request: Request, call_next):
47
- logger.info(f"Incoming request: {request.method} {request.url}")
48
- try:
49
- response = await call_next(request)
50
- logger.info(f"Response status: {response.status_code} for {request.method} {request.url}")
51
- return response
52
- except Exception as exc:
53
- logger.exception(f"Unhandled exception for {request.method} {request.url}")
54
- raise
55
-
56
- @app.get("/")
57
- def root():
58
- logger.info("Root endpoint called.")
59
- return {"message": "Welcome! This API is for transcription. Try /health or /transcribe."}
60
-
61
- @app.head("/")
62
- def root_head():
63
- logger.info("Root HEAD endpoint called.")
64
- return {"message": "Welcome! This API is for transcription. Try /health or /transcribe."}
65
-
66
- @app.get("/health")
67
- def health():
68
- logger.info("Health check endpoint called.")
69
- return {"status": "ok"}
70
-
71
- @app.post("/")
72
- async def transcribe(audioFile: UploadFile = File(...)):
73
- logger.info(f"Transcription endpoint called. Filename: {audioFile.filename}")
74
- try:
75
- audio_bytes = await audioFile.read()
76
- logger.debug(f"Read {len(audio_bytes)} bytes from uploaded file.")
77
- audio_input, sr = librosa.load(io.BytesIO(audio_bytes), sr=16000)
78
- logger.debug("Audio loaded and resampled to 16kHz.")
79
- duration = len(audio_input) / sr
80
- inputs = processor(audio_input, sampling_rate=16000, return_tensors="pt")
81
- logger.debug("Audio processed for model input.")
82
- with torch.no_grad():
83
- logits = model(inputs.input_values).logits
84
- predicted_ids = torch.argmax(logits, dim=-1)
85
- transcription = processor.batch_decode(predicted_ids.numpy())[0]
86
- logger.info(f"Transcription result: {transcription}")
87
- words = transcription.strip().split()
88
- n_words = len(words)
89
- segments = []
90
- if n_words > 0:
91
- word_duration = duration / n_words
92
- for i, word in enumerate(words):
93
- start = round(i * word_duration, 2)
94
- end = round((i + 1) * word_duration, 2)
95
- ipa_result = convert_to_ipa(word)
96
- ipa = ipa_result["ipa"] if ipa_result["success"] else None
97
- ipa_error = ipa_result["error"] if not ipa_result["success"] else None
98
- segments.append({
99
- "start": start,
100
- "end": end,
101
- "text": word,
102
- "ipa": ipa,
103
- "ipa_error": ipa_error
104
- })
105
- return JSONResponse(
106
- status_code=200,
107
- content={
108
- "success": True,
109
- "segments": segments,
110
- "transcription": transcription,
111
- "duration": duration
112
- }
113
- )
114
- except Exception as e:
115
- logger.exception(f"Error during transcription process: {e}")
116
- return JSONResponse(
117
- status_code=500,
118
- content={"success": False, "error": str(e)}
119
- )
120
-
121
- @app.post("/ipa")
122
- async def word_to_ipa(word: str = Form(...)):
123
- logger.info(f"IPA endpoint called for word: {word}")
124
- try:
125
- ipa_result = convert_to_ipa(word)
126
- ipa = ipa_result["ipa"] if ipa_result["success"] else None
127
- ipa_error = ipa_result["error"] if not ipa_result["success"] else None
128
- return JSONResponse(
129
- status_code=200,
130
- content={
131
- "success": ipa_result["success"],
132
- "ipa": ipa,
133
- "ipa_error": ipa_error
134
- }
135
- )
136
- except Exception as e:
137
- logger.exception(f"Error during IPA conversion: {e}")
138
- return JSONResponse(
139
- status_code=500,
140
- content={"success": False, "error": str(e)}
141
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
backend/.DS_Store ADDED
Binary file (6.15 kB). View file
 
backend/README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Voxpreference
3
+ emoji: 📈
4
+ colorFrom: indigo
5
+ colorTo: gray
6
+ sdk: docker
7
+ pinned: false
8
+ short_description: speech recognition using nigerian english
9
+ ---
10
+
11
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
backend/app.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import asdict
2
+ import threading
3
+ from typing import List, Optional
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ from fastapi import FastAPI, File, Form, UploadFile
8
+ from fastapi.responses import JSONResponse
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ from fastapi.staticfiles import StaticFiles
11
+ import io
12
+ import librosa
13
+ from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
14
+ from text_to_ipa import convert_to_ipa
15
+ import torch
16
+ from pg import audio as pg_audio
17
+ from pg.ot import DEFAULT_RANKING, TENET_NAMES, TENETS, parse_ranking
18
+ from pg.report import contrast_csv, html_report, subclusters_csv, tokens_csv
19
+ from pg.tenets import load_units, settings_from
20
+
21
+ app = FastAPI()
22
+
23
+ app.add_middleware(
24
+ CORSMiddleware,
25
+ allow_origins=["*"],
26
+ allow_credentials=True,
27
+ allow_methods=["*"],
28
+ allow_headers=["*"],
29
+ )
30
+
31
+ _asr = None
32
+
33
+
34
+ def get_asr():
35
+ global _asr
36
+ if _asr is None:
37
+ processor = Wav2Vec2Processor.from_pretrained("thebickersteth/wav2vec2-nigerian-english")
38
+ model = Wav2Vec2ForCTC.from_pretrained("thebickersteth/wav2vec2-nigerian-english").eval()
39
+ _asr = (processor, model)
40
+ return _asr
41
+
42
+ FRONTEND_DIST = Path(os.environ.get("FRONTEND_DIST", Path(__file__).resolve().parents[1] / "VoxPreference-frontend" / "dist"))
43
+
44
+
45
+ if not FRONTEND_DIST.is_dir():
46
+ @app.get("/")
47
+ def root():
48
+ return {"message": "Welcome! This API is for transcription. Try /health or /transcribe."}
49
+
50
+
51
+ @app.get("/health")
52
+ def health():
53
+ return {"status": "ok"}
54
+
55
+ @app.post("/transcribe")
56
+ async def transcribe(audioFile: UploadFile = File(...)):
57
+ try:
58
+ audio_bytes = await audioFile.read()
59
+ audio_input, _ = librosa.load(io.BytesIO(audio_bytes), sr=16000)
60
+ processor, model = get_asr()
61
+ inputs = processor(audio_input, sampling_rate=16000, return_tensors="pt")
62
+ with torch.no_grad():
63
+ logits = model(inputs.input_values).logits
64
+ predicted_ids = torch.argmax(logits, dim=-1)
65
+ transcription = processor.batch_decode(predicted_ids.numpy())[0]
66
+ ipa_result = convert_to_ipa(transcription)
67
+ ipa = ipa_result["ipa"] if ipa_result["success"] else None
68
+ ipa_error = ipa_result["error"] if not ipa_result["success"] else None
69
+ print(transcription, ipa, ipa_error)
70
+ return JSONResponse(
71
+ status_code=200,
72
+ content={
73
+ "success": True,
74
+ "transcription": transcription,
75
+ "ipa": ipa,
76
+ "ipa_error": ipa_error
77
+ }
78
+ )
79
+ except Exception as e:
80
+ return JSONResponse(
81
+ status_code=500,
82
+ content={"success": False, "error": str(e)}
83
+ )
84
+
85
+
86
+ _analyzer = None
87
+ # one analysis at a time: the models take ~2 GB and every analysis uses all CPU cores
88
+ _analysis_lock = threading.Lock()
89
+ MAX_FILES = 300
90
+ MAX_FILE_BYTES = 50 * 1024 * 1024
91
+
92
+
93
+ _analyzer_lock = threading.Lock()
94
+
95
+
96
+ def get_analyzer():
97
+ # the phone model is large, so it loads on the first PG request, or in the background at start-up
98
+ # when PG_WARM=1 (the Docker image sets it, so a woken Space is ready sooner)
99
+ global _analyzer
100
+ with _analyzer_lock:
101
+ if _analyzer is None:
102
+ from pg.pipeline import Analyzer
103
+ _analyzer = Analyzer()
104
+ return _analyzer
105
+
106
+
107
+ @app.on_event("startup")
108
+ def _warm_up():
109
+ if os.environ.get("PG_WARM") == "1":
110
+ threading.Thread(target=lambda: get_analyzer().aligner, daemon=True).start()
111
+
112
+
113
+ @app.get("/pg/units")
114
+ def pg_units():
115
+ return {
116
+ "units": {k: asdict(u) for k, u in load_units().items()},
117
+ "tenets": [{"key": t, "name": TENET_NAMES[t]} for t in TENETS],
118
+ "default_ranking": DEFAULT_RANKING,
119
+ }
120
+
121
+
122
+ @app.post("/pg/analyze")
123
+ def pg_analyze(
124
+ files: List[UploadFile] = File(...),
125
+ words: str = Form(...),
126
+ unit: Optional[str] = Form(None),
127
+ ranking: str = Form(DEFAULT_RANKING),
128
+ transcripts: Optional[str] = Form(None),
129
+ speakers: Optional[str] = Form(None),
130
+ settings: Optional[str] = Form(None),
131
+ asr: bool = Form(False),
132
+ diarize: bool = Form(True),
133
+ num_speakers: Optional[int] = Form(None),
134
+ ):
135
+ """files: recordings; words: comma-separated target words; transcripts/speakers: JSON objects
136
+ keyed by file name (omit transcripts for single-word recordings; "auto" or asr=true finds the
137
+ words in unscripted audio by speech recognition); diarize: separate the speakers inside unscripted
138
+ recordings that have no speaker id; num_speakers: how many talk in each, if known; settings: JSON
139
+ tenet thresholds."""
140
+ from pg.pipeline import Recording
141
+ try:
142
+ config = settings_from(json.loads(settings) if settings else None)
143
+ parse_ranking(ranking)
144
+ if len(files) > MAX_FILES:
145
+ raise ValueError(f"at most {MAX_FILES} recordings per analysis")
146
+ transcript_of = json.loads(transcripts) if transcripts else {}
147
+ speaker_of = json.loads(speakers) if speakers else {}
148
+ if num_speakers is not None and not 1 <= num_speakers <= 20:
149
+ raise ValueError("num_speakers must be between 1 and 20")
150
+ recordings = []
151
+ for f in files:
152
+ data = f.file.read(MAX_FILE_BYTES + 1)
153
+ if len(data) > MAX_FILE_BYTES:
154
+ raise ValueError(f"{f.filename} is larger than {MAX_FILE_BYTES // 2**20} MB")
155
+ try:
156
+ audio = pg_audio.load(data)
157
+ except RuntimeError as e:
158
+ raise ValueError(f"{f.filename}: {e}") from e
159
+ recordings.append(Recording(f.filename, audio, speaker=speaker_of.get(f.filename, ""),
160
+ transcript=transcript_of.get(f.filename, "auto" if asr else ""),
161
+ diarize=None if diarize else False, num_speakers=num_speakers))
162
+ with _analysis_lock:
163
+ result = get_analyzer().analyse(recordings, words.split(","), unit or None, ranking, config)
164
+ except (ValueError, KeyError) as e:
165
+ return JSONResponse(status_code=400, content={"success": False, "error": str(e).strip("'\"")})
166
+ except Exception as e:
167
+ return JSONResponse(status_code=500, content={"success": False, "error": str(e)})
168
+ body = result.to_dict()
169
+ body["success"] = True
170
+ body["files"] = {
171
+ "tokens.csv": tokens_csv(result),
172
+ "subclusters.csv": subclusters_csv(result),
173
+ "contrast_matrix.csv": contrast_csv(result),
174
+ "operability_table.csv": result.tableau.to_csv() if result.tableau else "",
175
+ "report.html": html_report(result),
176
+ }
177
+ return body
178
+
179
+
180
+ # the built frontend (npm run build) is served from the same address as the API, so one process is the whole app
181
+ if FRONTEND_DIST.is_dir():
182
+ app.mount("/", StaticFiles(directory=FRONTEND_DIST, html=True), name="frontend")
prepare_balanced_dataset.py → backend/eval/__init__.py RENAMED
File without changes
backend/eval/diarize_eval.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """How well speaker separation works, on made-up conversations whose speakers are known.
2
+
3
+ Utterances from different SLR70 Nigerian English speakers are joined into one recording in short turns
4
+ (1-3 utterances each, small pauses), as in a panel podcast. We then score how much of the speech is given to
5
+ the right speaker (after matching our anonymous labels to the true speakers) and whether the number of
6
+ speakers was found. Same-sex speakers are included, which is the harder case.
7
+
8
+ python -m eval.diarize_eval [--conversations 8] [--minutes 4]
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import random
15
+ from collections import defaultdict
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ from scipy.optimize import linear_sum_assignment
20
+
21
+ from pg.audio import load
22
+ from pg.diarize import Diarizer, cluster, speech_windows
23
+
24
+ SLR70 = Path(__file__).resolve().parents[1] / "data" / "work" / "slr70" / "wav"
25
+ SR = 16000
26
+
27
+
28
+ def by_speaker() -> dict[str, list[Path]]:
29
+ out = defaultdict(list)
30
+ for p in sorted(SLR70.glob("*.wav")):
31
+ out[p.stem.rsplit("_", 1)[0]].append(p)
32
+ return {s: ps for s, ps in out.items() if len(ps) >= 20}
33
+
34
+
35
+ def conversation(speakers: list[str], files: dict[str, list[Path]], seconds: float, rng: random.Random):
36
+ pieces, truth, t, last = [], [], 0.0, None
37
+ while t < seconds:
38
+ who = rng.choice([s for s in speakers if s != last] or speakers)
39
+ last = who
40
+ for _ in range(rng.randint(1, 3)):
41
+ audio = load(rng.choice(files[who]))
42
+ gap = np.zeros(int(rng.uniform(0.15, 0.6) * SR), dtype=np.float32)
43
+ pieces += [audio, gap]
44
+ truth.append((t, t + len(audio) / SR, who))
45
+ t += (len(audio) + len(gap)) / SR
46
+ return np.concatenate(pieces), truth
47
+
48
+
49
+ def score(truth, dia, step: float = 0.05) -> float:
50
+ """Share of speech time given to the right speaker, under the best one-to-one matching of labels."""
51
+ true_names = sorted({w for _, _, w in truth})
52
+ hyp_names = sorted({t.speaker for t in dia.turns}) or ["none"]
53
+ m = np.zeros((len(true_names), len(hyp_names)))
54
+ total = 0.0
55
+ for s, e, who in truth:
56
+ for x in np.arange(s, e, step):
57
+ got = dia.speaker_at(x, x + step, reach=0.0)
58
+ total += step
59
+ if got is not None:
60
+ m[true_names.index(who), hyp_names.index(got)] += step
61
+ r, c = linear_sum_assignment(-m)
62
+ return float(m[r, c].sum() / total)
63
+
64
+
65
+ def clip_score(truth, dia) -> tuple[float, float]:
66
+ """Share of clips (a sentence each) credited to the right speaker, the way a word inside it is credited,
67
+ under the best matching of labels; and the same for 0.4 s pieces from the middle of each clip."""
68
+ true_names = sorted({w for _, _, w in truth})
69
+ hyp = sorted({t.speaker for t in dia.turns}) or ["none"]
70
+ whole, piece = np.zeros((len(true_names), len(hyp))), np.zeros((len(true_names), len(hyp)))
71
+ for s, e, who in truth:
72
+ for m, (a, b) in ((whole, (s, e)), (piece, ((s + e) / 2 - 0.2, (s + e) / 2 + 0.2))):
73
+ got = dia.speaker_at(a, b)
74
+ if got is not None:
75
+ m[true_names.index(who), hyp.index(got)] += 1
76
+ out = []
77
+ for m in (whole, piece):
78
+ r, c = linear_sum_assignment(-m)
79
+ out.append(float(m[r, c].sum() / len(truth)))
80
+ return tuple(out)
81
+
82
+
83
+ def main():
84
+ ap = argparse.ArgumentParser()
85
+ ap.add_argument("--conversations", type=int, default=8)
86
+ ap.add_argument("--minutes", type=float, default=4)
87
+ ap.add_argument("--thresholds", default="0.8,0.9")
88
+ ap.add_argument("--seed", type=int, default=0, help="a new seed gives conversations not used for tuning")
89
+ ap.add_argument("--out", default="data/work/diarize_eval.json")
90
+ ap.add_argument("--model", default=None, help="speaker model (default: pg.diarize.SPEAKER_MODEL)")
91
+ args = ap.parse_args()
92
+ files = by_speaker()
93
+ rng = random.Random(args.seed)
94
+ diarizer = Diarizer(args.model) if args.model else Diarizer()
95
+ rows = []
96
+ for i in range(args.conversations):
97
+ n = [2, 3, 4, 5][i % 4]
98
+ speakers = rng.sample(sorted(files), n)
99
+ audio, truth = conversation(speakers, files, args.minutes * 60, rng)
100
+ windows = speech_windows(audio)
101
+ emb = diarizer.embed(audio, windows)
102
+ cache = Path(args.out).with_suffix("") / f"conv{i}.npz"
103
+ cache.parent.mkdir(parents=True, exist_ok=True)
104
+ np.savez(cache, emb=emb, windows=np.array(windows), truth=np.array(truth, dtype=object), speakers=speakers)
105
+ row = {"speakers": n, "ids": speakers, "seconds": round(len(audio) / SR)}
106
+ for th in [float(x) for x in args.thresholds.split(",")]:
107
+ d = cluster(windows, emb, None, th)
108
+ row[f"auto_{th}"] = {"found": d.speakers, "accuracy": round(score(truth, d), 3),
109
+ "word_level": round(clip_score(truth, d)[1], 3)}
110
+ d = cluster(windows, emb, n)
111
+ row["known_n"] = {"found": d.speakers, "accuracy": round(score(truth, d), 3),
112
+ "word_level": round(clip_score(truth, d)[1], 3)}
113
+ rows.append(row)
114
+ print(json.dumps(row), flush=True)
115
+ Path(args.out).write_text(json.dumps(rows, indent=1))
116
+ keys = [k for k in rows[0] if k.startswith("auto_") or k == "known_n"]
117
+ for k in keys:
118
+ acc = np.mean([r[k]["accuracy"] for r in rows])
119
+ right_n = np.mean([r[k]["found"] == r["speakers"] for r in rows])
120
+ word = np.mean([r[k]["word_level"] for r in rows])
121
+ print(f"{k}: words credited right {word:.3f}, speech time {acc:.3f}, right number of speakers in {right_n:.0%}")
122
+
123
+
124
+ if __name__ == "__main__":
125
+ main()