@adriansteffan/reactive 0.1.34 → 0.2.0
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.
- package/.claude/settings.local.json +7 -1
- package/README.md +108 -5
- package/dist/{mod-BpIlYaYt.js → mod-C-XUCKhQ.js} +11574 -11216
- package/dist/mod.d.ts +110 -6
- package/dist/reactive.es.js +74 -63
- package/dist/reactive.umd.js +626 -654
- package/dist/style.css +1 -1
- package/dist/{web-CoJYNnww.js → web-Dpb5MAUc.js} +1 -1
- package/dist/{web-CFP76jkq.js → web-Dv2PC8fG.js} +1 -1
- package/package.json +4 -2
- package/raw-loader-hooks.mjs +25 -0
- package/raw-loader.mjs +5 -0
- package/src/components/experimentrunner.tsx +54 -1
- package/src/components/index.ts +1 -0
- package/src/components/microphonecheck.tsx +70 -84
- package/src/components/text.tsx +1 -1
- package/src/components/upload.tsx +4 -1
- package/src/components/voicerecorder.tsx +184 -162
- package/src/components/voicerecording.tsx +198 -0
- package/src/index.css +6 -0
- package/src/mod.tsx +8 -3
- package/src/utils/array.ts +61 -11
- package/src/utils/audiodevice.ts +4 -0
- package/src/utils/distributions.ts +28 -5
- package/src/utils/llm.ts +101 -0
- package/src/utils/nodecompat.ts +11 -0
- package/src/utils/simulation.ts +2 -2
- package/src/utils/theme.ts +1 -0
- package/src/utils/tts.ts +82 -0
- package/src/utils/upload.ts +65 -5
- package/template/README.md +26 -0
- package/template/backend/src/backend.ts +32 -1
- package/template/docker-compose.yaml +32 -0
- package/template/package.json +5 -2
- package/template/simulate.ts +13 -3
- package/template/src/Experiment.tsx +10 -12
- package/template/transcription/Dockerfile.cpu +8 -0
- package/template/transcription/Dockerfile.gpu +8 -0
- package/template/transcription/transcribe.py +161 -0
- package/vite.config.ts +1 -1
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import React, { useState, useRef } from 'react';
|
|
2
|
+
import { BaseComponentProps } from '../utils/common';
|
|
3
|
+
import { VoiceRecorder, VoiceRecorderHandle } from './voicerecorder';
|
|
4
|
+
import { registerSimulation } from '../utils/simulation';
|
|
5
|
+
import { registerFlattener, generateAudioFilename } from '../utils/upload';
|
|
6
|
+
import { useTheme, t } from '../utils/theme';
|
|
7
|
+
import { HiExclamationTriangle } from 'react-icons/hi2';
|
|
8
|
+
import { textToWebmBase64, probeAudioDurationMs } from '../utils/tts';
|
|
9
|
+
import { post } from '../utils/request';
|
|
10
|
+
|
|
11
|
+
// 0.5s 440Hz sine tone, Opus codec; fallback when system TTS/ffmpeg unavailable
|
|
12
|
+
const DUMMY_AUDIO_BASE64 = 'GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQRChYECGFOAZwEAAAAAAARQEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHYTbuMU6uEElTDZ1OsggE/TbuMU6uEHFO7a1OsggQ67AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmsirXsYMPQkBNgI1MYXZmNTguNzYuMTAwV0GNTGF2ZjU4Ljc2LjEwMESJiEB/wAAAAAAAFlSua+KuAQAAAAAAAFnXgQFzxYhRMt5OPJYVP5yBACK1nIN1bmSGhkFfT1BVU1aqg2MuoFa7hATEtACDgQLhkZ+BAbWIQOdwAAAAAABiZIEQY6KTT3B1c0hlYWQBATgBgLsAAAAAABJUw2dAm3NzAQAAAAAAACdjwIBnyAEAAAAAAAAaRaOHRU5DT0RFUkSHjUxhdmY1OC43Ni4xMDBzcwEAAAAAAABgY8CLY8WIUTLeTjyWFT9nyAEAAAAAAAAjRaOHRU5DT0RFUkSHlkxhdmM1OC4xMzQuMTAwIGxpYm9wdXNnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjUwODAwMDAwMAAAH0O2dUJU54EAo5GBAACACINtgtAc/epJ/gE/wKOZgQAVgAinGl2KmC5fWspQj0PpJrkNsG40QKOVgQApgAihLxDkXfvcBBqwyPJFmpFgo5OBAD2ACKE40Hcyqlc9/1ttqV84o5SBAFGACKE40Hcyql5YIeRahOZfwKOXgQBlgAihTMA96uabsR453W080Xeb9h6jkYEAeYAIoTjQdzKqXDNU2kjGo5aBAI2ACKDZbPIJxX8xM7SEPNZetOMco5OBAKGACKE40Hcyqla9XawRHUWoo5OBALWACKE40Hcyqmb1XKO++uAQo5SBAMmACKEvEORd+8XekK1/rf/rrKOVgQDdgAihONB3MqpWRgIfsDV4YBUIo5OBAPGACKE40Hcyql5SyE1S2QFAo5SBAQWACKE40Hcyqla+8h2o+iaxgKOVgQEZgAihONB3MqpeqdUAtSaZmdKAo5OBAS2ACKFIA0bVUn3Jmsi7ollwo5OBAUGACKE40Hcyql6pt6b1uh3oo5WBAVWACKEvEORd+9/La7aeTKZnv/CjlYEBaYAIoTjO/AZGOE9OIX9kO96+gKOTgQF9gAihONB3MqpekAQ00UpCUKOTgQGRgAihSANG1VJz2oSiMZRZKqOQgQGlgAihONB3MqpeqbeK3KORgQG5gAihLxDkXfvfy2sJCQyjmoEBzYAIosXU/J/RyZHEovOUhd6Ypj7UPC8Bo5uBAeGACKRIuuxKsgM4Wle7xUaBZDTNWofASYGgAQAAAAAAABuhkoEB9QAIBkQ+QjevBKpbiF1qJHWihADN/mAcU7trkbuPs4EAt4r3gQHxggHg8IED';
|
|
13
|
+
|
|
14
|
+
export { DUMMY_AUDIO_BASE64 };
|
|
15
|
+
|
|
16
|
+
registerFlattener('VoiceRecording', 'session');
|
|
17
|
+
registerSimulation('VoiceRecording', async (_trialProps, _experimentState, simulators, participant) => {
|
|
18
|
+
const respond = simulators.respondTTS ?? simulators.respondBase64;
|
|
19
|
+
const result = await respond(_trialProps, participant);
|
|
20
|
+
const { participantState } = result;
|
|
21
|
+
|
|
22
|
+
let data64: string;
|
|
23
|
+
if (simulators.respondTTS) {
|
|
24
|
+
const text = result.value as string;
|
|
25
|
+
const ttsResult = await textToWebmBase64(text);
|
|
26
|
+
if (!ttsResult) throw new Error('TTS failed. Ensure say/espeak and ffmpeg are installed.');
|
|
27
|
+
data64 = ttsResult;
|
|
28
|
+
} else {
|
|
29
|
+
data64 = result.value as string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Exact duration via ffprobe, fall back to estimate from file size
|
|
33
|
+
const recordingDuration = (await probeAudioDurationMs(data64)) ?? Math.round(data64.length / 4);
|
|
34
|
+
return {
|
|
35
|
+
responseData: {
|
|
36
|
+
type: 'audiorecording',
|
|
37
|
+
data64,
|
|
38
|
+
timestamp: new Date().toISOString(),
|
|
39
|
+
recordingDuration,
|
|
40
|
+
},
|
|
41
|
+
participantState,
|
|
42
|
+
duration: recordingDuration,
|
|
43
|
+
};
|
|
44
|
+
}, {
|
|
45
|
+
/** Returns text to be spoken via platform TTS. Default: generic test sentence. */
|
|
46
|
+
respondTTS: (_input: any, participant: any) => ({
|
|
47
|
+
value: 'This is a simulated voice recording for testing purposes.',
|
|
48
|
+
participantState: participant,
|
|
49
|
+
}),
|
|
50
|
+
/** Returns raw base64-encoded WebM audio directly. Default: dummy 0.5s sine tone. */
|
|
51
|
+
respondBase64: (_input: any, participant: any) => ({
|
|
52
|
+
value: DUMMY_AUDIO_BASE64,
|
|
53
|
+
participantState: participant,
|
|
54
|
+
}),
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
function VoiceRecording({
|
|
58
|
+
content,
|
|
59
|
+
buttonText,
|
|
60
|
+
shortButtonText = 'Continue without improving',
|
|
61
|
+
className = '',
|
|
62
|
+
containerClass,
|
|
63
|
+
next,
|
|
64
|
+
store,
|
|
65
|
+
minDuration,
|
|
66
|
+
shortRecordingWarning,
|
|
67
|
+
showVisualizer = true,
|
|
68
|
+
eagerUpload = true,
|
|
69
|
+
animate = false,
|
|
70
|
+
name,
|
|
71
|
+
}: BaseComponentProps & {
|
|
72
|
+
content?: React.ReactNode;
|
|
73
|
+
buttonText?: string;
|
|
74
|
+
/** Button text when recording is shorter than minDuration. Defaults to buttonText. */
|
|
75
|
+
shortButtonText?: string;
|
|
76
|
+
className?: string;
|
|
77
|
+
containerClass?: string;
|
|
78
|
+
/** Minimum recording duration in ms. If shorter, a warning is shown when paused. */
|
|
79
|
+
minDuration?: number;
|
|
80
|
+
/** Custom warning text for short recordings. */
|
|
81
|
+
shortRecordingWarning?: React.ReactNode;
|
|
82
|
+
/** Show the volume level meter during recording. Default true. */
|
|
83
|
+
showVisualizer?: boolean;
|
|
84
|
+
/** Upload audio immediately after recording to reduce final upload size. Default true. */
|
|
85
|
+
eagerUpload?: boolean;
|
|
86
|
+
animate?: boolean;
|
|
87
|
+
name?: string;
|
|
88
|
+
}) {
|
|
89
|
+
const th = t(useTheme());
|
|
90
|
+
const resolvedButtonText = buttonText ?? (minDuration != null ? 'Save & Continue' : 'Continue');
|
|
91
|
+
const recorderRef = useRef<VoiceRecorderHandle>(null);
|
|
92
|
+
const pendingContinueRef = useRef(false);
|
|
93
|
+
|
|
94
|
+
const [recordingData, setRecordingData] = useState<object | null>(null);
|
|
95
|
+
const [paused, setPaused] = useState(false);
|
|
96
|
+
const [pausedDuration, setPausedDuration] = useState(0);
|
|
97
|
+
|
|
98
|
+
const isTooShort = minDuration != null && pausedDuration < minDuration;
|
|
99
|
+
|
|
100
|
+
const handleSave = (data: any) => {
|
|
101
|
+
// Eager upload: POST audio to backend immediately.
|
|
102
|
+
// Flag is only set after confirmed success.
|
|
103
|
+
// If the POST fails, the flag stays false and the final Upload handles it.
|
|
104
|
+
if (eagerUpload && data.data64 && store?._uploadId) {
|
|
105
|
+
const filename = generateAudioFilename(name ?? 'recording');
|
|
106
|
+
post('/data', {
|
|
107
|
+
sessionId: store._uploadId,
|
|
108
|
+
files: [{ filename, content: data.data64, encoding: 'base64' }],
|
|
109
|
+
}).then(() => {
|
|
110
|
+
data._audioPreUploaded = true;
|
|
111
|
+
data._audioPreUploadedFilename = filename;
|
|
112
|
+
}).catch(() => { /* ignore — final Upload handles it */ });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
setRecordingData(data);
|
|
116
|
+
setPaused(false);
|
|
117
|
+
if (pendingContinueRef.current) {
|
|
118
|
+
pendingContinueRef.current = false;
|
|
119
|
+
next(data);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const handlePause = (duration: number) => {
|
|
124
|
+
setPaused(true);
|
|
125
|
+
setPausedDuration(duration);
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const handleResume = () => {
|
|
129
|
+
setPaused(false);
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const finalize = () => {
|
|
133
|
+
pendingContinueRef.current = true;
|
|
134
|
+
recorderRef.current?.stop();
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
return (
|
|
138
|
+
<div className={`min-h-screen ${containerClass ?? th.containerBg}`}>
|
|
139
|
+
<div className={`max-w-prose mx-auto ${className} pt-20 pb-20 px-4 ${animate ? 'animate-fade-in opacity-0' : ''}`}>
|
|
140
|
+
{content && (
|
|
141
|
+
<article
|
|
142
|
+
className={`prose prose-2xl ${th.prose} text-xl ${th.proseLink} prose-a:underline prose-h1:text-4xl prose-h1:mb-10 prose-h1:font-bold prose-p:mb-4 prose-strong:font-bold ${th.text} leading-relaxed`}
|
|
143
|
+
>
|
|
144
|
+
{content}
|
|
145
|
+
</article>
|
|
146
|
+
)}
|
|
147
|
+
|
|
148
|
+
<div className='pt-6'>
|
|
149
|
+
<VoiceRecorder
|
|
150
|
+
ref={recorderRef}
|
|
151
|
+
handleSaveVoiceData={handleSave}
|
|
152
|
+
handleDiscardVoiceData={() => { setRecordingData(null); setPaused(false); }}
|
|
153
|
+
showStop={minDuration == null}
|
|
154
|
+
showDiscard={minDuration != null}
|
|
155
|
+
showVisualizer={showVisualizer}
|
|
156
|
+
onPause={handlePause}
|
|
157
|
+
onResume={handleResume}
|
|
158
|
+
/>
|
|
159
|
+
</div>
|
|
160
|
+
|
|
161
|
+
{paused && isTooShort && (
|
|
162
|
+
<div className={`mt-8 flex items-start space-x-3 p-4 border-2 ${th.buttonBorder} ${th.text} ${animate ? 'animate-fade-in opacity-0' : ''}`}>
|
|
163
|
+
<HiExclamationTriangle className='w-6 h-6 text-yellow-500 flex-shrink-0 mt-0.5' />
|
|
164
|
+
<p className='text-sm'>
|
|
165
|
+
{shortRecordingWarning ?? 'Your recording seems quite short. Please consider adding more detail to your description.'}
|
|
166
|
+
</p>
|
|
167
|
+
</div>
|
|
168
|
+
)}
|
|
169
|
+
|
|
170
|
+
{/* Continue button (visible when paused, minDuration mode only) */}
|
|
171
|
+
{paused && minDuration != null && (
|
|
172
|
+
<div className={`mt-8 flex justify-center ${animate ? 'animate-fade-in opacity-0' : ''}`}>
|
|
173
|
+
<button
|
|
174
|
+
onClick={finalize}
|
|
175
|
+
className={`${th.buttonBg} cursor-pointer px-8 py-3 border-2 ${th.buttonBorder} font-bold ${th.buttonText} text-lg rounded-xl ${th.buttonShadow} hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-none`}
|
|
176
|
+
>
|
|
177
|
+
{isTooShort ? shortButtonText : resolvedButtonText}
|
|
178
|
+
</button>
|
|
179
|
+
</div>
|
|
180
|
+
)}
|
|
181
|
+
|
|
182
|
+
{/* Continue button after recording is stopped (non-minDuration mode) */}
|
|
183
|
+
{recordingData && !paused && (
|
|
184
|
+
<div className={`mt-16 flex justify-center ${animate ? 'animate-fade-in opacity-0' : ''}`}>
|
|
185
|
+
<button
|
|
186
|
+
onClick={() => next(recordingData)}
|
|
187
|
+
className={`${th.buttonBg} cursor-pointer px-8 py-3 border-2 ${th.buttonBorder} font-bold ${th.buttonText} text-lg rounded-xl ${th.buttonShadow} hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-none`}
|
|
188
|
+
>
|
|
189
|
+
{resolvedButtonText}
|
|
190
|
+
</button>
|
|
191
|
+
</div>
|
|
192
|
+
)}
|
|
193
|
+
</div>
|
|
194
|
+
</div>
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export default VoiceRecording;
|
package/src/index.css
CHANGED
|
@@ -85,6 +85,12 @@
|
|
|
85
85
|
font-style: italic;
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
+
.reactive-light-dot-bg {
|
|
89
|
+
background-color: white;
|
|
90
|
+
background-image: radial-gradient(#e5e7eb 1px, transparent 1px);
|
|
91
|
+
background-size: 16px 16px;
|
|
92
|
+
}
|
|
93
|
+
|
|
88
94
|
.reactive-dark-bg-plain {
|
|
89
95
|
background-color: #21294b;
|
|
90
96
|
}
|
package/src/mod.tsx
CHANGED
|
@@ -6,10 +6,15 @@ export * from './utils/array';
|
|
|
6
6
|
export * from './utils/common';
|
|
7
7
|
export * from './utils/simulation';
|
|
8
8
|
export { registerFlattener, arrayFlattener } from './utils/upload';
|
|
9
|
-
export { normal, poisson, uniform, seedDistributions, sobol, halton, sampleParticipants } from './utils/distributions';
|
|
10
|
-
export { useTheme, ThemeContext, THEME, t, DARK_BG_CLASS, DARK_BG_PLAIN_CLASS } from './utils/theme';
|
|
9
|
+
export { normal, poisson, uniform, seedDistributions, sobol, halton, sampleParticipants, draw } from './utils/distributions';
|
|
10
|
+
export { useTheme, ThemeContext, THEME, t, LIGHT_DOT_BG_CLASS, DARK_BG_CLASS, DARK_BG_PLAIN_CLASS } from './utils/theme';
|
|
11
|
+
export { AudioDeviceContext, useAudioDeviceId } from './utils/audiodevice';
|
|
12
|
+
export { textToWebmBase64, probeAudioDurationMs } from './utils/tts';
|
|
13
|
+
export { DUMMY_AUDIO_BASE64 } from './components/voicerecording';
|
|
14
|
+
export { invokeLLM } from './utils/llm';
|
|
15
|
+
export type { LLMConfig, LLMSchema } from './utils/llm';
|
|
11
16
|
export type { Theme } from './utils/theme';
|
|
12
|
-
export type { DimensionSpec, UniformSpec, NormalSpec, PoissonSpec, SamplingMethod } from './utils/distributions';
|
|
17
|
+
export type { DimensionSpec, UniformSpec, NormalSpec, PoissonSpec, IntegerSpec, DiscreteSpec, SamplingMethod } from './utils/distributions';
|
|
13
18
|
export { simulateDDMTrial, mapDDMChoice } from './utils/ddm';
|
|
14
19
|
export type { DDMTrialParams, DDMTrialResult, ParameterDef, NormalDist, UniformDist, BoundaryDef, CollapseDef, PostStimStrategyDef, ContinueStrategy, CollapseStrategy, SnapshotStrategy } from './utils/ddm';
|
|
15
20
|
export * from './components';
|
package/src/utils/array.ts
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
import { uniform } from './distributions';
|
|
2
2
|
|
|
3
|
+
interface SampleOptions {
|
|
4
|
+
replace?: boolean;
|
|
5
|
+
}
|
|
6
|
+
|
|
3
7
|
declare global {
|
|
4
8
|
interface Array<T> {
|
|
5
9
|
/**
|
|
6
10
|
* Returns random elements from the array
|
|
7
11
|
* @param n Number of random elements to return (defaults to 1)
|
|
12
|
+
* @param options Options object with `replace` (default: true)
|
|
8
13
|
*/
|
|
9
|
-
sample(n?: number): Array<T>;
|
|
14
|
+
sample(n?: number, options?: SampleOptions): Array<T>;
|
|
10
15
|
|
|
11
16
|
/**
|
|
12
17
|
* Shuffles array elements using Fisher-Yates algorithm
|
|
@@ -24,24 +29,42 @@ declare global {
|
|
|
24
29
|
* @param n Number of chunks to create
|
|
25
30
|
*/
|
|
26
31
|
chunk(n: number): Array<Array<T>>;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Returns the arithmetic mean of the array
|
|
35
|
+
*/
|
|
36
|
+
mean(): number;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Returns the sum of the array
|
|
40
|
+
*/
|
|
41
|
+
sum(): number;
|
|
27
42
|
}
|
|
28
43
|
}
|
|
29
44
|
|
|
30
45
|
/**
|
|
31
46
|
* Returns random elements from an array
|
|
32
47
|
*/
|
|
33
|
-
export function sample<T>(array: T[], n: number = 1): T[] {
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
48
|
+
export function sample<T>(array: T[], n: number = 1, options: SampleOptions = {}): T[] {
|
|
49
|
+
const { replace = true } = options;
|
|
50
|
+
if (array.length === 0) return [];
|
|
51
|
+
|
|
52
|
+
if (replace) {
|
|
53
|
+
const result: T[] = [];
|
|
54
|
+
for (let i = 0; i < n; i++) {
|
|
55
|
+
const randomIndex = Math.floor(uniform(0, 1) * array.length);
|
|
56
|
+
result.push(array[randomIndex]);
|
|
57
|
+
}
|
|
37
58
|
return result;
|
|
38
59
|
}
|
|
39
|
-
|
|
60
|
+
|
|
61
|
+
// Without replacement, cycling when n > array.length
|
|
62
|
+
const result: T[] = [];
|
|
63
|
+
let pool: T[] = [];
|
|
40
64
|
for (let i = 0; i < n; i++) {
|
|
41
|
-
|
|
42
|
-
result.push(
|
|
65
|
+
if (pool.length === 0) pool = shuffle(array);
|
|
66
|
+
result.push(pool.pop()!);
|
|
43
67
|
}
|
|
44
|
-
|
|
45
68
|
return result;
|
|
46
69
|
}
|
|
47
70
|
|
|
@@ -75,6 +98,21 @@ export function chunk<T>(array: T[], n: number): T[][] {
|
|
|
75
98
|
);
|
|
76
99
|
}
|
|
77
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Returns the arithmetic mean of a number array
|
|
103
|
+
*/
|
|
104
|
+
export function mean(array: number[]): number {
|
|
105
|
+
if (array.length === 0) return 0;
|
|
106
|
+
return array.reduce((a, b) => a + b, 0) / array.length;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Returns the sum of a number array
|
|
111
|
+
*/
|
|
112
|
+
export function sum(array: number[]): number {
|
|
113
|
+
return array.reduce((a, b) => a + b, 0);
|
|
114
|
+
}
|
|
115
|
+
|
|
78
116
|
/**
|
|
79
117
|
* Registers array methods on the Array prototype.
|
|
80
118
|
* Call this function once to make array methods available globally.
|
|
@@ -90,8 +128,8 @@ export function chunk<T>(array: T[], n: number): T[][] {
|
|
|
90
128
|
*/
|
|
91
129
|
export function registerArrayExtensions(): void {
|
|
92
130
|
if (typeof Array.prototype.sample !== 'function') {
|
|
93
|
-
Array.prototype.sample = function <T>(this: T[], n?: number): T[] {
|
|
94
|
-
return sample(this, n);
|
|
131
|
+
Array.prototype.sample = function <T>(this: T[], n?: number, options?: SampleOptions): T[] {
|
|
132
|
+
return sample(this, n, options);
|
|
95
133
|
};
|
|
96
134
|
}
|
|
97
135
|
|
|
@@ -107,6 +145,18 @@ export function registerArrayExtensions(): void {
|
|
|
107
145
|
};
|
|
108
146
|
}
|
|
109
147
|
|
|
148
|
+
if (typeof Array.prototype.mean !== 'function') {
|
|
149
|
+
Array.prototype.mean = function (this: number[]): number {
|
|
150
|
+
return mean(this);
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (typeof Array.prototype.sum !== 'function') {
|
|
155
|
+
Array.prototype.sum = function (this: number[]): number {
|
|
156
|
+
return sum(this);
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
110
160
|
if (typeof Array.prototype.chunk !== 'function') {
|
|
111
161
|
Array.prototype.chunk = function <T>(this: T[], n: number): T[][] {
|
|
112
162
|
return chunk(this, n);
|
|
@@ -30,7 +30,9 @@ function seedDistributions(seed: number): void {
|
|
|
30
30
|
type UniformSpec = { distribution: 'uniform'; min: number; max: number };
|
|
31
31
|
type NormalSpec = { distribution: 'normal'; mean: number; sd: number };
|
|
32
32
|
type PoissonSpec = { distribution: 'poisson'; mean: number };
|
|
33
|
-
type
|
|
33
|
+
type IntegerSpec = { distribution: 'integer'; min: number; max: number };
|
|
34
|
+
type DiscreteSpec = { distribution: 'discrete'; outcomes: Array<{ value: number; weight: number }> };
|
|
35
|
+
type DimensionSpec = UniformSpec | NormalSpec | PoissonSpec | IntegerSpec | DiscreteSpec;
|
|
34
36
|
|
|
35
37
|
// Inverse CDFs return +-Infinity at exactly 0 or 1, so clamp to open interval (0, 1).
|
|
36
38
|
function clampUnit(value: number): number {
|
|
@@ -47,6 +49,23 @@ function resolveTransform(spec: DimensionSpec): (unitValue: number) => number {
|
|
|
47
49
|
// QMC variance reduction is less effective on discrete distributions
|
|
48
50
|
// due to integer clumping at quantile boundaries.
|
|
49
51
|
return (u) => poissonQuantile(clampUnit(u), spec.mean);
|
|
52
|
+
case 'integer':
|
|
53
|
+
// Uniform integer in [min, max] inclusive
|
|
54
|
+
return (u) => Math.floor(spec.min + u * (spec.max - spec.min + 1));
|
|
55
|
+
case 'discrete': {
|
|
56
|
+
// Weighted discrete distribution -> divide [0,1) into segments proportional to weights
|
|
57
|
+
const totalWeight = spec.outcomes.reduce((sum, o) => sum + o.weight, 0);
|
|
58
|
+
const cumulative = spec.outcomes.map((() => {
|
|
59
|
+
let acc = 0;
|
|
60
|
+
return (o: { value: number; weight: number }) => { acc += o.weight / totalWeight; return acc; };
|
|
61
|
+
})());
|
|
62
|
+
return (u) => {
|
|
63
|
+
for (let i = 0; i < cumulative.length; i++) {
|
|
64
|
+
if (u < cumulative[i]) return spec.outcomes[i].value;
|
|
65
|
+
}
|
|
66
|
+
return spec.outcomes[spec.outcomes.length - 1].value;
|
|
67
|
+
};
|
|
68
|
+
}
|
|
50
69
|
}
|
|
51
70
|
}
|
|
52
71
|
|
|
@@ -154,7 +173,7 @@ function sampleParticipants<T extends Record<string, DimensionSpec>>(
|
|
|
154
173
|
method: SamplingMethod,
|
|
155
174
|
count: number,
|
|
156
175
|
specs: T,
|
|
157
|
-
): Array<{ [K in keyof T]: number }> {
|
|
176
|
+
): Array<{ [K in keyof T]: number } & { index: number }> {
|
|
158
177
|
const keys = Object.keys(specs) as (keyof T & string)[];
|
|
159
178
|
const dimSpecs = keys.map((k) => specs[k]);
|
|
160
179
|
|
|
@@ -173,7 +192,7 @@ function sampleParticipants<T extends Record<string, DimensionSpec>>(
|
|
|
173
192
|
|
|
174
193
|
return Array.from({ length: count }, (_, i) => {
|
|
175
194
|
const row = keys.length === 1 ? [points[i] as number] : (points[i] as number[]);
|
|
176
|
-
return Object.fromEntries(keys.map((k, d) => [k, row[d]])) as { [K in keyof T]: number };
|
|
195
|
+
return { index: i, ...Object.fromEntries(keys.map((k, d) => [k, row[d]])) } as { [K in keyof T]: number } & { index: number };
|
|
177
196
|
});
|
|
178
197
|
}
|
|
179
198
|
|
|
@@ -187,5 +206,9 @@ function randomPoints(count: number, specs: DimensionSpec[]): number[] | number[
|
|
|
187
206
|
);
|
|
188
207
|
}
|
|
189
208
|
|
|
190
|
-
|
|
191
|
-
|
|
209
|
+
function draw(spec: DimensionSpec): number {
|
|
210
|
+
return resolveTransform(spec)(uniform(0, 1));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export { normal, poisson, uniform, seedDistributions, sobol, halton, sampleParticipants, draw };
|
|
214
|
+
export type { DimensionSpec, UniformSpec, NormalSpec, PoissonSpec, IntegerSpec, DiscreteSpec, SamplingMethod };
|
package/src/utils/llm.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
export interface LLMConfig {
|
|
2
|
+
provider: 'openai' | 'huggingface';
|
|
3
|
+
model: string;
|
|
4
|
+
apiKey: string;
|
|
5
|
+
/** Override the API base URL. Defaults to the provider's standard endpoint. */
|
|
6
|
+
baseUrl?: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** JSON Schema object for constraining LLM output. Passed as the third argument to invokeLLM. */
|
|
10
|
+
export type LLMSchema = Record<string, any>;
|
|
11
|
+
|
|
12
|
+
function resolveBaseUrl(config: LLMConfig): string {
|
|
13
|
+
return config.baseUrl
|
|
14
|
+
?? (config.provider === 'huggingface'
|
|
15
|
+
? `https://api-inference.huggingface.co/models/${config.model}/v1`
|
|
16
|
+
: 'https://api.openai.com/v1');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function callLLM(config: LLMConfig, prompt: string, schema?: LLMSchema): Promise<string> {
|
|
20
|
+
const baseUrl = resolveBaseUrl(config);
|
|
21
|
+
|
|
22
|
+
const body: Record<string, any> = {
|
|
23
|
+
model: config.model,
|
|
24
|
+
messages: [{ role: 'user', content: prompt }],
|
|
25
|
+
};
|
|
26
|
+
if (schema) {
|
|
27
|
+
body.response_format = {
|
|
28
|
+
type: 'json_schema',
|
|
29
|
+
json_schema: { name: 'response', schema, strict: true },
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const response = await fetch(`${baseUrl}/chat/completions`, {
|
|
34
|
+
method: 'POST',
|
|
35
|
+
headers: {
|
|
36
|
+
'Authorization': `Bearer ${config.apiKey}`,
|
|
37
|
+
'Content-Type': 'application/json',
|
|
38
|
+
},
|
|
39
|
+
body: JSON.stringify(body),
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
if (!response.ok) {
|
|
43
|
+
throw new Error(`LLM API error: ${response.status} ${response.statusText}`);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const data = await response.json();
|
|
47
|
+
return data.choices[0].message.content;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// --- Disk-backed LLM response cache ---
|
|
51
|
+
// Stored at .reactive-cache/llm.json in the working directory.
|
|
52
|
+
// Keyed by provider:model:prompt:responseFormat — API key intentionally excluded
|
|
53
|
+
// so cache works across key rotations.
|
|
54
|
+
|
|
55
|
+
const CACHE_DIR = '.reactive-cache';
|
|
56
|
+
const CACHE_FILE = 'llm.json';
|
|
57
|
+
let diskCache: Record<string, string> | null = null;
|
|
58
|
+
import { getNodeRequire } from './nodecompat';
|
|
59
|
+
|
|
60
|
+
async function loadCache(): Promise<Record<string, string>> {
|
|
61
|
+
if (diskCache) return diskCache;
|
|
62
|
+
try {
|
|
63
|
+
const req = await getNodeRequire();
|
|
64
|
+
const fs = req('fs') as typeof import('fs');
|
|
65
|
+
const path = req('path') as typeof import('path');
|
|
66
|
+
const filePath = path.join(process.cwd(), CACHE_DIR, CACHE_FILE);
|
|
67
|
+
if (fs.existsSync(filePath)) {
|
|
68
|
+
diskCache = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
69
|
+
return diskCache!;
|
|
70
|
+
}
|
|
71
|
+
} catch {}
|
|
72
|
+
diskCache = {};
|
|
73
|
+
return diskCache;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function saveCache(): Promise<void> {
|
|
77
|
+
if (!diskCache) return;
|
|
78
|
+
try {
|
|
79
|
+
const req = await getNodeRequire();
|
|
80
|
+
const fs = req('fs') as typeof import('fs');
|
|
81
|
+
const path = req('path') as typeof import('path');
|
|
82
|
+
const dirPath = path.join(process.cwd(), CACHE_DIR);
|
|
83
|
+
fs.mkdirSync(dirPath, { recursive: true });
|
|
84
|
+
fs.writeFileSync(path.join(dirPath, CACHE_FILE), JSON.stringify(diskCache, null, 2));
|
|
85
|
+
} catch {}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function invokeLLM(config: LLMConfig, prompt: string, schema?: LLMSchema): Promise<string> {
|
|
89
|
+
const formatKey = schema ? JSON.stringify(schema) : '';
|
|
90
|
+
const cacheKey = `${config.provider}:${config.model}:${prompt}:${formatKey}`;
|
|
91
|
+
const cache = await loadCache();
|
|
92
|
+
|
|
93
|
+
let text = cache[cacheKey];
|
|
94
|
+
if (!text) {
|
|
95
|
+
text = await callLLM(config, prompt, schema);
|
|
96
|
+
cache[cacheKey] = text;
|
|
97
|
+
await saveCache();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return text;
|
|
101
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Creates a require() function for loading Node builtins (fs, path, etc.) at runtime.
|
|
2
|
+
// Needed because these files are bundled as ESM by Vite, where require doesn't exist.
|
|
3
|
+
// Only initialized when called (simulation time), not on import (safe in browser).
|
|
4
|
+
let _require: ((id: string) => any) | null = null;
|
|
5
|
+
export async function getNodeRequire(): Promise<(id: string) => any> {
|
|
6
|
+
if (!_require) {
|
|
7
|
+
const mod = await import(/* @vite-ignore */ 'module') as any;
|
|
8
|
+
_require = mod.createRequire(import.meta.url);
|
|
9
|
+
}
|
|
10
|
+
return _require!;
|
|
11
|
+
}
|
package/src/utils/simulation.ts
CHANGED
|
@@ -182,7 +182,7 @@ export async function orchestrateSimulation(config: RunSimulationConfig, scriptP
|
|
|
182
182
|
? config.participants.length
|
|
183
183
|
: config.participants.count;
|
|
184
184
|
|
|
185
|
-
const backend = spawn('
|
|
185
|
+
const backend = spawn('node', ['src/backend.ts'], {
|
|
186
186
|
cwd: './backend',
|
|
187
187
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
188
188
|
});
|
|
@@ -223,7 +223,7 @@ export async function orchestrateSimulation(config: RunSimulationConfig, scriptP
|
|
|
223
223
|
|
|
224
224
|
const spawnWorker = (i: number) => new Promise<void>((resolve) => {
|
|
225
225
|
let stderr = '';
|
|
226
|
-
const worker = spawn('
|
|
226
|
+
const worker = spawn('node', [scriptPath], {
|
|
227
227
|
env: {
|
|
228
228
|
...process.env,
|
|
229
229
|
_REACTIVE_WORKER_INDEX: String(i),
|
package/src/utils/theme.ts
CHANGED
package/src/utils/tts.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { getNodeRequire } from './nodecompat';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Generates a WebM audio file from text using the platform's native TTS.
|
|
5
|
+
* Requires `ffmpeg` to be installed for WAV->WebM conversion.
|
|
6
|
+
*
|
|
7
|
+
* - macOS: `say` (prefers Ava voice if available)
|
|
8
|
+
* - Linux: `espeak-ng` or `espeak`
|
|
9
|
+
* - Windows: PowerShell `System.Speech`
|
|
10
|
+
*
|
|
11
|
+
* Returns base64-encoded WebM audio, or null if TTS/ffmpeg is unavailable.
|
|
12
|
+
*/
|
|
13
|
+
export async function textToWebmBase64(text: string): Promise<string | null> {
|
|
14
|
+
try {
|
|
15
|
+
const req = await getNodeRequire();
|
|
16
|
+
const childProcess: typeof import('child_process') = req('child_process');
|
|
17
|
+
const path: typeof import('path') = req('path');
|
|
18
|
+
const fs: typeof import('fs') = req('fs');
|
|
19
|
+
const os: typeof import('os') = req('os');
|
|
20
|
+
|
|
21
|
+
const { execSync } = childProcess;
|
|
22
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'reactive-tts-'));
|
|
23
|
+
const wavPath = path.join(dir, 'tts.wav');
|
|
24
|
+
const webmPath = path.join(dir, 'tts.webm');
|
|
25
|
+
|
|
26
|
+
const escaped = text.replace(/"/g, '\\"');
|
|
27
|
+
const platform = process.platform;
|
|
28
|
+
|
|
29
|
+
if (platform === 'darwin') {
|
|
30
|
+
let voice = '';
|
|
31
|
+
try {
|
|
32
|
+
const voices = execSync('say -v "?"', { encoding: 'utf8' });
|
|
33
|
+
if (voices.includes('Ava')) voice = '-v "Ava (Premium)"';
|
|
34
|
+
} catch { /* use default */ }
|
|
35
|
+
execSync(`say ${voice} -o "${wavPath}" --data-format=LEI16@22050 "${escaped}"`, { stdio: 'ignore' });
|
|
36
|
+
} else if (platform === 'win32') {
|
|
37
|
+
const ps = `Add-Type -AssemblyName System.Speech; $s = New-Object System.Speech.Synthesis.SpeechSynthesizer; $s.SetOutputToWaveFile('${wavPath.replace(/'/g, "''")}'); $s.Speak('${escaped.replace(/'/g, "''")}'); $s.Dispose()`;
|
|
38
|
+
execSync(`powershell -Command "${ps.replace(/"/g, '\\"')}"`, { stdio: 'ignore' });
|
|
39
|
+
} else {
|
|
40
|
+
try {
|
|
41
|
+
execSync(`espeak-ng -w "${wavPath}" "${escaped}"`, { stdio: 'ignore' });
|
|
42
|
+
} catch {
|
|
43
|
+
execSync(`espeak -w "${wavPath}" "${escaped}"`, { stdio: 'ignore' });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
execSync(`ffmpeg -i "${wavPath}" -c:a libopus -b:a 24k "${webmPath}" -y`, { stdio: 'ignore' });
|
|
48
|
+
|
|
49
|
+
const webmData = fs.readFileSync(webmPath);
|
|
50
|
+
const base64 = webmData.toString('base64');
|
|
51
|
+
|
|
52
|
+
try { fs.unlinkSync(wavPath); } catch { /* ignore */ }
|
|
53
|
+
try { fs.unlinkSync(webmPath); } catch { /* ignore */ }
|
|
54
|
+
try { fs.rmdirSync(dir); } catch { /* ignore */ }
|
|
55
|
+
|
|
56
|
+
return base64;
|
|
57
|
+
} catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Returns the duration of a base64-encoded audio file in milliseconds using ffprobe.
|
|
64
|
+
* Returns null if ffprobe is unavailable or the audio can't be probed.
|
|
65
|
+
*/
|
|
66
|
+
export async function probeAudioDurationMs(base64Audio: string): Promise<number | null> {
|
|
67
|
+
try {
|
|
68
|
+
const req = await getNodeRequire();
|
|
69
|
+
const { execSync } = req('child_process') as typeof import('child_process');
|
|
70
|
+
const fs = req('fs') as typeof import('fs');
|
|
71
|
+
const path = req('path') as typeof import('path');
|
|
72
|
+
const os = req('os') as typeof import('os');
|
|
73
|
+
|
|
74
|
+
const tmp = path.join(os.tmpdir(), `reactive-probe-${Date.now()}.webm`);
|
|
75
|
+
fs.writeFileSync(tmp, Buffer.from(base64Audio, 'base64'));
|
|
76
|
+
const out = execSync(`ffprobe -v error -show_entries format=duration -of csv=p=0 "${tmp}"`, { encoding: 'utf8' }).trim();
|
|
77
|
+
fs.unlinkSync(tmp);
|
|
78
|
+
return Math.round(parseFloat(out) * 1000);
|
|
79
|
+
} catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|