html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sherlock Voice/UI Prototyping Toolkit</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.35.0/ace.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.3/chart.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }
.panel { background: white; border-radius: 8px; padding: 20px; margin: 10px 0; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
.row { display: flex; gap: 20px; }
.col { flex: 1; }
#ssml-preview { white-space: pre-wrap; background: #f0f0f0; padding: 10px; border-radius: 4px; min-height: 60px; }
#user-input { width: 70%; padding: 10px; font-size: 16px; }
button { padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background: #0056b3; }
button:disabled { background: #ccc; }
#audio { width: 100%; margin-top: 10px; }
#analytics-chart { height: 300px; }
.log-entry { padding: 5px; border-bottom: 1px solid #eee; font-family: monospace; }
.status { padding: 10px; border-radius: 4px; margin: 10px 0; }
.success { background: #d4edda; color: #155724; }
.error { background: #f8d7da; color: #721c24; }
.warning { background: #fff3cd; color: #856404; }
</style>
</head>
<body>
<h1>🕵️♂️ Sherlock Voice/UI Prototyping Toolkit</h1>
<p><em>Built by Trailblazer Labs. Merge SSML for voice output, conversational flows for tests, and analytics for iterative design. Self-contained—save as .html and iterate!</em></p>
<div class="row">
<div class="col panel">
<h3>1. Flow Editor (JSON + SSML)</h3>
<div id="editor" style="height: 300px; border: 1px solid #ddd;"></div>
<button onclick="loadExample()">Load Example</button>
<button onclick="saveFlow()">Save Flow</button>
</div>
<div class="col panel">
<h3>2. SSML Live Preview</h3>
<div id="ssml-preview"></div>
<button onclick="playSSML()">🔊 Play SSML</button>
<button onclick="stopAudio()">⏹️ Stop</button>
</div>
</div>
<div class="row">
<div class="col panel">
<h3>3. Live Test (Manual Conversation)</h3>
<input type="text" id="user-input" placeholder="Type user utterance..." onkeypress="if(event.key==='Enter') sendUtterance()">
<button onclick="sendUtterance()">Send Utterance</button>
<div id="live-log"></div>
<audio id="audio" controls></audio>
</div>
<div class="col panel">
<h3>4. Test Suite Editor</h3>
<div id="test-editor" style="height: 200px; border: 1px solid #ddd;"></div>
<button onclick="loadTestExample()">Load Test Example</button>
<button onclick="runTests()">Run Tests</button>
<button onclick="exportAnalytics()">Export Analytics CSV</button>
</div>
</div>
<div class="panel">
<h3>5. Analytics Dashboard</h3>
<canvas id="analytics-chart"></canvas>
<div id="analytics-summary"></div>
<div id="test-log"></div>
</div>
<script>
// Global state
let currentFlow = {};
let currentTests = [];
let analyticsData = []; // Array of sessions: {id, events: [], metrics: {turns:0, completed:true, dropoffNode:null}}
let currentSession = null;
let audioContext = null;
let currentNode = null;
let sessionId = 0;
let chart = null;
// Ace Editors
const flowEditor = ace.edit("editor");
flowEditor.setTheme("ace/theme/monokai");
flowEditor.session.setMode("ace/mode/json");
flowEditor.setOptions({ fontSize: "14px" });
const testEditor = ace.edit("test-editor");
testEditor.setTheme("ace/theme/monokai");
testEditor.session.setMode("ace/mode/json");
testEditor.setOptions({ fontSize: "14px" });
// Example Flow (conversational tree with SSML)
function loadExample() {
const example = {
start: "welcome",
nodes: {
welcome: {
ssml: `<speak>Welcome! <prosody rate="slow" pitch="+10%">How can I help?</prosody> Say <emphasis level="strong">yes</emphasis> or <break time="500ms"/> no.</speak>`,
intents: { yes: "help", no: "goodbye" }
},
help: {
ssml: `<speak>Great! Here's some <prosody volume="loud">help</prosody>. <break strength="medium"/> Anything else?</speak>`,
intents: { yes: "more", no: "goodbye" }
},
more: {
ssml: `<speak>More help coming up. Thanks for testing! <prosody rate="x-slow">End of flow.</prosody></speak>`,
intents: {}
},
goodbye: {
ssml: `<speak>Goodbye! <break time="1s"/>Session end.</speak>`,
intents: {}
}
}
};
flowEditor.setValue(JSON.stringify(example, null, 2));
updateSSMLPreview(example.nodes[example.start]?.ssml || '');
logStatus('success', 'Example flow loaded. Edit and test!');
}
// Example Tests (array of sessions: each an array of user utterances)
function loadTestExample() {
const example = [
["yes", "yes"], // Happy path
["no"], // Early exit
["help", "no"], // Alt path
["junk"] // Error handling
];
testEditor.setValue(JSON.stringify(example, null, 2));
logStatus('success', 'Test suite loaded. Run to analyze!');
}
// Load/Save Flow
flowEditor.on('change', () => {
try {
currentFlow = JSON.parse(flowEditor.getValue());
if (currentFlow.start && currentFlow.nodes) {
updateSSMLPreview(currentFlow.nodes[currentFlow.start]?.ssml || '');
logStatus('success', 'Flow parsed OK.');
}
} catch (e) {
logStatus('error', 'Invalid JSON: ' + e.message);
}
});
function saveFlow() {
const blob = new Blob([flowEditor.getValue()], {type: 'application/json'});
saveAs(blob, 'voice-flow.json');
}
// SSML Preview (strip tags for text preview; approx TTS)
function updateSSMLPreview(ssml) {
const text = ssml.replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
document.getElementById('ssml-preview').textContent = ssml + '\n\nPreview Text: ' + text;
}
// Play SSML via Web Speech (partial support; strips tags for fallback)
function playSSML() {
const ssml = document.getElementById('ssml-preview').textContent.split('\n')[0];
const utterance = new SpeechSynthesisUtterance(ssml.replace(/<[^>]*>/g, ''));
// Hacky SSML approx: parse prosody etc. (expandable)
if (ssml.includes('rate="slow"')) utterance.rate = 0.8;
if (ssml.includes('loud')) utterance.volume = 1;
speechSynthesis.speak(utterance);
}
function stopAudio() {
speechSynthesis.cancel();
}
// Simple NLU: word overlap scoring for prototyping (no real ML)
function recognizeIntent(utterance, intents) {
const words = utterance.toLowerCase().split(/\s+/).filter(w => w.length > 2);
let bestIntent = null;
let bestScore = 0;
Object.keys(intents).forEach(key => {
const score = key.toLowerCase().split(/\s+/).filter(w => words.includes(w)).length;
if (score > bestScore) {
bestScore = score;
bestIntent = key;
}
});
const confidence = bestScore / Math.max(words.length, 1);
return { intent: bestIntent || 'fallback', confidence: confidence > 0.3 ? confidence : 0 };
}
// Live Test Simulator
function sendUtterance() {
const input = document.getElementById('user-input');
const utterance = input.value.trim();
if (!utterance || !currentFlow.start) return input.value = '';
if (!currentSession) newSession();
const logEl = document.getElementById('live-log');
logEl.innerHTML += `<div class="log-entry"><strong>User:</strong> ${utterance}</div>`;
const recog = recognizeIntent(utterance, currentNode?.intents || {});
currentSession.events.push({ type: 'listen', utterance, intent: recog.intent, confidence: recog.confidence, time: Date.now() });
logEl.innerHTML += `<div class="log-entry"><strong>Intent:</strong> ${recog.intent} (conf ${Math.round(recog.confidence*100)}%)</div>`;
const nextNodeId = currentNode?.intents?.[recog.intent];
if (nextNodeId && currentFlow.nodes[nextNodeId]) {
currentNode = currentFlow.nodes[nextNodeId];
currentSession.events.push({ type: 'transition', from: currentNodeId, to: nextNodeId, time: Date.now() });
} else {
currentNode = null;
currentSession.metrics.completed = false;
currentSession.metrics.dropoffNode = currentNodeId;
logStatus('warning', 'Dropoff/No match!');
}
if (currentNode) {
speak(currentNode.ssml);
currentSession.metrics.turns++;
}
input.value = '';
updateAnalytics();
}
function speak(ssml) {
updateSSMLPreview(ssml);
// Simulate audio play (use playSSML() for real; here queue)
playSSML();
const logEl = document.getElementById('live-log');
logEl.innerHTML += `<div class="log-entry"><strong>Bot:</strong> ${ssml.replace(/<[^>]*>/g, '')}</div>`;
currentSession.events.push({ type: 'speak', node: currentNodeId, ssml, time: Date.now() });
}
function newSession() {
sessionId++;
currentSession = { id: sessionId, events: [], metrics: { turns: 0, completed: true, dropoffNode: null } };
currentNode = currentFlow.nodes?.[currentFlow.start];
if (currentNode) speak(currentNode.ssml);
else logStatus('error', 'No start node!');
}
// Test Suite Runner
testEditor.on('change', () => {
try {
currentTests = JSON.parse(testEditor.getValue());
} catch (e) {}
});
async function runTests() {
try {
currentTests = JSON.parse(testEditor.getValue());
} catch (e) {
logStatus('error', 'Invalid test JSON');
return;
}
analyticsData = [];
sessionId = 0;
document.getElementById('test-log').innerHTML = '';
const testLogEl = document.getElementById('test-log');
for (let i = 0; i < currentTests.length; i++) {
const test = currentTests[i];
newSession();
testLogEl.innerHTML += `<div class="status success">Test ${i+1}: ${test.length} turns</div>`;
for (const utt of test) {
document.getElementById('user-input').value = utt;
sendUtterance();
await new Promise(r => setTimeout(r, 1000)); // Simulate response time
}
analyticsData.push(currentSession);
testLogEl.innerHTML += `<div class="log-entry">Session ${currentSession.id}: ${currentSession.metrics.turns} turns, Completed: ${currentSession.metrics.completed}</div>`;
}
updateAnalytics();
logStatus('success', `${currentTests.length} tests run! Check dashboard.`);
}
// Analytics
function updateAnalytics() {
const summaryEl = document.getElementById('analytics-summary');
const sessions = analyticsData.length + (currentSession ? 1 : 0);
const avgTurns = analyticsData.reduce((sum, s) => sum + s.metrics.turns, currentSession?.metrics.turns || 0) / Math.max(sessions,1);
const completionRate = (analyticsData.filter(s => s.metrics.completed).length + (currentSession?.metrics.completed ? 1 : 0)) / Math.max(sessions,1) * 100;
summaryEl.innerHTML = `
<p>Sessions: ${sessions} | Avg Turns: ${avgTurns.toFixed(1)} | Completion: ${completionRate.toFixed(1)}% | Dropoffs: ${analyticsData.filter(s => s.metrics.dropoffNode).length}</p>
`;
// Chart: Turns per session
const ctx = document.getElementById('analytics-chart').getContext('2d');
if (chart) chart.destroy();
const labels = analyticsData.map((s,i) => `S${s.id}`);
if (currentSession) labels.push('Live');
chart = new Chart(ctx, {
type: 'bar',
data: {
labels,
datasets: [{
label: 'Turns',
data: [...analyticsData.map(s => s.metrics.turns), currentSession?.metrics.turns || 0]
}, {
label: 'Completion',
data: [...analyticsData.map(s => s.metrics.completed ? 1 : 0), currentSession?.metrics.completed ? 1 : 0],
type: 'line'
}]
},
options: { scales: { y: { beginAtZero: true } } }
});
}
function exportAnalytics() {
const csv = ['Session,Turns,Completed,Dropoff,Events\n'] +
analyticsData.map(s => `${s.id},${s.metrics.turns},${s.metrics.completed},${s.metrics.dropoffNode || ''},${s.events.length}`).join('\n');
const blob = new Blob([csv], {type: 'text/csv'});
saveAs(blob, 'analytics.csv');
}
function logStatus(type, msg) {
const statusEl = document.getElementById('live-log');
statusEl.innerHTML += `<div class="status ${type}">${msg}</div>`;
statusEl.scrollTop = statusEl.scrollHeight;
}
// Init
loadExample();
loadTestExample();
newSession();
updateAnalytics();
</script>
</body>
</html>
Iterate away, designer! 🛠️ Questions? Ask Sherlock.