@adriansteffan/reactive 0.1.36 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.claude/settings.local.json +7 -1
  2. package/README.md +108 -5
  3. package/dist/{mod-urua6TFn.js → mod-CWKvMS7s.js} +11570 -11218
  4. package/dist/mod.d.ts +110 -6
  5. package/dist/reactive.es.js +74 -63
  6. package/dist/reactive.umd.js +626 -654
  7. package/dist/style.css +1 -1
  8. package/dist/{web-D9yqAhIx.js → web-DDyOXSFH.js} +1 -1
  9. package/dist/{web-BtWqed4E.js → web-DR-HR3ib.js} +1 -1
  10. package/package.json +4 -2
  11. package/raw-loader-hooks.mjs +25 -0
  12. package/raw-loader.mjs +5 -0
  13. package/src/components/experimentrunner.tsx +56 -2
  14. package/src/components/index.ts +1 -0
  15. package/src/components/microphonecheck.tsx +70 -84
  16. package/src/components/text.tsx +1 -1
  17. package/src/components/upload.tsx +4 -1
  18. package/src/components/voicerecorder.tsx +184 -162
  19. package/src/components/voicerecording.tsx +198 -0
  20. package/src/index.css +6 -0
  21. package/src/mod.tsx +8 -3
  22. package/src/utils/array.ts +61 -11
  23. package/src/utils/audiodevice.ts +4 -0
  24. package/src/utils/common.ts +3 -3
  25. package/src/utils/distributions.ts +28 -5
  26. package/src/utils/llm.ts +101 -0
  27. package/src/utils/nodecompat.ts +11 -0
  28. package/src/utils/simulation.ts +2 -2
  29. package/src/utils/theme.ts +1 -0
  30. package/src/utils/tts.ts +82 -0
  31. package/src/utils/upload.ts +54 -1
  32. package/template/README.md +26 -0
  33. package/template/backend/src/backend.ts +32 -1
  34. package/template/docker-compose.yaml +32 -0
  35. package/template/package.json +5 -2
  36. package/template/simulate.ts +13 -3
  37. package/template/src/Experiment.tsx +10 -12
  38. package/template/transcription/Dockerfile.cpu +8 -0
  39. package/template/transcription/Dockerfile.gpu +8 -0
  40. package/template/transcription/transcribe.py +161 -0
  41. package/vite.config.ts +1 -1
@@ -36,7 +36,7 @@ export function escapeCsvValue(value: any): string {
36
36
  return '';
37
37
  }
38
38
 
39
- const stringValue = String(value);
39
+ const stringValue = typeof value === 'object' ? JSON.stringify(value) : String(value);
40
40
 
41
41
  if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes('\n')) {
42
42
  const escapedValue = stringValue.replace(/"/g, '""');
@@ -187,6 +187,56 @@ function autoBuildCSVs(sessionID: string, data: any[], sessionData?: Record<stri
187
187
  return files;
188
188
  }
189
189
 
190
+ let audioFileIndex = 0;
191
+ export function generateAudioFilename(label: string): string {
192
+ return `audio_${label}_${audioFileIndex++}_${Date.now()}.webm`;
193
+ }
194
+
195
+ // Scans trial data for audio recordings (type: 'audiorecording' with data64),
196
+ // extracts them as separate .webm files, and replaces the binary data in-place
197
+ // with a filename reference. This keeps CSVs and raw JSON clean.
198
+ function extractAudioRecordings(data: any[]): FileUpload[] {
199
+ const files: FileUpload[] = [];
200
+
201
+ const processRecording = (obj: any, nameHint: string) => {
202
+ if (obj?.type === 'audiorecording') {
203
+ if (obj._audioPreUploaded && obj._audioPreUploadedFilename) {
204
+ // Already uploaded eagerly -> just record the filename reference
205
+ obj.audioFile = obj._audioPreUploadedFilename;
206
+ } else if (obj.data64) {
207
+ // Not pre-uploaded —> extract as a file for the final upload
208
+ const filename = generateAudioFilename(nameHint);
209
+ files.push({ filename, content: obj.data64, encoding: 'base64' });
210
+ obj.audioFile = filename;
211
+ }
212
+ delete obj.data64;
213
+ delete obj.blob;
214
+ delete obj.url;
215
+ delete obj._audioPreUploaded;
216
+ delete obj._audioPreUploadedFilename;
217
+ }
218
+ };
219
+
220
+ for (const item of data) {
221
+ const rd = item.responseData;
222
+ if (!rd || typeof rd !== 'object') continue;
223
+
224
+ // Direct responseData is an audio recording (VoiceRecording component)
225
+ processRecording(rd, item.name || item.type);
226
+
227
+ // Nested in responseData (Quest voicerecorder questions)
228
+ if (!Array.isArray(rd)) {
229
+ for (const [key, value] of Object.entries(rd)) {
230
+ if (value && typeof value === 'object') {
231
+ processRecording(value, `${item.name || item.type}_${key}`);
232
+ }
233
+ }
234
+ }
235
+ }
236
+
237
+ return files;
238
+ }
239
+
190
240
  export function buildUploadFiles(config: {
191
241
  sessionID: string;
192
242
  data: any[];
@@ -206,6 +256,9 @@ export function buildUploadFiles(config: {
206
256
 
207
257
  const files: FileUpload[] = generateFiles ? generateFiles(sessionID, data, store) : [];
208
258
 
259
+ // Extract audio recordings as separate files before serialization
260
+ files.push(...extractAudioRecordings(data));
261
+
209
262
  if (uploadRaw) {
210
263
  files.push({
211
264
  filename: `${sessionID}.raw.json`,
@@ -144,6 +144,32 @@ http://localhost:5173?hybridSimulation=true
144
144
  Trials with `simulators` or `simulate: true` defined will auto-advance. Others render normally for human interaction. Hybrid mode is enabled by default during development. For production, set `VITE_DISABLE_HYBRID_SIMULATION=true` to disable it.
145
145
 
146
146
 
147
+ ## Transcription
148
+
149
+ Automatically transcribe voice recordings from experiment data using Docker. Requires [Docker](https://docs.docker.com/engine/install/) to be installed.
150
+
151
+ ### CPU (faster-whisper)
152
+
153
+ ```
154
+ npm run transcribe
155
+ ```
156
+
157
+ ### GPU (qwen-asr, requires NVIDIA GPU)
158
+
159
+ ```
160
+ npm run transcribe:gpu
161
+ ```
162
+
163
+ ### Options
164
+
165
+ ```
166
+ npm run transcribe -- --overwrite # re-transcribe even if transcriptions.csv exists
167
+ npm run transcribe -- --model small # use a different model
168
+ ```
169
+
170
+ Output: `transcriptions.csv` in each participant's data directory with `filename,text` columns. The model is cached in a Docker volume, so it only downloads once.
171
+
172
+
147
173
  ## Target: Windows or MacOS
148
174
 
149
175
  ### Development
@@ -29,9 +29,23 @@ interface FileUpload {
29
29
 
30
30
  interface UploadRequest {
31
31
  sessionId: string;
32
+ _uploadId?: string;
32
33
  files: FileUpload[];
33
34
  }
34
35
 
36
+ async function getUniqueDirName(base: string): Promise<string> {
37
+ let candidate = base;
38
+ let counter = 0;
39
+ while (true) {
40
+ try {
41
+ await fs.access(path.join(backendFolder, candidate));
42
+ counter++;
43
+ candidate = `${base}_${counter}`;
44
+ } catch {
45
+ return candidate;
46
+ }
47
+ }
48
+ }
35
49
 
36
50
  api.post(
37
51
  '/data',
@@ -48,7 +62,24 @@ api.post(
48
62
  }
49
63
 
50
64
  const data = req.body as UploadRequest;
51
- const dataDir = path.join(backendFolder, data.sessionId);
65
+ let targetDir = data.sessionId;
66
+
67
+ // If _uploadId differs from sessionId and its folder exists, rename it
68
+ if (data._uploadId && data._uploadId !== data.sessionId) {
69
+ const uploadIdDir = path.join(backendFolder, data._uploadId);
70
+ try {
71
+ await fs.access(uploadIdDir);
72
+ // Folder from eager uploads exists; rename to final sessionId with collision avoidance
73
+ const uniqueName = await getUniqueDirName(data.sessionId);
74
+ await fs.rename(uploadIdDir, path.join(backendFolder, uniqueName));
75
+ targetDir = uniqueName;
76
+ } catch {
77
+ // No eager upload folder — use sessionId directly with collision avoidance
78
+ targetDir = await getUniqueDirName(data.sessionId);
79
+ }
80
+ }
81
+
82
+ const dataDir = path.join(backendFolder, targetDir);
52
83
  await fs.mkdir(dataDir, { recursive: true });
53
84
 
54
85
  const savePromises = data.files.map(async (file) => {
@@ -11,3 +11,35 @@ services:
11
11
  environment:
12
12
  - NODE_ENV=production
13
13
  - PORT=8001
14
+
15
+ transcribe:
16
+ profiles: ["transcribe"]
17
+ build:
18
+ context: ./transcription
19
+ dockerfile: Dockerfile.cpu
20
+ volumes:
21
+ - ./data:/data
22
+ - model-cache:/root/.cache/huggingface
23
+ environment:
24
+ - DATA_DIR=/data
25
+
26
+ transcribe-gpu:
27
+ profiles: ["transcribe-gpu"]
28
+ build:
29
+ context: ./transcription
30
+ dockerfile: Dockerfile.gpu
31
+ volumes:
32
+ - ./data:/data
33
+ - model-cache:/root/.cache/huggingface
34
+ environment:
35
+ - DATA_DIR=/data
36
+ deploy:
37
+ resources:
38
+ reservations:
39
+ devices:
40
+ - driver: nvidia
41
+ count: 1
42
+ capabilities: [gpu]
43
+
44
+ volumes:
45
+ model-cache:
@@ -47,7 +47,9 @@
47
47
  "dev": "vite",
48
48
  "backend": "npm run dev --prefix backend",
49
49
  "dev:all": "concurrently -n \"FRONT,BACK\" -c \"blue,green\" \"npm run dev\" \"npm run backend\"",
50
- "simulate": "npx tsx simulate.ts",
50
+ "simulate": "NODE_OPTIONS='--import tsx/esm --import @adriansteffan/reactive/raw-loader' node simulate.ts",
51
+ "transcribe": "docker compose run --rm transcribe",
52
+ "transcribe:gpu": "docker compose run --rm transcribe-gpu",
51
53
  "build": "tsc && vite build",
52
54
  "test": "vitest --silent=false",
53
55
  "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
@@ -72,7 +74,8 @@
72
74
  "react": "^18.2.0",
73
75
  "react-dom": "^18.2.0",
74
76
  "react-icons": "^5.1.0",
75
- "survey-react-ui": "^1.12.9"
77
+ "survey-react-ui": "^1.12.9",
78
+ "dotenv": "^16.4.7"
76
79
  },
77
80
  "devDependencies": {
78
81
  "@capacitor/cli": "^7.0.1",
@@ -1,5 +1,13 @@
1
+ import 'dotenv/config';
1
2
  import { orchestrateSimulation, simulateParticipant, setBackendUrl, seedDistributions } from '@adriansteffan/reactive';
2
3
 
4
+ function extractProps(ExperimentComponent: any) {
5
+ // Call the component function directly to get the ExperimentRunner element.
6
+ // This is safe because Experiment() just returns JSX — no hooks execute.
7
+ const element = ExperimentComponent();
8
+ return element.props;
9
+ }
10
+
3
11
  // Each simulated participant runs as a separate subprocess to get fresh module-level
4
12
  // randomization (e.g., group assignment). The orchestrator spawns workers that re-run
5
13
  // this script with _REACTIVE_WORKER_INDEX set.
@@ -13,7 +21,8 @@ if (process.env._REACTIVE_WORKER_INDEX) {
13
21
  if (seed) seedDistributions(parseInt(seed) + index);
14
22
  setBackendUrl(process.env._REACTIVE_BACKEND_URL!);
15
23
 
16
- const { experiment, simulationConfig } = await import('./src/Experiment');
24
+ const { default: Experiment } = await import('./src/Experiment');
25
+ const { timeline, simulationConfig } = extractProps(Experiment);
17
26
  const participants = simulationConfig.participants;
18
27
 
19
28
  let participant;
@@ -28,8 +37,9 @@ if (process.env._REACTIVE_WORKER_INDEX) {
28
37
  participant = participants.generator(index);
29
38
  }
30
39
 
31
- await simulateParticipant(experiment, participant);
40
+ await simulateParticipant(timeline, participant);
32
41
  } else {
33
- const { simulationConfig } = await import('./src/Experiment');
42
+ const { default: Experiment } = await import('./src/Experiment');
43
+ const { simulationConfig } = extractProps(Experiment);
34
44
  await orchestrateSimulation(simulationConfig, import.meta.filename);
35
45
  }
@@ -66,7 +66,7 @@ const CustomQuestion = () => {
66
66
 
67
67
  // --- Timeline ---
68
68
 
69
- export const experiment = [
69
+ const experiment = [
70
70
  {
71
71
  name: 'introtext',
72
72
  type: 'Text',
@@ -151,6 +151,14 @@ export const experiment = [
151
151
  },
152
152
  ];
153
153
 
154
+ // --- Simulation config ---
155
+ const simulationConfig = {
156
+ seed: 42,
157
+ participants: () => sampleParticipants('sobol', 10, {
158
+ needForCognition: { distribution: 'normal', mean: 3.5, sd: 0.8 },
159
+ }).map((p) => ({ ...p, nickname: `participant_${p.index}` })),
160
+ };
161
+
154
162
  export default function Experiment() {
155
163
  return (
156
164
  <ExperimentRunner
@@ -159,17 +167,7 @@ export default function Experiment() {
159
167
  components={{CustomTrial}}
160
168
  questions={{CustomQuestion}}
161
169
  hybridParticipant={{ id: 0, nickname: 'test' }}
170
+ simulationConfig={simulationConfig}
162
171
  />
163
172
  );
164
173
  }
165
-
166
- // --- Simulation config ---
167
- // Define how simulated participants are generated.
168
- // Use a factory function for participants: the framework seeds it with the base seed,
169
- // so every worker generates the same participant list regardless of its per-worker seed.
170
- export const simulationConfig = {
171
- seed: 42,
172
- participants: () => sampleParticipants('sobol', 10, {
173
- needForCognition: { distribution: 'normal', mean: 3.5, sd: 0.8 },
174
- }).map((p, i) => ({ ...p, id: i, nickname: `participant_${i}` })),
175
- };
@@ -0,0 +1,8 @@
1
+ FROM python:3.11-slim
2
+
3
+ RUN pip install --no-cache-dir faster-whisper tqdm
4
+
5
+ WORKDIR /app
6
+ COPY transcribe.py .
7
+
8
+ ENTRYPOINT ["python", "transcribe.py"]
@@ -0,0 +1,8 @@
1
+ FROM pytorch/pytorch:2.6.0-cuda12.6-cudnn9-runtime
2
+
3
+ RUN pip install --no-cache-dir qwen-asr tqdm
4
+
5
+ WORKDIR /app
6
+ COPY transcribe.py .
7
+
8
+ ENTRYPOINT ["python", "transcribe.py"]
@@ -0,0 +1,161 @@
1
+ #!/usr/bin/env python3
2
+ import csv
3
+ import os
4
+ import sys
5
+ import argparse
6
+
7
+
8
+ def find_participant_dirs(data_dir):
9
+ """Return participant directories that contain .webm audio files."""
10
+ dirs = []
11
+ for entry in sorted(os.listdir(data_dir)):
12
+ full = os.path.join(data_dir, entry)
13
+ if not os.path.isdir(full):
14
+ continue
15
+ if any(f.endswith(".webm") for f in os.listdir(full)):
16
+ dirs.append(full)
17
+ return dirs
18
+
19
+
20
+ def find_audio_files(participant_dir):
21
+ return sorted(
22
+ os.path.join(participant_dir, f)
23
+ for f in os.listdir(participant_dir)
24
+ if f.endswith(".webm")
25
+ )
26
+
27
+
28
+ def transcribe_faster_whisper(audio_files, model):
29
+ results = []
30
+ for path in audio_files:
31
+ print(f" transcribing: {os.path.basename(path)}")
32
+ segments, _ = model.transcribe(path, language="en")
33
+ text = " ".join(segment.text.strip() for segment in segments)
34
+ results.append((os.path.basename(path), text))
35
+ return results
36
+
37
+
38
+ def transcribe_qwen_asr(audio_files, model):
39
+ print(f" batching {len(audio_files)} file(s)")
40
+ out = model.transcribe(audio=audio_files)
41
+ results = []
42
+ for path, result in zip(audio_files, out):
43
+ results.append((os.path.basename(path), result.text.strip()))
44
+ return results
45
+
46
+
47
+ def write_csv(participant_dir, rows):
48
+ session_id = os.path.basename(participant_dir)
49
+ csv_path = os.path.join(participant_dir, f"transcriptions.{session_id}.csv")
50
+ with open(csv_path, "w", newline="") as f:
51
+ writer = csv.writer(f)
52
+ writer.writerow(["filename", "text"])
53
+ writer.writerows(rows)
54
+ print(f" wrote: {csv_path}")
55
+
56
+
57
+ def main():
58
+ parser = argparse.ArgumentParser(
59
+ description="Transcribe audio recordings from experiment data."
60
+ )
61
+ parser.add_argument(
62
+ "--data-dir",
63
+ default=os.environ.get("DATA_DIR", "/data"),
64
+ help="Path to data directory (default: /data or $DATA_DIR)",
65
+ )
66
+ parser.add_argument(
67
+ "--model",
68
+ default=None,
69
+ help="Override the model name (default depends on backend)",
70
+ )
71
+ parser.add_argument(
72
+ "--overwrite",
73
+ action="store_true",
74
+ help="Re-transcribe even if transcriptions.csv already exists",
75
+ )
76
+ parser.add_argument(
77
+ "--backend",
78
+ choices=["faster-whisper", "qwen-asr"],
79
+ default=None,
80
+ help="Force a specific backend (auto-detected if omitted)",
81
+ )
82
+ args = parser.parse_args()
83
+
84
+ if not os.path.isdir(args.data_dir):
85
+ print(f"Error: data directory not found: {args.data_dir}", file=sys.stderr)
86
+ sys.exit(1)
87
+
88
+ participant_dirs = find_participant_dirs(args.data_dir)
89
+ if not participant_dirs:
90
+ print("No participant directories with audio files found.")
91
+ sys.exit(0)
92
+
93
+ backend = args.backend
94
+ if backend is None:
95
+ try:
96
+ import faster_whisper # noqa: F401
97
+
98
+ backend = "faster-whisper"
99
+ except ImportError:
100
+ pass
101
+ if backend is None:
102
+ try:
103
+ import qwen_asr # noqa: F401
104
+
105
+ backend = "qwen-asr"
106
+ except ImportError:
107
+ pass
108
+ if backend is None:
109
+ print(
110
+ "Error: no backend available. Install faster-whisper or qwen-asr.",
111
+ file=sys.stderr,
112
+ )
113
+ sys.exit(1)
114
+
115
+ # Load model
116
+ if backend == "faster-whisper":
117
+ from faster_whisper import WhisperModel
118
+
119
+ model_name = args.model or "large-v3-turbo"
120
+ print(f"Loading faster-whisper model: {model_name} (int8, cpu)")
121
+ model = WhisperModel(model_name, device="cpu", compute_type="int8")
122
+ transcribe_fn = transcribe_faster_whisper
123
+ else:
124
+ import torch
125
+ from qwen_asr import Qwen3ASRModel
126
+
127
+ model_name = args.model or "Qwen/Qwen3-ASR-1.7B"
128
+ print(f"Loading Qwen3-ASR model: {model_name} (bfloat16, cuda)")
129
+ model = Qwen3ASRModel.from_pretrained(
130
+ model_name, dtype=torch.bfloat16, device_map="cuda:0"
131
+ )
132
+ transcribe_fn = transcribe_qwen_asr
133
+
134
+ print(f"Backend: {backend}")
135
+ print(f"Processing {len(participant_dirs)} participant(s)\n")
136
+
137
+ for pdir in participant_dirs:
138
+ participant_id = os.path.basename(pdir)
139
+
140
+ has_transcription = any(
141
+ f.startswith("transcriptions.") and f.endswith(".csv")
142
+ for f in os.listdir(pdir)
143
+ )
144
+ if has_transcription and not args.overwrite:
145
+ print(f"[{participant_id}] skip (transcription exists)")
146
+ continue
147
+
148
+ audio_files = find_audio_files(pdir)
149
+ if not audio_files:
150
+ print(f"[{participant_id}] no audio files")
151
+ continue
152
+
153
+ print(f"[{participant_id}] {len(audio_files)} file(s)")
154
+ rows = transcribe_fn(audio_files, model)
155
+ write_csv(pdir, rows)
156
+
157
+ print("\nDone.")
158
+
159
+
160
+ if __name__ == "__main__":
161
+ main()
package/vite.config.ts CHANGED
@@ -26,7 +26,7 @@ export default defineConfig(() => {
26
26
  fileName: (format: string) => `reactive.${format}.js`,
27
27
  },
28
28
  rollupOptions: {
29
- external: ['react', 'react-dom', 'child_process', 'os'],
29
+ external: ['react', 'react-dom', 'child_process', 'os', 'path', 'fs', 'module'],
30
30
  output: {
31
31
  globals: {
32
32
  react: 'React',