Spaces:
Running
Running
feat: deploy SignLens web app to Hugging Face Spaces
Browse filesThis view is limited to 50 files because it contains too many changes. ย See raw diff
Files changed (50)
- .gitattributes+2
- ASL_Alphabet_Chart.pngAdded
- ISL_Hand_Signs_Official.pngAdded
- README.md+36-3
- app.jsAdded+2384
- asl_landmarks_weights.jsonAdded
- asl_signs/A.pngAdded
- asl_signs/B.pngAdded
- asl_signs/C.pngAdded
- asl_signs/D.pngAdded
- asl_signs/E.pngAdded
- asl_signs/F.pngAdded
- asl_signs/G.pngAdded
- asl_signs/H.pngAdded
- asl_signs/I.pngAdded
- asl_signs/J.pngAdded
- asl_signs/K.pngAdded
- asl_signs/L.pngAdded
- asl_signs/M.pngAdded
- asl_signs/N.pngAdded
- asl_signs/O.pngAdded
- asl_signs/P.pngAdded
- asl_signs/Q.pngAdded
- asl_signs/R.pngAdded
- asl_signs/S.pngAdded
- asl_signs/T.pngAdded
- asl_signs/U.pngAdded
- asl_signs/V.pngAdded
- asl_signs/W.pngAdded
- asl_signs/X.pngAdded
- asl_signs/Y.pngAdded
- asl_signs/Z.pngAdded
- index.html+393-19
- isl_landmarks_weights.jsonAdded
- isl_signs/1.pngAdded
- isl_signs/2.pngAdded
- isl_signs/3.pngAdded
- isl_signs/4.pngAdded
- isl_signs/5.pngAdded
- isl_signs/6.pngAdded
- isl_signs/7.pngAdded
- isl_signs/8.pngAdded
- isl_signs/9.pngAdded
- isl_signs/A.pngAdded
- isl_signs/B.pngAdded
- isl_signs/C.pngAdded
- isl_signs/D.pngAdded
- isl_signs/E.pngAdded
- isl_signs/F.pngAdded
- isl_signs/G.pngAdded
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textASL_Alphabet_Chart.png filter=lfs diff=lfs merge=lfs -textISL_Hand_Signs_Official.png filter=lfs diff=lfs merge=lfs -text
12345678910---title: SignLensemoji: ๐colorFrom: indigocolorTo: indigosdk: staticpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122232425262728293031323334353637383940414243---title: SignLensemoji: ๐คcolorFrom: yellowcolorTo: indigosdk: staticpinned: falselicense: apache-2.0tags:- sign-language-detection- computer-vision- mediapipe- indian-sign-language- american-sign-language- accessibility- neural-network---# ๐ค SignLens: Real-Time Sign Language Translation & Avatar Practice StudioWelcome to **SignLens** running live on Hugging Face Spaces!SignLens is a high-speed, client-side neural landmark translation engine that translates **Indian Sign Language (ISL)** and **American Sign Language (ASL)** directly in your browser with zero server latency.## โจ Features1. **Live Camera Recognition**:- High-speed 3D landmark tracking powered by MediaPipe WebVision.- Dual-mode support for both **ISL** (Dual-Hand 35 classes) and **ASL** (Single-Hand 28 classes).- In-browser neural forward pass with confidence thresholds, hold gauge, and streak confirmation.2. **Auto-Framing Word & Sentence Builder**:- Eliminates gesture spam and flickering.- Dynamic word boundary detection and Text-to-Speech (TTS) voice readout.3. **VISUALLY โ 3D Skeletal Avatar Studio**:- Type any phrase or click sample prompts to watch the interactive avatar demonstrate correct hand and arm motions step-by-step.- Interactive scrub bar, playback speed control (0.5x, 1.0x, 1.5x), and live letter timeline.- Top-right real-human sign reference card synchronized with the skeleton.4. **Official Sign Reference Guide**:- Full dictionary of official poses, hand counts (1-Hand vs 2-Hand rules), and high-resolution photo popups.## ๐ Project Links- **Model Card & Evaluation**: [Hugging Face: SignLens-Landmark-Model](https://huggingface.co/venmugilrajan/SignLens-Landmark-Model)- **Source Code**: [GitHub: Sign_lang](https://github.com/venmugilrajan/Sign_lang)- **Author**: Venmugil Rajan
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384/**
* SignLens โ MediaPipe Landmark Neural Network Edition
*
* Runs classification directly in the browser using the weights
* of our custom MLP Neural Network trained on the 21 hand landmarks.
*/
// โโ Config โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
let STREAK_NEEDED = 5; // frames of same letter to capture (settings sheet, matches native)
const COOLDOWN_MS = 350; // ms after capture before detecting again (fluid sign transitions)
let SPACE_FRAMES = 90; // no-hand frames before auto word push (~3.0s at 30fps, plenty of transition time)
let MIN_CONFIDENCE = 0.50; // minimum classifier confidence (settings sheet, matches native 0.40-0.50)
const MIN_HAND_SPAN = 35; // minimum pixel distance between wrist and middle MCP to reject ghost hands
// โโ MediaPipe Hand Connections โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
const CONNECTIONS = [
[0,1],[1,2],[2,3],[3,4],
[0,5],[5,6],[6,7],[7,8],
[0,9],[9,10],[10,11],[11,12],
[0,13],[13,14],[14,15],[15,16],
[0,17],[17,18],[18,19],[19,20],
[5,9],[9,13],[13,17],
];
const NODE_COLORS = {
0:'#ffffff',
1:'#f2856a',2:'#f2856a',3:'#f2856a',4:'#f2856a',
5:'#f0a53f',6:'#f0a53f',7:'#f0a53f',8:'#f0a53f',
9:'#6ec9a0',10:'#6ec9a0',11:'#6ec9a0',12:'#6ec9a0',
13:'#5aa9e6',14:'#5aa9e6',15:'#5aa9e6',16:'#5aa9e6',
17:'#b98ae0',18:'#b98ae0',19:'#b98ae0',20:'#b98ae0',
};
const EDGE_COLORS = [
'#f2856a','#f2856a','#f2856a','#f2856a', // thumb 0-3
'#f0a53f','#f0a53f','#f0a53f','#f0a53f', // index 4-7
'#6ec9a0','#6ec9a0','#6ec9a0','#6ec9a0', // middle 8-11
'#5aa9e6','#5aa9e6','#5aa9e6','#5aa9e6', // ring 12-15
'#b98ae0','#b98ae0','#b98ae0','#b98ae0', // pinky 16-19
'#6a6a76','#6a6a76','#6a6a76', // palm 20-22
];
// โโ State โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
let currentMode = 'asl';
let paused = false;
let inCooldown = false;
let cameraActive = false;
let currentWord = '';
let letterConfidences = [];
let sentenceWords = [];
let streakLetter = null;
let streakCount = 0;
let noHandCount = 0;
// State tracking to prevent runaway letter repeat without releasing hand
let lastCapturedLetter = '';
let releasedSinceLastCapture = true;
let releaseFrames = 0;
const RELEASE_FRAMES_NEEDED = 3;
// State tracking to prevent runaway word repeat without clear user intent
let lastCommittedWord = '';
// Trained Neural Network model weights (kept for OFFLINE fallback only)
let aslWeights = null;
let islWeights = null;
let currentWeights = null;
// โโ Server-side inference state โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// When Flask is running, all classification is done server-side (predict_proba
// on the sklearn model) for feature parity with run_native.py.
// If the server is unreachable, we fall back to the JS MLP.
let serverAvailable = false; // set true after first successful /health probe
let serverCheckPending = false;
// โโ DOM โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
const video = document.getElementById('webcam-video');
const displayCanvas = document.getElementById('display-canvas');
const dctx = displayCanvas.getContext('2d');
const noHandOverlay = document.getElementById('no-hand-overlay');
const detectedLetter = document.getElementById('detected-letter');
const detectedConf = document.getElementById('detected-conf');
const streakBar = document.getElementById('streak-bar');
const streakLabel = document.getElementById('streak-label');
const handBadge = document.getElementById('hand-badge');
const statusPill = document.getElementById('status-pill');
const statusText = document.getElementById('status-text');
const wordDisplay = document.getElementById('word-display');
const sentenceDisplay = document.getElementById('sentence-display');
const wordChips = document.getElementById('word-chips');
const modeToggle = document.getElementById('mode-toggle');
const toast = document.getElementById('toast');
// โโ Utilities โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ๏ฟฝ๏ฟฝ๏ฟฝโโโโโโโโโโโโโโโ
function showToast(msg, ms = 2000) {
toast.textContent = msg;
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), ms);
}
function setStatus(cls, msg) {
statusPill.className = `status-pill ${cls}`;
statusText.textContent = msg;
}
function setStreakVisual(pct) {
streakBar.style.width = `${pct}%`;
// .dial-ring reads --streak as a registered <number> and interpolates it.
document.documentElement.style.setProperty('--streak', pct);
}
function resetStreak() {
streakLetter = null; streakCount = 0;
setStreakVisual(0);
streakLabel.textContent = `0 / ${STREAK_NEEDED}`;
}
// โโ Word / Sentence โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
function renderWord() {
wordDisplay.innerHTML = currentWord
? currentWord
: '<span class="ph">Start signingโฆ</span>';
}
function renderSentence() {
sentenceDisplay.innerHTML = sentenceWords.length
? sentenceWords.join(' ')
: '<em class="ph">Your sentence will appear hereโฆ</em>';
wordChips.innerHTML = '';
sentenceWords.forEach(w => {
const c = document.createElement('span');
c.className = 'word-chip'; c.textContent = w;
wordChips.appendChild(c);
});
}
async function pushWord() {
let w = currentWord.trim();
if (w) {
// Attempt spellcheck via backend API if available
try {
const res = await fetch('/spellcheck', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ word: w, confidences: letterConfidences })
});
if (res.ok) {
const data = await res.json();
if (data.corrected) {
w = data.corrected.toUpperCase();
}
}
} catch (e) {
// Backend not present or offline, keep raw word
}
// Gating: Don't repeat the exact same word back-to-back if triggered by background jitter
const isDuplicateAutoPush = (sentenceWords.length > 0 && sentenceWords[sentenceWords.length - 1] === w && lastCommittedWord === w);
if (!isDuplicateAutoPush) {
sentenceWords.push(w);
lastCommittedWord = w;
renderSentence();
showToast(`โ "${w}"`);
}
}
currentWord = '';
letterConfidences = [];
renderWord();
resetStreak();
noHandCount = 0;
lastCapturedLetter = '';
releasedSinceLastCapture = true;
releaseFrames = 0;
}
// โโ Letter capture โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
function captureLetter(letter, confidence = 0.85) {
if (inCooldown) return;
const l = letter.toLowerCase();
if (l === 'space' || l === '_') { pushWord(); return; }
if (l === 'del' || l === 'delete') {
currentWord = currentWord.slice(0, -1);
letterConfidences.pop();
renderWord();
resetStreak();
lastCapturedLetter = '';
releasedSinceLastCapture = true;
return;
}
if (l === 'nothing') return;
currentWord += letter.toUpperCase();
letterConfidences.push(confidence);
renderWord();
lastCapturedLetter = letter.toUpperCase();
releasedSinceLastCapture = false;
releaseFrames = 0;
detectedLetter.classList.remove('flash');
void detectedLetter.offsetWidth;
detectedLetter.classList.add('flash');
resetStreak();
noHandCount = 0;
inCooldown = true;
setTimeout(() => { inCooldown = false; }, COOLDOWN_MS);
}
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโ Landmark Neural Network Classifier โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/** 15 finger flexion triplets (vertex is the middle index) */
const ANGLE_TRIPLETS = [
[0,1,2], [1,2,3], [2,3,4],
[0,5,6], [5,6,7], [6,7,8],
[0,9,10], [9,10,11], [10,11,12],
[0,13,14], [13,14,15], [14,15,16],
[0,17,18], [17,18,19], [18,19,20],
];
/** Angle at vertex b formed by a-b-c, in radians normalized to [0,1] */
function calculateAngle3D(a, b, c) {
const bax = a[0]-b[0], bay = a[1]-b[1], baz = a[2]-b[2];
const bcx = c[0]-b[0], bcy = c[1]-b[1], bcz = c[2]-b[2];
const dot = bax*bcx + bay*bcy + baz*bcz;
const nba = Math.sqrt(bax*bax + bay*bay + baz*baz);
const nbc = Math.sqrt(bcx*bcx + bcy*bcy + bcz*bcz);
const cos = Math.min(1, Math.max(-1, dot / (nba*nbc + 1e-6)));
return Math.acos(cos) / Math.PI;
}
/**
* Builds the 78-D feature vector the MLP was trained on:
* 63 aspect-corrected, wrist-centred, palm-scaled, rotation-aligned coords
* + 15 finger flexion angles.
*
* Mirrors train_landmark_classifier.extract_features_from_image() exactly,
* including its rotation convention. Do not "fix" the rotation here alone --
* the shipped weights were trained with it (see notes).
*/
function normalizeLandmarks(lm, w, h, handedness = "Right", applyHandednessMirror = false) {
w = w || video.videoWidth || 640;
h = h || video.videoHeight || 480;
// Aspect-ratio corrected pixel space: (x*w, y*h, z*w)
const pts = lm.map(p => [p.x * w, p.y * h, p.z * w]);
// Mirror Left hand to match Right hand dataset distribution (ASL single hand)
if (applyHandednessMirror && handedness === "Left") {
const wristX = pts[0][0];
pts.forEach(p => {
p[0] = wristX - (p[0] - wristX);
});
}
// Centre on the wrist
const wrist = pts[0];
const cen = pts.map(p => [p[0]-wrist[0], p[1]-wrist[1], p[2]-wrist[2]]);
// Palm scale = 2D wrist -> middle MCP distance
let scale = Math.sqrt(cen[9][0]*cen[9][0] + cen[9][1]*cen[9][1]);
if (scale < 1e-4) scale = 1;
// 2D rotation keyed on landmark 9 against the negative Y axis
const angle = Math.atan2(cen[9][0]/scale, -cen[9][1]/scale);
const ca = Math.cos(angle), sa = Math.sin(angle);
const features = [];
// ISL uses the mathematically correct rotation matrix [[cos, -sin], [sin, cos]]
// that aligns landmark 9 to vertical 12 o'clock, cancelling any hand tilt.
const isIslMode = (typeof currentMode !== 'undefined' && currentMode === 'isl');
cen.forEach(p => {
const x = p[0]/scale, y = p[1]/scale;
if (isIslMode) {
features.push(x*ca + y*sa);
features.push(-x*sa + y*ca);
} else {
// ASL legacy rotation
features.push(x*ca - y*sa);
features.push(x*sa + y*ca);
}
features.push(p[2]/scale); // z is scaled but not rotated
});
// Angles come from the raw pixel points, not the normalized ones
ANGLE_TRIPLETS.forEach(([i, j, k]) =>
features.push(calculateAngle3D(pts[i], pts[j], pts[k]))
);
return features; // 63 + 15 = 78
}
/** Matrix multiplication helper */
function matMul(input, weights, bias) {
const output = [];
const numOutputs = bias.length;
const numInputs = input.length;
for (let j = 0; j < numOutputs; j++) {
let sum = bias[j];
for (let i = 0; i < numInputs; i++) {
sum += input[i] * weights[i][j];
}
output.push(sum);
}
return output;
}
/** ReLU activation function */
function relu(arr) {
return arr.map(x => Math.max(0, x));
}
/** Softmax activation function */
function softmax(arr) {
const max = Math.max(...arr);
const exps = arr.map(x => Math.exp(x - max));
const sum = exps.reduce((a, b) => a + b, 0);
return exps.map(x => x / sum);
}
/**
* Probes /health to find out whether the Flask backend is up.
* Called once at startup and retried whenever a classify() call fails.
*/
async function probeServer() {
if (serverCheckPending) return;
serverCheckPending = true;
try {
const r = await fetch('/health', { signal: AbortSignal.timeout(1500) });
if (r.ok) {
if (!serverAvailable) {
serverAvailable = true;
console.log('โ
Flask backend detected โ using server-side inference');
setStatus('ready', 'Connected');
}
} else {
serverAvailable = false;
}
} catch {
serverAvailable = false;
} finally {
serverCheckPending = false;
// If server is currently offline, automatically retry in 2.5s
if (!serverAvailable && cameraActive) {
setTimeout(probeServer, 2500);
}
}
}
/** Load MLP weights from JSON files (used for OFFLINE fallback only) */
async function loadLandmarkModel() {
try {
const resAsl = await fetch('asl_landmarks_weights.json');
if (resAsl.ok) {
aslWeights = await resAsl.json();
console.log('๐ง ASL Neural Network loaded (offline fallback)');
}
const resIsl = await fetch('isl_landmarks_weights.json');
if (resIsl.ok) {
islWeights = await resIsl.json();
console.log('๐ง ISL Neural Network loaded (offline fallback)');
}
currentWeights = currentMode === 'asl' ? aslWeights : islWeights;
} catch (err) {
console.error('Failed to load MLP weights:', err);
}
}
/**
* Assembles the 78-D (single-hand) or 156-D (dual-hand) feature vector.
*
* Sorting is on the RAW wrist x of the unflipped frame, identical to
* run_native.extract_landmarks(). If these two ever disagree, every
* two-handed sign silently decodes to the wrong letter.
*/
function buildFeatureVector(multiHandLandmarks, isDualMode, multiHandedness, w, h) {
if (!isDualMode) {
const handedness = (multiHandedness && multiHandedness[0] && multiHandedness[0].label)
? multiHandedness[0].label
: 'Right';
// In ASL single hand mode, mirror Left hands to match Right hand dataset
return normalizeLandmarks(multiHandLandmarks[0], w, h, handedness, true);
}
// Dual mode (ISL):
// Single-hand ISL model is trained on BOTH Left & Right hands natively,
// and two-handed classes strictly require both hands.
// No fragile handedness guessing/mirroring is needed.
const hands = multiHandLandmarks
.map(lm => ({ x: lm[0].x, feat: normalizeLandmarks(lm, w, h, 'Right', false) }))
.sort((a, b) => a.x - b.x);
const slot1 = hands[0].feat;
const slot2 = hands.length > 1 ? hands[1].feat : new Array(78).fill(0);
return slot1.concat(slot2);
}
// Helper to check if hand landmarks represent a valid, non-ghost hand
function isValidHand(lm) {
if (!lm || lm.length < 21) return false;
const w = displayCanvas.width || 640;
const h = displayCanvas.height || 480;
// Wrist (0) to Middle MCP (9) distance in pixels
const dx = (lm[9].x - lm[0].x) * w;
const dy = (lm[9].y - lm[0].y) * h;
const span = Math.sqrt(dx * dx + dy * dy);
// Reject tiny noise clusters / background artifacts
if (span < MIN_HAND_SPAN) return false;
// Check landmark coordinates are reasonably within frame [-0.2, 1.2]
for (let i = 0; i < lm.length; i++) {
if (isNaN(lm[i].x) || isNaN(lm[i].y)) return false;
if (lm[i].x < -0.2 || lm[i].x > 1.2 || lm[i].y < -0.2 || lm[i].y > 1.2) return false;
}
return true;
}
/**
* JS MLP fallback โ used ONLY when Flask server is unreachable.
* Runs the MLP forward pass in-browser using the cached weight JSON.
*/
function classifyJS(featureVector) {
if (!currentWeights) return { letter: 'nothing', confidence: 0.0 };
const x = featureVector;
if (x.length !== currentWeights.w0.length) {
return { letter: 'nothing', confidence: 0.0 };
}
let h = relu(matMul(x, currentWeights.w0, currentWeights.b0));
h = relu(matMul(h, currentWeights.w1, currentWeights.b1));
if (currentWeights.w2 && currentWeights.b2) {
if (currentWeights.w3 && currentWeights.b3) {
h = relu(matMul(h, currentWeights.w2, currentWeights.b2));
h = matMul(h, currentWeights.w3, currentWeights.b3);
} else {
h = matMul(h, currentWeights.w2, currentWeights.b2);
}
}
let probs = softmax(h);
// โโ ISL Hand-Count Constrained Gating โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
if (currentMode === 'isl' && x.length === 156) {
const isOneHand = x.slice(78).every(v => Math.abs(v) < 1e-4);
const islSingleHand = new Set(['1', '2', '3', '4', '5', '6', '7', '8', '9', 'C', 'I', 'J', 'L', 'O', 'Q', 'U', 'V']);
for (let i = 0; i < probs.length; i++) {
const cls = currentWeights.classes[i];
if (isOneHand ? !islSingleHand.has(cls) : islSingleHand.has(cls)) {
probs[i] = 0;
}
}
const pSum = probs.reduce((a, b) => a + b, 0);
if (pSum > 0) {
probs = probs.map(p => p / pSum);
}
}
let maxIdx = 0, maxProb = 0, secondProb = 0;
for (let i = 0; i < probs.length; i++) {
if (probs[i] > maxProb) { secondProb = maxProb; maxProb = probs[i]; maxIdx = i; }
else if (probs[i] > secondProb) { secondProb = probs[i]; }
}
if ((maxProb - secondProb) < 0.08 && maxProb < 0.85) {
return { letter: 'nothing', confidence: maxProb };
}
return { letter: currentWeights.classes[maxIdx], confidence: maxProb };
}
/**
* PRIMARY classify() โ async.
*
* Strategy:
* 1. Build the feature vector in JS (normalization is correct and fast).
* 2. POST it to Flask /predict_landmarks โ uses sklearn's calibrated
* predict_proba(), identical to run_native.py. This is why signs that
* work in native Python also work in the browser.
* 3. If the server is unavailable, fall back to the JS MLP.
*/
async function classify(multiHandLandmarks, multiHandedness) {
if (!multiHandLandmarks || multiHandLandmarks.length === 0) {
return { letter: 'nothing', confidence: 0.0 };
}
// Determine if active model is dual-hand (156-D) or single-hand (78-D)
const isDualMode = currentWeights ? currentWeights.w0.length === 156 : false;
// Build feature vector with true display/camera aspect ratio
const cw = (displayCanvas && displayCanvas.width) || (video && video.videoWidth) || 640;
const ch = (displayCanvas && displayCanvas.height) || (video && video.videoHeight) || 480;
const featureVector = buildFeatureVector(multiHandLandmarks, isDualMode, multiHandedness, cw, ch);
// โโ PATH A: Server-side inference (preferred) โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
if (serverAvailable) {
try {
const response = await fetch('/predict_landmarks', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode: currentMode, landmarks: featureVector }),
signal: AbortSignal.timeout(1500), // 1500ms resilient timeout per frame
});
if (response.ok) {
const data = await response.json();
return {
letter: data.letter || 'nothing',
confidence: data.confidence || 0.0,
top3: data.top3 || [],
};
}
// Non-200 response โ server up but something is wrong
console.warn('[classify] Server error:', response.status);
return { letter: 'nothing', confidence: 0.0 };
} catch (err) {
// Timeout or network error โ mark server down and re-probe
console.warn('[classify] Server unreachable, switching to JS fallback:', err.name);
serverAvailable = false;
showToast('โ ๏ธ Server offline โ using JS fallback', 3000);
setStatus('loading', 'JS fallback');
probeServer(); // async retry in background
}
}
// โโ PATH B: JS MLP fallback โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
if (!currentWeights) return { letter: 'nothing', confidence: 0.0 };
return classifyJS(featureVector);
}
// โโ Process classification result โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
function processResult(letter, confidence) {
const conf = Math.round(confidence * 100);
detectedLetter.textContent = (letter === 'nothing' || confidence < MIN_CONFIDENCE)
? ''
: letter.toUpperCase();
detectedConf.textContent = letter === 'nothing'
? 'Unclear gesture'
: `${conf}% ยท ${letter.toUpperCase()}`;
const effective = (confidence >= MIN_CONFIDENCE && letter !== 'nothing') ? letter : null;
// Track release for repeating the same letter
if (!effective || effective !== lastCapturedLetter) {
releaseFrames++;
if (releaseFrames >= RELEASE_FRAMES_NEEDED) {
releasedSinceLastCapture = true;
}
} else {
releaseFrames = 0;
}
if (paused || inCooldown || !effective) {
if (!effective) resetStreak();
return;
}
// Prevent spamming the exact same letter repeatedly without releasing hand
if (effective.toUpperCase() === lastCapturedLetter && !releasedSinceLastCapture) {
resetStreak();
return;
}
noHandCount = 0;
if (effective === streakLetter) {
streakCount++;
} else {
streakLetter = effective;
streakCount = 1;
}
const pct = Math.min(100, Math.round((streakCount / STREAK_NEEDED) * 100));
setStreakVisual(pct);
streakLabel.textContent = `${Math.min(streakCount, STREAK_NEEDED)} / ${STREAK_NEEDED}`;
if (streakCount >= STREAK_NEEDED) {
captureLetter(streakLetter, confidence);
}
}
// (handLandmarker and animFrameId declared near initMediaPipe below)
// Prevent concurrent classify calls from piling up while a fetch is in flight
let classifyInFlight = false;
async function onResults(results) {
dctx.save();
dctx.clearRect(0, 0, displayCanvas.width, displayCanvas.height);
dctx.drawImage(results.image, 0, 0, displayCanvas.width, displayCanvas.height);
// Filter for genuine hands with valid size and geometry
const validHands = (results.multiHandLandmarks || []).filter(isValidHand);
if (validHands.length > 0) {
noHandOverlay.classList.remove('visible');
handBadge.className = 'hand-badge live';
if (currentMode === 'isl') {
handBadge.textContent = validHands.length > 1 ? '2 HANDS ยท ISL (A-Z)' : '1 HAND ยท ISL (1-9, C, I, L, O, U, V)';
} else {
handBadge.textContent = validHands.length > 1 ? '2 HANDS DETECTED' : 'HAND DETECTED';
}
validHands.forEach(drawSkeleton);
// Skip this frame if the previous classify() hasn't returned yet
// (avoids a queue of stale requests building up on slow networks)
if (!classifyInFlight) {
classifyInFlight = true;
try {
const res = await classify(validHands, results.multiHandedness);
processResult(res.letter, res.confidence);
} finally {
classifyInFlight = false;
}
}
} else {
noHandOverlay.classList.add('visible');
handBadge.className = 'hand-badge';
handBadge.textContent = 'NO HAND';
detectedLetter.textContent = '';
detectedConf.textContent = 'Waitingโฆ';
resetStreak();
// Hand was dropped/removed -> immediately grant release permission for next letter
releaseFrames++;
if (releaseFrames >= RELEASE_FRAMES_NEEDED) {
releasedSinceLastCapture = true;
}
if (currentWord) {
noHandCount++;
if (noHandCount >= SPACE_FRAMES) {
pushWord();
}
}
}
dctx.restore();
}
function drawSkeleton(lm) {
const w = displayCanvas.width;
const h = displayCanvas.height;
// Draw lines
CONNECTIONS.forEach(([i, j], idx) => {
const p1 = lm[i];
const p2 = lm[j];
dctx.beginPath();
dctx.moveTo(p1.x * w, p1.y * h);
dctx.lineTo(p2.x * w, p2.y * h);
dctx.strokeStyle = EDGE_COLORS[idx] || '#6a6a76'; // arrays are aligned; neutral if ever not
dctx.lineWidth = 3;
dctx.lineCap = 'round';
dctx.stroke();
});
// Draw points
lm.forEach((p, i) => {
const x = p.x * w;
const y = p.y * h;
dctx.beginPath();
dctx.arc(x, y, i === 0 ? 7 : 5, 0, 2 * Math.PI);
dctx.fillStyle = NODE_COLORS[i] || '#ffffff';
dctx.fill();
dctx.strokeStyle = '#ffffff';
dctx.lineWidth = 1.5;
dctx.stroke();
});
}
/**
* Renders a styled, in-theme camera failure inside the camera panel.
* Replaces the native alert() MediaPipe would otherwise raise.
*/
function showCameraError(err) {
const name = (err && err.name) ? err.name : 'Error';
const HINTS = {
NotReadableError: 'Another application is already using the camera. Close it (video call, another browser tab, your editor\u2019s preview pane) and reload.',
NotAllowedError: 'Camera permission was denied. Allow camera access for this site, then reload.',
NotFoundError: 'No camera device was found on this machine.',
NotSupportedError: 'This browser cannot access a camera on this page. A secure origin (https:// or localhost) is required.',
OverconstrainedError: 'No camera matches the requested 640\u00d7480 video mode.',
AbortError: 'The camera was released before it could start. Reload to retry.',
};
const msg = HINTS[name] || (err && err.message) || 'The camera could not be started.';
noHandOverlay.innerHTML =
'<div class="cam-error-icon" aria-hidden="true">\u26A0</div>' +
'<div class="cam-error-title">Camera unavailable</div>' +
'<div class="cam-error-msg"></div>' +
'<div class="cam-error-code"></div>';
// textContent, not innerHTML -- the error string is not ours to trust as markup
noHandOverlay.querySelector('.cam-error-msg').textContent = msg;
noHandOverlay.querySelector('.cam-error-code').textContent = name;
noHandOverlay.classList.add('error');
noHandOverlay.classList.remove('hidden');
noHandOverlay.setAttribute('role', 'alert');
setStatus('err', 'Camera unavailable');
detectedLetter.textContent = '';
detectedConf.textContent = 'No camera';
console.error('[SignLens] camera init failed:', err);
}
// โโ MediaPipe Tasks Vision Camera Loop โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
let handLandmarker = null;
let animFrameId = null;
/**
* Converts new Tasks Vision HandLandmarker results into the same shape
* the rest of app.js expects:
* multiHandLandmarks: Array of [{x,y,z}, ...21] (same as old API)
* multiHandedness: Array of {label: 'Right'|'Left'} (same field name)
*/
function adaptResults(result) {
const rawLandmarks = result.landmarks || [];
const rawHandedness = result.handedness || [];
const multiHandLandmarks = [];
const multiHandedness = [];
for (let i = 0; i < rawLandmarks.length; i++) {
const lms = rawLandmarks[i];
if (!lms || lms.length < 21) continue;
// Anatomical validation:
// Rejects facial false positives while fully supporting profile/curled hand signs like 'O', 'C', 'E', 'S'
const palmLen = Math.hypot(lms[9].x - lms[0].x, lms[9].y - lms[0].y);
const totalSpan = Math.max(...lms.map(p => Math.hypot(p.x - lms[0].x, p.y - lms[0].y)));
if (palmLen < 0.03 || totalSpan < 0.06) {
continue;
}
multiHandLandmarks.push(lms);
const h = rawHandedness[i];
multiHandedness.push({
label: (h && h[0] && h[0].categoryName) ? h[0].categoryName : 'Right'
});
}
return { multiHandLandmarks, multiHandedness };
}
async function initMediaPipe() {
// Probe getUserMedia first so we can show a styled error instead of a
// native alert() on failure.
try {
const probe = await navigator.mediaDevices.getUserMedia({
video: { width: 640, height: 480 }
});
probe.getTracks().forEach(t => t.stop());
} catch (err) {
showCameraError(err);
return false;
}
// Dynamically import the Tasks Vision ES-module bundle.
// More reliable than a <script> UMD tag: exports land directly in scope,
// no window.* namespace hunting required.
const { FilesetResolver, HandLandmarker } = await import(
'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.14/vision_bundle.mjs'
);
// Resolve WASM files from the same CDN version
const vision = await FilesetResolver.forVisionTasks(
'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.14/wasm'
);
handLandmarker = await HandLandmarker.createFromOptions(vision, {
baseOptions: {
// Same hand_landmarker model as Python's hand_landmarker.task โ identical coordinate space
modelAssetPath: 'https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task',
delegate: 'GPU',
},
runningMode: 'VIDEO',
numHands: 2,
minHandDetectionConfidence: 0.25,
minHandPresenceConfidence: 0.25,
minTrackingConfidence: 0.25,
});
// Start camera stream
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia({
video: { width: 640, height: 480, facingMode: 'user' }
});
} catch (err) {
showCameraError(err);
return false;
}
video.srcObject = stream;
await new Promise(resolve => { video.onloadedmetadata = resolve; });
video.play();
cameraActive = true;
setStatus('ready', 'Connected');
// Detection loop using requestAnimationFrame for smooth 30fps
let lastVideoTime = -1;
function detect() {
if (!cameraActive) { animFrameId = null; return; }
animFrameId = requestAnimationFrame(detect);
if (video.currentTime === lastVideoTime) return; // no new frame yet
lastVideoTime = video.currentTime;
displayCanvas.width = video.videoWidth || 640;
displayCanvas.height = video.videoHeight || 480;
// detectForVideo uses the video timestamp in ms for temporal smoothing
const result = handLandmarker.detectForVideo(video, performance.now());
const adapted = adaptResults(result);
// Synthesise a results object matching what onResults() already expects
onResults({
image: video,
multiHandLandmarks: adapted.multiHandLandmarks,
multiHandedness: adapted.multiHandedness,
});
}
detect();
return true;
}
// โโ Controls Setup โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
function setupControls() {
document.getElementById('btn-backspace').addEventListener('click', () => {
currentWord = currentWord.slice(0, -1);
letterConfidences.pop();
renderWord();
resetStreak();
});
document.getElementById('btn-add-space').addEventListener('click', () => {
pushWord();
});
document.getElementById('btn-clear-word').addEventListener('click', () => {
currentWord = '';
letterConfidences = [];
renderWord();
resetStreak();
});
document.getElementById('btn-clear-sentence').addEventListener('click', () => {
sentenceWords = [];
currentWord = '';
letterConfidences = [];
renderWord();
renderSentence();
resetStreak();
});
document.getElementById('btn-pause-detection').addEventListener('click', function() {
paused = !paused;
this.textContent = paused ? 'Resume' : 'Pause';
this.classList.toggle('active-btn', paused);
});
document.getElementById('btn-camera-toggle').addEventListener('click', function() {
cameraActive = !cameraActive;
this.textContent = cameraActive ? 'Stop Camera' : 'Start Camera';
this.classList.toggle('active-btn', !cameraActive);
if (!cameraActive && animFrameId) {
cancelAnimationFrame(animFrameId);
animFrameId = null;
} else if (cameraActive && !animFrameId && handLandmarker) {
// restart loop
let lastVideoTime = -1;
function detect() {
if (!cameraActive) { animFrameId = null; return; }
animFrameId = requestAnimationFrame(detect);
if (video.currentTime === lastVideoTime) return;
lastVideoTime = video.currentTime;
displayCanvas.width = video.videoWidth || 640;
displayCanvas.height = video.videoHeight || 480;
const result = handLandmarker.detectForVideo(video, performance.now());
const adapted = adaptResults(result);
onResults({ image: video, multiHandLandmarks: adapted.multiHandLandmarks, multiHandedness: adapted.multiHandedness });
}
detect();
}
});
document.getElementById('btn-copy').addEventListener('click', () => {
if (sentenceWords.length) {
navigator.clipboard.writeText(sentenceWords.join(' '));
showToast('๐ Copied to clipboard!');
}
});
// Global reference to prevent Chrome garbage-collection bug on SpeechSynthesisUtterance
window._activeUtterance = null;
function fallbackServerSpeak(text, btn) {
fetch('/speak', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text })
}).then(res => res.json())
.then(data => {
console.log('[SignLens] Server TTS spoke:', data);
})
.catch(err => console.error('[SignLens] Server TTS failed:', err))
.finally(() => {
if (btn) {
btn.classList.remove('active');
btn.textContent = 'Speak';
}
});
}
function speakSentence() {
const text = (sentenceWords.length
? sentenceWords.join(' ')
: (sentenceDisplay.innerText || '').replace(/Your sentence will appear here[โฆ\.]*/i, '')
).trim();
if (!text) {
showToast('โ ๏ธ No sentence to speak yet');
return;
}
const btnSpeak = document.getElementById('btn-speak');
if (btnSpeak) {
btnSpeak.classList.add('active');
btnSpeak.textContent = 'Speakingโฆ';
}
showToast(`๐ Speaking: "${text}"`);
if ('speechSynthesis' in window) {
try {
window.speechSynthesis.cancel(); // Reset stuck Chromium speech queue
const u = new SpeechSynthesisUtterance(text);
window._activeUtterance = u; // Keep reference to prevent V8 GC drop
u.lang = 'en-US';
u.rate = 0.95;
u.pitch = 1.0;
u.volume = 1.0;
const voices = window.speechSynthesis.getVoices();
if (voices && voices.length > 0) {
const enVoice = voices.find(v => v.lang.startsWith('en') && !v.localService) ||
voices.find(v => v.lang.startsWith('en')) ||
voices[0];
if (enVoice) u.voice = enVoice;
}
u.onend = () => {
window._activeUtterance = null;
if (btnSpeak) {
btnSpeak.classList.remove('active');
btnSpeak.textContent = 'Speak';
}
};
u.onerror = (e) => {
console.warn('[SignLens] Browser speech error, falling back to server TTS:', e);
window._activeUtterance = null;
fallbackServerSpeak(text, btnSpeak);
};
window.speechSynthesis.speak(u);
if (window.speechSynthesis.paused) {
window.speechSynthesis.resume();
}
// Safety timeout to reset button state after utterance
setTimeout(() => {
if (btnSpeak && btnSpeak.textContent === 'Speakingโฆ') {
btnSpeak.classList.remove('active');
btnSpeak.textContent = 'Speak';
}
}, Math.max(3000, text.split(' ').length * 1200));
} catch (err) {
console.warn('[SignLens] SpeechSynthesis exception:', err);
fallbackServerSpeak(text, btnSpeak);
}
} else {
fallbackServerSpeak(text, btnSpeak);
}
}
document.getElementById('btn-speak').addEventListener('click', speakSentence);
// Mode buttons
const btnAsl = document.getElementById('btn-asl');
const btnIsl = document.getElementById('btn-isl');
const btnVisually = document.getElementById('btn-visually');
const liveWorkspace = document.getElementById('live-workspace');
const visuallyWorkspace = document.getElementById('visually-workspace');
function isInVisuallyMode() {
return visuallyWorkspace && !visuallyWorkspace.classList.contains('hidden');
}
btnAsl.addEventListener('click', () => {
currentMode = 'asl';
currentWeights = aslWeights;
btnAsl.classList.add('active');
btnIsl.classList.remove('active');
if (btnVisually) btnVisually.classList.remove('active');
modeToggle.classList.remove('isl-mode', 'visually-mode');
if (liveWorkspace) liveWorkspace.classList.remove('hidden');
if (visuallyWorkspace) visuallyWorkspace.classList.add('hidden');
resetStreak();
showToast('Switched to ASL (Live Camera)');
});
btnIsl.addEventListener('click', () => {
currentMode = 'isl';
currentWeights = islWeights;
btnIsl.classList.add('active');
btnAsl.classList.remove('active');
if (btnVisually) btnVisually.classList.remove('active');
modeToggle.classList.remove('visually-mode');
modeToggle.classList.add('isl-mode');
if (liveWorkspace) liveWorkspace.classList.remove('hidden');
if (visuallyWorkspace) visuallyWorkspace.classList.add('hidden');
resetStreak();
showToast('Switched to ISL (Live Camera)');
});
if (btnVisually) {
btnVisually.addEventListener('click', () => {
btnVisually.classList.add('active');
btnAsl.classList.remove('active');
btnIsl.classList.remove('active');
modeToggle.classList.remove('isl-mode');
modeToggle.classList.add('visually-mode');
if (liveWorkspace) liveWorkspace.classList.add('hidden');
if (visuallyWorkspace) visuallyWorkspace.classList.remove('hidden');
activatePracticeStudio();
showToast('Practice Studio Active');
});
}
// Settings sheet. Both thresholds are read live by processResult(),
// so no restart is needed after a change.
const setConf = document.getElementById('set-confidence');
const outConf = document.getElementById('out-confidence');
const setStreak = document.getElementById('set-streak');
const outStreak = document.getElementById('out-streak');
const setTimeoutInput = document.getElementById('set-timeout');
const outTimeout = document.getElementById('out-timeout');
setConf.value = Math.round(MIN_CONFIDENCE * 100);
outConf.value = `${setConf.value}%`;
setStreak.value = STREAK_NEEDED;
outStreak.value = STREAK_NEEDED;
if (setTimeoutInput && outTimeout) {
setTimeoutInput.value = (SPACE_FRAMES / 30).toFixed(1);
outTimeout.value = `${setTimeoutInput.value}s`;
}
setConf.addEventListener('input', () => {
MIN_CONFIDENCE = Number(setConf.value) / 100;
outConf.value = `${setConf.value}%`;
});
setStreak.addEventListener('input', () => {
STREAK_NEEDED = Number(setStreak.value);
outStreak.value = STREAK_NEEDED;
resetStreak(); // rescale the dial against the new target
});
if (setTimeoutInput && outTimeout) {
setTimeoutInput.addEventListener('input', () => {
const sec = Number(setTimeoutInput.value);
SPACE_FRAMES = Math.round(sec * 30);
outTimeout.value = `${sec.toFixed(1)}s`;
});
}
// Theme Toggle (Light / Dark Mode)
const btnThemeToggle = document.getElementById('btn-theme-toggle');
const iconThemeToggle = document.getElementById('theme-toggle-icon');
function applyTheme(theme) {
const isLight = theme === 'light';
document.documentElement.setAttribute('data-theme', isLight ? 'light' : 'dark');
localStorage.setItem('signlens_theme', isLight ? 'light' : 'dark');
if (iconThemeToggle) {
iconThemeToggle.textContent = isLight ? '๐' : 'โ๏ธ';
}
if (btnThemeToggle) {
btnThemeToggle.setAttribute('title', isLight ? 'Switch to Dark Mode' : 'Switch to Light Mode');
btnThemeToggle.setAttribute('aria-label', isLight ? 'Switch to Dark Mode' : 'Switch to Light Mode');
}
// Re-render avatar if in practice mode so canvas background updates immediately
if (typeof drawAvatar === 'function') {
try { drawAvatar(); } catch (_) {}
}
}
// Load saved preference or fallback to dark
const savedTheme = localStorage.getItem('signlens_theme') || 'dark';
applyTheme(savedTheme);
if (btnThemeToggle) {
btnThemeToggle.addEventListener('click', () => {
const currentTheme = document.documentElement.getAttribute('data-theme') || 'dark';
const nextTheme = currentTheme === 'light' ? 'dark' : 'light';
applyTheme(nextTheme);
showToast(nextTheme === 'light' ? 'โ๏ธ Switched to Light Mode' : '๐ Switched to Dark Mode');
});
}
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
// Ignore shortcuts while a control has focus, or a sheet is open.
if (e.target.closest('input, textarea, [popover]')) return;
if (e.key === ' ' || e.code === 'Space') {
e.preventDefault();
pushWord();
} else if (e.key === 'Backspace') {
currentWord = currentWord.slice(0, -1);
letterConfidences.pop();
renderWord();
} else if (e.key === '1') {
btnAsl.click();
} else if (e.key === '2') {
btnIsl.click();
} else if (e.key === '3') {
if (btnVisually) btnVisually.click();
}
});
}
// โโ Sign Reference Guide Modal โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโ Sign Reference Guide Modal โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
function initSignGuide() {
const panelGuide = document.getElementById('panel-guide');
const btnOpenGuide = document.getElementById('btn-open-guide');
const btnCloseGuide = document.getElementById('btn-close-guide');
const tabIsl = document.getElementById('tab-guide-isl');
const tabAsl = document.getElementById('tab-guide-asl');
const contentIsl = document.getElementById('guide-content-isl');
const contentAsl = document.getElementById('guide-content-asl');
const singleGrid = document.getElementById('isl-single-cards');
const dualGrid = document.getElementById('isl-dual-cards');
const islDescFallback = {
'1': 'Index finger extended upwards',
'2': 'Index and middle fingers extended in V-shape',
'3': 'Thumb, index, and middle fingers extended',
'4': 'Four fingers extended upwards',
'5': 'Open hand with all five fingers spread',
'6': 'Thumb and little finger extended',
'7': 'Thumb, index, and little finger extended',
'8': 'Middle, ring, and little fingers extended',
'9': 'Thumb touching index finger in circle',
'C': 'Curved hand forming C-shape',
'I': 'Little finger extended upwards',
'L': 'Thumb and index finger forming L-shape',
'O': 'All fingers curved touching thumb in O-shape',
'U': 'Index and middle fingers held together vertically',
'V': 'Index and middle fingers in open V-shape',
'A': 'Dominant index finger touching non-dominant thumb tip',
'B': 'Both hands forming double circles / glasses pose',
'D': 'Dominant index pointing to non-dominant index forming D',
'E': 'Left hand curved C/horizontal, right index touching middle knuckle',
'F': 'Dominant index and middle crossing non-dominant index and middle',
'G': 'Both fists held together vertically with knuckles facing forward',
'H': 'Dominant open palm sweeping flat across non-dominant palm',
'J': 'Index finger drawing J stroke across non-dominant palm',
'K': 'Dominant index finger hooking over non-dominant index finger',
'M': 'Dominant three fingers laid across non-dominant palm',
'N': 'Dominant two fingers laid across non-dominant palm',
'P': 'Dominant index finger forming circle with thumb touching non-dominant tip',
'Q': 'Dominant hand forming circle loop with non-dominant index through',
'R': 'Dominant index finger hooked on non-dominant palm',
'S': 'Dominant pinky hooking non-dominant pinky / fist lock',
'T': 'Dominant index finger placed perpendicularly on non-dominant index side',
'W': 'Interlocking open fingers of both hands upright',
'X': 'Crossing both index fingers in an X',
'Y': 'Dominant index pointing between non-dominant thumb and index',
'Z': 'Dominant open palm held upright against non-dominant palm'
};
function createGuideCard(letter, isTwoHanded, desc) {
const el = document.createElement('div');
el.className = 'guide-card';
el.title = `${letter}: ${desc} (click to enlarge)`;
el.dataset.letter = letter;
el.dataset.hands = isTwoHanded ? '2' : '1';
el.dataset.desc = desc;
el.dataset.lang = 'ISL';
el.dataset.imgSrc = `isl_signs/${letter}.png`;
el.innerHTML = `
<div class="guide-card-img-wrap">
<img src="isl_signs/${letter}.png" alt="Sign ${letter}" loading="lazy" />
</div>
<div class="guide-card-body">
<span class="guide-card-char">${letter}</span>
<span class="guide-card-hands ${isTwoHanded ? 'pill-blue' : 'pill-amber'} pill-badge">${isTwoHanded ? '2 Hands' : '1 Hand'}</span>
</div>
<p class="guide-card-desc" style="padding: 6px 10px 10px; font-size: 0.72rem; color: var(--text-dim); line-height: 1.35; margin: 0;">${desc}</p>
`;
el.addEventListener('click', () => openSignLightbox(el));
return el;
}
function renderGuideCards() {
if (!singleGrid || !dualGrid) return;
singleGrid.innerHTML = '';
dualGrid.innerHTML = '';
const isl = (practiceTemplates && practiceTemplates.isl) ? practiceTemplates.isl : {};
const singleKeys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'C', 'I', 'L', 'O', 'U', 'V'];
const dualKeys = ['A', 'B', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'W', 'X', 'Y', 'Z'];
singleKeys.forEach(k => {
const desc = (isl[k] && isl[k].desc) ? isl[k].desc : (islDescFallback[k] || 'Single hand sign');
singleGrid.appendChild(createGuideCard(k, false, desc));
});
dualKeys.forEach(k => {
const desc = (isl[k] && isl[k].desc) ? isl[k].desc : (islDescFallback[k] || 'Dual hand sign');
dualGrid.appendChild(createGuideCard(k, true, desc));
});
}
const aslDescFallback = {
'A': 'Fist with thumb on side', 'B': 'All fingers together pointing up',
'C': 'Curved hand in C-shape', 'D': 'Index up, fingers curve to thumb',
'E': 'Fingers bent, thumb tucked', 'F': 'Index-thumb circle, three fingers up',
'G': 'Index and thumb point sideways', 'H': 'Two fingers point sideways',
'I': 'Pinky finger up', 'J': 'Pinky draws J in air',
'K': 'Index up, middle angled, thumb out', 'L': 'L-shape โ thumb and index',
'M': 'Three fingers over thumb', 'N': 'Two fingers over thumb',
'O': 'All fingers curve to form O', 'P': 'K shape pointing down',
'Q': 'G shape pointing down', 'R': 'Two fingers crossed',
'S': 'Fist with thumb over fingers', 'T': 'Thumb between index and middle',
'U': 'Two fingers together pointing up', 'V': 'Two fingers spread in V',
'W': 'Three fingers spread out', 'X': 'Index finger hooks',
'Y': 'Thumb and pinky out', 'Z': 'Index draws Z in air'
};
function renderAslCards() {
const aslGrid = document.getElementById('asl-cards');
if (!aslGrid || aslGrid.children.length > 0) return; // render once
aslGrid.innerHTML = '';
const aslLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
aslLetters.forEach(letter => {
const desc = aslDescFallback[letter] || 'ASL hand sign';
const el = document.createElement('div');
el.className = 'guide-card';
el.title = `${letter}: ${desc} (click to enlarge)`;
el.dataset.letter = letter;
el.dataset.hands = '1';
el.dataset.desc = desc;
el.dataset.lang = 'ASL';
el.dataset.imgSrc = `asl_signs/${letter}.png`;
el.innerHTML = `
<div class="guide-card-img-wrap">
<img src="asl_signs/${letter}.png" alt="ASL Sign ${letter}" loading="lazy" />
</div>
<div class="guide-card-body">
<span class="guide-card-char">${letter}</span>
<span class="guide-card-hands pill-amber pill-badge">1 Hand</span>
</div>
<p class="guide-card-desc" style="padding: 6px 10px 10px; font-size: 0.72rem; color: var(--text-dim); line-height: 1.35; margin: 0;">${desc}</p>
`;
el.addEventListener('click', () => openSignLightbox(el));
aslGrid.appendChild(el);
});
}
function openGuide() {
renderGuideCards();
renderAslCards();
if (panelGuide) {
try {
if (panelGuide.showPopover) {
panelGuide.showPopover();
} else {
panelGuide.style.display = 'flex';
panelGuide.classList.add('open');
}
} catch (err) {
panelGuide.style.display = 'flex';
panelGuide.classList.add('open');
}
}
}
function closeGuide() {
if (panelGuide) {
try {
if (panelGuide.hidePopover) {
panelGuide.hidePopover();
} else {
panelGuide.style.display = 'none';
panelGuide.classList.remove('open');
}
} catch (err) {
panelGuide.style.display = 'none';
panelGuide.classList.remove('open');
}
}
}
if (panelGuide) {
// Synchronize inline display style with popover state
panelGuide.addEventListener('toggle', (e) => {
if (e.newState === 'open') {
panelGuide.style.display = 'flex';
panelGuide.classList.add('open');
} else {
panelGuide.style.display = 'none';
panelGuide.classList.remove('open');
}
});
// Ensure it starts closed and strictly hidden
panelGuide.style.display = 'none';
panelGuide.classList.remove('open');
}
const stageGuideBtn = document.getElementById('stage-guide-btn');
if (stageGuideBtn) {
stageGuideBtn.addEventListener('click', (e) => {
e.preventDefault();
openGuide();
});
}
if (btnOpenGuide) {
btnOpenGuide.addEventListener('click', (e) => {
e.preventDefault();
openGuide();
});
}
if (btnCloseGuide) {
btnCloseGuide.addEventListener('click', (e) => {
e.preventDefault();
closeGuide();
});
}
if (tabIsl && tabAsl && contentIsl && contentAsl) {
tabIsl.addEventListener('click', () => {
tabIsl.classList.add('active');
tabAsl.classList.remove('active');
tabIsl.setAttribute('aria-selected', 'true');
tabAsl.setAttribute('aria-selected', 'false');
contentIsl.classList.remove('hidden');
contentAsl.classList.add('hidden');
});
tabAsl.addEventListener('click', () => {
tabAsl.classList.add('active');
tabIsl.classList.remove('active');
tabAsl.setAttribute('aria-selected', 'true');
tabIsl.setAttribute('aria-selected', 'false');
contentAsl.classList.remove('hidden');
contentIsl.classList.add('hidden');
});
}
// โโ Sign Lightbox popup โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
const lightboxOverlay = document.getElementById('sign-lightbox-overlay');
const lightboxImg = document.getElementById('sign-lightbox-img');
const lightboxLetter = document.getElementById('sign-lightbox-letter');
const lightboxType = document.getElementById('sign-lightbox-type');
const lightboxDesc = document.getElementById('sign-lightbox-desc');
const lightboxLang = document.getElementById('sign-lightbox-lang');
const lightboxCloseBtn = document.getElementById('sign-lightbox-close');
function openSignLightbox(dataOrEl) {
if (!lightboxOverlay) return;
let letter = '?';
let hands = '1';
let desc = '';
let lang = 'ISL';
let imgSrc = '';
if (dataOrEl instanceof HTMLElement) {
letter = dataOrEl.dataset.letter || '?';
hands = dataOrEl.dataset.hands || '1';
desc = dataOrEl.dataset.desc || '';
lang = dataOrEl.dataset.lang || 'ISL';
imgSrc = dataOrEl.dataset.imgSrc || '';
} else if (typeof dataOrEl === 'object' && dataOrEl !== null) {
letter = dataOrEl.letter || '?';
hands = String(dataOrEl.hands || '1');
desc = dataOrEl.desc || '';
lang = dataOrEl.lang || 'ISL';
imgSrc = dataOrEl.imgSrc || '';
}
if (lightboxImg) lightboxImg.src = imgSrc;
if (lightboxLetter) lightboxLetter.textContent = `Sign: ${letter}`;
if (lightboxType) {
const isTwoHand = hands === '2';
lightboxType.textContent = isTwoHand ? 'โ๏ธ 2 Hands Required' : '๐ค 1 Hand Only';
lightboxType.className = `sign-lightbox-type ${isTwoHand ? 'two-hand' : 'one-hand'}`;
}
if (lightboxDesc) lightboxDesc.textContent = desc;
if (lightboxLang) lightboxLang.textContent = (lang.toUpperCase() === 'ASL') ? '๐บ๐ธ American Sign Language (ASL)' : '๐ฎ๐ณ Indian Sign Language (ISL)';
// Open natively in the browser Top Layer (above all popovers and dialogs)
if (typeof lightboxOverlay.showModal === 'function') {
if (!lightboxOverlay.open) {
lightboxOverlay.showModal();
}
} else {
lightboxOverlay.setAttribute('open', '');
}
}
function closeSignLightbox() {
if (!lightboxOverlay) return;
if (typeof lightboxOverlay.close === 'function') {
if (lightboxOverlay.open) {
lightboxOverlay.close();
}
} else {
lightboxOverlay.removeAttribute('open');
}
}
// Make openSignLightbox available globally for card click handlers
window.openSignLightbox = openSignLightbox;
// Close button
if (lightboxCloseBtn) {
lightboxCloseBtn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
closeSignLightbox();
});
}
// Click outside (on backdrop) to close dialog
if (lightboxOverlay) {
lightboxOverlay.addEventListener('click', (e) => {
if (e.target === lightboxOverlay) {
closeSignLightbox();
}
});
}
// ESC key natively closes <dialog>, but add safety handler
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && lightboxOverlay && lightboxOverlay.open) {
closeSignLightbox();
}
});
window._renderGuideCards = renderGuideCards;
window._openSignGuide = openGuide;
}
// โโ Startup โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
window.addEventListener('DOMContentLoaded', async () => {
displayCanvas.width = 640;
displayCanvas.height = 480;
// Wire controls FIRST: a camera failure must not leave every button dead.
setupControls();
initPracticeStudio();
initSignGuide();
setStatus('loading', 'Loadingโฆ');
try {
// 1. Probe for Flask backend (async, result used by classify())
probeServer();
// 2. Always load JS MLP weights for offline fallback
await loadLandmarkModel();
// 3. Start camera
await initMediaPipe();
} catch (err) {
showCameraError(err);
}
});
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// VISUALLY (PRACTICE STUDIO) IMPLEMENTATION
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
let practiceTemplates = { asl: {}, isl: {} };
let practiceDialect = 'asl'; // 'asl' | 'isl'
let practiceSpeed = 1.0; // 0.5 | 1.0 | 1.5
// Sequence and animation state
let practiceSequence = []; // e.g. ['H', 'I', ' ', 'B', 'A', 'B', 'Y']
let practiceCurrentIndex = 0;
let practiceIsPlaying = false;
let practiceStepStartTime = 0;
let practiceAnimFrameId = null;
// Poses for interpolation: arrays of 21 landmarks [x, y, z]
let practiceFromPose = null;
let practiceToPose = null;
let practiceCurrentPose = null;
// Default neutral resting pose (21 landmarks)
const NEUTRAL_REST_POSE = Array(21).fill(0).map((_, i) => {
if (i === 0) return [0, 0, 0];
const fingerIdx = Math.floor((i - 1) / 4);
const jointIdx = ((i - 1) % 4) + 1;
const xOffset = (fingerIdx - 2) * 0.18;
const yOffset = -0.35 * jointIdx;
return [xOffset, yOffset, 0];
});
function clone21(pts) {
if (!pts || !Array.isArray(pts)) return null;
return pts.map(pt => [pt[0], pt[1], pt[2] || 0]);
}
function normalizePose(raw) {
if (!raw) {
return {
twoHanded: false,
left: null,
right: clone21(NEUTRAL_REST_POSE),
wristL: [0.0, 0.0],
wristR: [0.0, 0.0],
desc: ''
};
}
if (Array.isArray(raw)) {
return {
twoHanded: false,
left: null,
right: clone21(raw),
wristL: [0.0, 0.0],
wristR: [0.0, 0.0],
desc: ''
};
}
return {
twoHanded: !!raw.twoHanded,
left: raw.left ? clone21(raw.left) : null,
right: raw.right ? clone21(raw.right) : clone21(NEUTRAL_REST_POSE),
wristL: raw.wristL ? [raw.wristL[0], raw.wristL[1]] : [0.0, 0.0],
wristR: raw.wristR ? [raw.wristR[0], raw.wristR[1]] : [0.0, 0.0],
desc: raw.desc || ''
};
}
function clonePose(pose) {
const norm = normalizePose(pose);
return {
twoHanded: norm.twoHanded,
left: clone21(norm.left),
right: clone21(norm.right),
wristL: [...norm.wristL],
wristR: [...norm.wristR],
desc: norm.desc
};
}
function initPracticeStudio() {
const canvas = document.getElementById('avatar-canvas');
if (!canvas) return;
const ctx = canvas.getContext('2d');
// 1. Fetch templates
fetch('/sign_templates.json?v=' + Date.now(), { cache: 'no-store' })
.then(res => {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
})
.then(data => {
practiceTemplates = data;
console.log('[PracticeStudio] Loaded sign templates:', Object.keys(data.asl || {}).length, 'ASL,', Object.keys(data.isl || {}).length, 'ISL');
// Set initial pose
practiceCurrentPose = clonePose(getTemplatePose('REST'));
drawAvatar();
const panelGuide = document.getElementById('panel-guide');
if (panelGuide && (panelGuide.matches(':popover-open') || panelGuide.classList.contains('open'))) {
if (window._renderGuideCards) window._renderGuideCards();
}
})
.catch(err => {
console.warn('[PracticeStudio] Failed to load sign_templates.json:', err);
});
// 2. DOM elements
const txtInput = document.getElementById('practice-input');
const charCount = document.getElementById('practice-char-count');
const btnMic = document.getElementById('btn-mic');
const micLabel = document.getElementById('mic-label');
const btnSpeakInput = document.getElementById('btn-speak-input');
const btnClearPractice = document.getElementById('btn-clear-practice');
const btnStartSign = document.getElementById('btn-start-sign');
const sequenceChipsContainer = document.getElementById('sequence-chips');
const seqCounter = document.getElementById('seq-counter');
const btnPracAsl = document.getElementById('btn-practice-asl');
const btnPracIsl = document.getElementById('btn-practice-isl');
const hudChar = document.getElementById('hud-letter-char');
const hudSub = document.getElementById('hud-letter-sub');
const hudCue = document.getElementById('hud-letter-cue');
const hudStatus = document.getElementById('avatar-hud-status');
const avatarStatusText = document.getElementById('avatar-status-text');
// Top-Right Sign Gesture Image Preview Reference
const signPreviewWrap = document.getElementById('avatar-sign-preview');
const signPreviewImg = document.getElementById('avatar-sign-img');
const signPreviewBadge = document.getElementById('avatar-sign-badge');
const signPreviewChar = document.getElementById('avatar-sign-char');
const signPreviewHands = document.getElementById('avatar-sign-hands');
const signPreviewDesc = document.getElementById('avatar-sign-desc');
if (signPreviewWrap) {
signPreviewWrap.addEventListener('click', () => {
if (signPreviewImg && signPreviewImg.dataset.letter) {
if (typeof openSignLightbox === 'function') {
openSignLightbox({
letter: signPreviewImg.dataset.letter,
hands: signPreviewImg.dataset.hands || '1',
desc: signPreviewImg.dataset.desc || '',
lang: signPreviewImg.dataset.lang || 'ISL',
imgSrc: signPreviewImg.src
});
}
}
});
}
const btnPrev = document.getElementById('btn-avatar-prev');
const btnPlayPause = document.getElementById('btn-avatar-playpause');
const btnNext = document.getElementById('btn-avatar-next');
const btnReplay = document.getElementById('btn-avatar-replay');
const scrubber = document.getElementById('avatar-scrubber');
// Resize canvas handler
function resizeCanvas() {
if (!canvas.parentElement) return;
const rect = canvas.parentElement.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
const w = Math.floor(rect.width);
const h = Math.floor(rect.height);
if (w > 0 && h > 0 && (canvas.width !== w * dpr || canvas.height !== h * dpr)) {
canvas.width = w * dpr;
canvas.height = h * dpr;
drawAvatar();
}
}
window.addEventListener('resize', resizeCanvas);
setTimeout(resizeCanvas, 100);
// Get template for a character
function getTemplatePose(char) {
const dict = practiceTemplates[practiceDialect] || practiceTemplates.asl || {};
const upper = String(char).toUpperCase();
if (dict[upper]) return normalizePose(dict[upper]);
if (dict['REST']) return normalizePose(dict['REST']);
return normalizePose(null);
}
const ASL_SAMPLES = ['HI', 'HELLO', 'THANK YOU', 'HOW ARE YOU', 'BABY'];
const ISL_SAMPLES = ['NAMASTE', 'A B C', '1 2 3', 'ONAM', 'INDIA'];
function updateSampleChips(samples) {
const chipsContainer = document.querySelector('.quick-samples');
if (!chipsContainer) return;
const chips = chipsContainer.querySelectorAll('.sample-chip');
chips.forEach((chip, idx) => {
if (samples[idx] !== undefined) {
chip.dataset.text = samples[idx];
chip.textContent = samples[idx];
chip.style.display = '';
} else {
chip.style.display = 'none';
}
});
}
// Dialect switch inside Practice
if (btnPracAsl && btnPracIsl) {
btnPracAsl.addEventListener('click', () => {
practiceDialect = 'asl';
btnPracAsl.classList.add('active');
btnPracIsl.classList.remove('active');
updateSampleChips(ASL_SAMPLES);
rebuildSequence(false);
showToast('Practice dialect: ASL');
});
btnPracIsl.addEventListener('click', () => {
practiceDialect = 'isl';
btnPracIsl.classList.add('active');
btnPracAsl.classList.remove('active');
updateSampleChips(ISL_SAMPLES);
rebuildSequence(false);
showToast('Practice dialect: ISL');
});
}
// Speed controls
document.querySelectorAll('.speed-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.speed-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
practiceSpeed = parseFloat(btn.dataset.speed) || 1.0;
});
});
// Quick sample chips
document.querySelectorAll('.sample-chip').forEach(chip => {
chip.addEventListener('click', () => {
const text = chip.dataset.text || '';
if (txtInput) {
txtInput.value = text;
updateCharCount();
}
rebuildSequence(true);
});
});
function updateCharCount() {
if (!txtInput || !charCount) return;
charCount.textContent = `${txtInput.value.length}/200`;
}
if (txtInput) {
txtInput.addEventListener('input', () => {
updateCharCount();
rebuildSequence(false);
});
txtInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
rebuildSequence(true);
}
});
}
if (btnClearPractice) {
btnClearPractice.addEventListener('click', () => {
if (txtInput) txtInput.value = '';
updateCharCount();
practiceSequence = [];
practiceCurrentIndex = 0;
pausePlayback();
renderSequenceChips();
updateHUD();
practiceCurrentPose = clonePose(getTemplatePose('REST'));
drawAvatar();
});
}
// Voice Speech-to-Text
if (btnMic) {
let recognition = null;
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
if (SpeechRecognition) {
recognition = new SpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.lang = 'en-US';
recognition.onstart = () => {
btnMic.classList.add('listening');
if (micLabel) micLabel.textContent = 'Listeningโฆ';
showToast('Speak now โ listeningโฆ');
};
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
if (txtInput) {
txtInput.value = transcript.toUpperCase();
updateCharCount();
rebuildSequence(true);
}
};
recognition.onerror = (event) => {
console.warn('[PracticeStudio] Speech recognition error:', event.error);
btnMic.classList.remove('listening');
if (micLabel) micLabel.textContent = 'Speak';
showToast('Voice error: ' + event.error);
};
recognition.onend = () => {
btnMic.classList.remove('listening');
if (micLabel) micLabel.textContent = 'Speak';
};
btnMic.addEventListener('click', () => {
try {
if (btnMic.classList.contains('listening')) {
recognition.stop();
} else {
recognition.start();
}
} catch (err) {
console.warn('[PracticeStudio] Speech start exception:', err);
}
});
} else {
btnMic.addEventListener('click', () => {
showToast('Speech recognition not supported in this browser. Please type.');
});
}
}
// TTS speak aloud
if (btnSpeakInput) {
btnSpeakInput.addEventListener('click', () => {
const text = (txtInput ? txtInput.value.trim() : '');
if (!text) {
showToast('Type some words to speak aloud.');
return;
}
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
const utter = new SpeechSynthesisUtterance(text);
utter.rate = 0.95;
window.speechSynthesis.speak(utter);
}
});
}
// Start Demonstration Button
if (btnStartSign) {
btnStartSign.addEventListener('click', () => {
rebuildSequence(true);
});
}
// Parse text into sequence of signs
function rebuildSequence(autoPlay = false) {
const raw = (txtInput ? txtInput.value : '').toUpperCase();
const cleanChars = [];
for (let i = 0; i < raw.length; i++) {
const ch = raw[i];
if ((ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')) {
cleanChars.push(ch);
} else if (ch === ' ' && cleanChars.length > 0 && cleanChars[cleanChars.length - 1] !== ' ') {
cleanChars.push(' ');
}
}
// Remove trailing space
if (cleanChars.length > 0 && cleanChars[cleanChars.length - 1] === ' ') {
cleanChars.pop();
}
practiceSequence = cleanChars;
practiceCurrentIndex = 0;
renderSequenceChips();
updateHUD();
if (practiceSequence.length === 0) {
practiceCurrentPose = clonePose(getTemplatePose('REST'));
drawAvatar();
return;
}
if (autoPlay) {
startPlayback();
} else {
jumpToStep(0);
}
}
function renderSequenceChips() {
if (!sequenceChipsContainer) return;
sequenceChipsContainer.innerHTML = '';
if (practiceSequence.length === 0) {
sequenceChipsContainer.innerHTML = '<span class="ph">Enter text above to preview gesture timelineโฆ</span>';
if (seqCounter) seqCounter.textContent = '0 / 0';
if (scrubber) scrubber.value = 0;
return;
}
if (seqCounter) {
seqCounter.textContent = `${practiceCurrentIndex + 1} / ${practiceSequence.length}`;
}
practiceSequence.forEach((char, idx) => {
const chip = document.createElement('button');
chip.className = 'sequence-chip' + (char === ' ' ? ' is-space' : '') + (idx === practiceCurrentIndex ? ' active' : '');
chip.textContent = (char === ' ' ? 'โฃ' : char);
chip.title = (char === ' ' ? 'Space (Rest pause)' : `Letter ${char}`);
chip.addEventListener('click', () => {
jumpToStep(idx);
});
sequenceChipsContainer.appendChild(chip);
});
if (scrubber) {
const pct = (practiceSequence.length > 1) ? (practiceCurrentIndex / (practiceSequence.length - 1)) * 100 : 0;
scrubber.value = pct;
}
}
function updateHUD() {
if (practiceSequence.length === 0) {
if (hudChar) hudChar.textContent = 'โ';
if (hudSub) hudSub.textContent = 'Waiting for input';
if (hudCue) { hudCue.style.display = 'none'; hudCue.textContent = ''; }
if (avatarStatusText) avatarStatusText.textContent = 'Ready';
if (hudStatus) hudStatus.classList.remove('playing');
if (signPreviewWrap) signPreviewWrap.style.display = 'none';
return;
}
const currChar = practiceSequence[practiceCurrentIndex];
if (hudChar) {
hudChar.textContent = (currChar === ' ' ? 'โฃ' : currChar);
}
const currPose = getTemplatePose(currChar === ' ' ? 'REST' : currChar);
const is2H = currPose.twoHanded;
const desc = currPose.desc;
if (hudSub) {
if (currChar === ' ') {
hudSub.textContent = `Word Boundary Pause (${practiceCurrentIndex + 1}/${practiceSequence.length})`;
} else {
const handTag = (practiceDialect === 'isl') ? (is2H ? ' โข Dual Hand (Two-Handed)' : ' โข Single Hand') : ' โข Single Hand';
hudSub.textContent = `${practiceDialect.toUpperCase()} Sign โข Step ${practiceCurrentIndex + 1} of ${practiceSequence.length}${handTag}`;
}
}
if (hudCue) {
if (desc && currChar !== ' ') {
hudCue.style.display = 'inline-flex';
hudCue.textContent = `${is2H ? '๐ Two-Handed: ' : 'โ '}${desc}`;
} else {
hudCue.style.display = 'none';
hudCue.textContent = '';
}
}
if (avatarStatusText) {
avatarStatusText.textContent = practiceIsPlaying ? 'Demonstratingโฆ' : 'Paused';
}
if (hudStatus) {
if (practiceIsPlaying) hudStatus.classList.add('playing');
else hudStatus.classList.remove('playing');
}
// Update Top-Right Sign Gesture Image Preview Reference
if (signPreviewWrap) {
if (currChar && currChar !== ' ') {
const lang = (practiceDialect || 'isl').toLowerCase();
const imgSrc = (lang === 'asl') ? `asl_signs/${currChar}.png` : `isl_signs/${currChar}.png`;
if (signPreviewImg) {
signPreviewImg.src = imgSrc;
signPreviewImg.dataset.letter = currChar;
signPreviewImg.dataset.hands = is2H ? '2' : '1';
signPreviewImg.dataset.desc = desc || '';
signPreviewImg.dataset.lang = lang.toUpperCase();
}
if (signPreviewBadge) signPreviewBadge.textContent = lang.toUpperCase();
if (signPreviewChar) signPreviewChar.textContent = `Sign: ${currChar}`;
if (signPreviewHands) signPreviewHands.textContent = is2H ? '2 Hands' : '1 Hand';
if (signPreviewDesc) signPreviewDesc.textContent = desc || (is2H ? 'Dual-hand gesture' : 'Single-hand gesture');
signPreviewWrap.style.display = 'flex';
} else {
signPreviewWrap.style.display = 'none';
}
}
}
function jumpToStep(idx) {
if (practiceSequence.length === 0) return;
practiceCurrentIndex = Math.max(0, Math.min(idx, practiceSequence.length - 1));
const char = practiceSequence[practiceCurrentIndex];
practiceFromPose = practiceCurrentPose ? clonePose(practiceCurrentPose) : clonePose(getTemplatePose('REST'));
practiceToPose = clonePose(getTemplatePose(char === ' ' ? 'REST' : char));
practiceStepStartTime = performance.now();
renderSequenceChips();
updateHUD();
// Scroll active chip into view
const activeChip = sequenceChipsContainer ? sequenceChipsContainer.children[practiceCurrentIndex] : null;
if (activeChip && activeChip.scrollIntoView) {
activeChip.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
}
}
function startPlayback() {
if (practiceSequence.length === 0) return;
practiceIsPlaying = true;
if (btnPlayPause) btnPlayPause.textContent = 'โธ';
jumpToStep(practiceCurrentIndex);
updateHUD();
}
function pausePlayback() {
practiceIsPlaying = false;
if (btnPlayPause) btnPlayPause.textContent = 'โถ';
updateHUD();
}
// Playback control buttons
if (btnPlayPause) {
btnPlayPause.addEventListener('click', () => {
if (practiceIsPlaying) {
pausePlayback();
} else {
if (practiceCurrentIndex >= practiceSequence.length - 1) {
practiceCurrentIndex = 0;
}
startPlayback();
}
});
}
if (btnPrev) {
btnPrev.addEventListener('click', () => {
pausePlayback();
jumpToStep(practiceCurrentIndex - 1);
});
}
if (btnNext) {
btnNext.addEventListener('click', () => {
pausePlayback();
jumpToStep(practiceCurrentIndex + 1);
});
}
if (btnReplay) {
btnReplay.addEventListener('click', () => {
practiceCurrentIndex = 0;
startPlayback();
});
}
if (scrubber) {
scrubber.addEventListener('input', () => {
if (practiceSequence.length === 0) return;
pausePlayback();
const val = parseFloat(scrubber.value);
const targetIdx = Math.round((val / 100) * (practiceSequence.length - 1));
jumpToStep(targetIdx);
});
}
// Interpolation & Render Loop
function lerp(a, b, t) {
return a + (b - a) * t;
}
function easeInOutCubic(x) {
return x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2;
}
function avatarAnimationLoop(now) {
practiceAnimFrameId = requestAnimationFrame(avatarAnimationLoop);
// Calculate step timing based on speed
const transitionMs = 450 / practiceSpeed;
const holdMs = 700 / practiceSpeed;
const totalStepMs = transitionMs + holdMs;
if (practiceToPose && practiceFromPose) {
const elapsed = now - practiceStepStartTime;
const progress = Math.min(1.0, elapsed / transitionMs);
const t = easeInOutCubic(progress);
if (!practiceCurrentPose) {
practiceCurrentPose = clonePose(practiceFromPose);
}
// Interpolate right hand
const fromR = practiceFromPose.right || NEUTRAL_REST_POSE;
const toR = practiceToPose.right || NEUTRAL_REST_POSE;
if (!practiceCurrentPose.right) practiceCurrentPose.right = clone21(fromR);
for (let i = 0; i < 21; i++) {
practiceCurrentPose.right[i][0] = lerp(fromR[i][0], toR[i][0], t);
practiceCurrentPose.right[i][1] = lerp(fromR[i][1], toR[i][1], t);
practiceCurrentPose.right[i][2] = lerp(fromR[i][2], toR[i][2], t);
}
// Interpolate left hand
const fromL = practiceFromPose.left;
const toL = practiceToPose.left;
if (fromL || toL) {
const effFromL = fromL || NEUTRAL_REST_POSE;
const effToL = toL || NEUTRAL_REST_POSE;
if (!practiceCurrentPose.left) practiceCurrentPose.left = clone21(effFromL);
for (let i = 0; i < 21; i++) {
practiceCurrentPose.left[i][0] = lerp(effFromL[i][0], effToL[i][0], t);
practiceCurrentPose.left[i][1] = lerp(effFromL[i][1], effToL[i][1], t);
practiceCurrentPose.left[i][2] = lerp(effFromL[i][2], effToL[i][2], t);
}
practiceCurrentPose.twoHanded = (t > 0.5) ? practiceToPose.twoHanded : practiceFromPose.twoHanded;
} else {
practiceCurrentPose.left = null;
practiceCurrentPose.twoHanded = false;
}
// Interpolate wrist offsets
practiceCurrentPose.wristL = [
lerp(practiceFromPose.wristL ? practiceFromPose.wristL[0] : 0, practiceToPose.wristL ? practiceToPose.wristL[0] : 0, t),
lerp(practiceFromPose.wristL ? practiceFromPose.wristL[1] : 0, practiceToPose.wristL ? practiceToPose.wristL[1] : 0, t)
];
practiceCurrentPose.wristR = [
lerp(practiceFromPose.wristR ? practiceFromPose.wristR[0] : 0, practiceToPose.wristR ? practiceToPose.wristR[0] : 0, t),
lerp(practiceFromPose.wristR ? practiceFromPose.wristR[1] : 0, practiceToPose.wristR ? practiceToPose.wristR[1] : 0, t)
];
practiceCurrentPose.desc = practiceToPose.desc;
if (practiceIsPlaying && elapsed >= totalStepMs) {
if (practiceCurrentIndex < practiceSequence.length - 1) {
jumpToStep(practiceCurrentIndex + 1);
} else {
// Completed full sequence
pausePlayback();
if (avatarStatusText) avatarStatusText.textContent = 'Complete';
}
}
}
drawAvatar();
}
// Draw 21-landmark hand skeleton with 5 distinct finger colors, palm metacarpals, and pearl beads
function drawHandSkeleton(ctx, pose21, wristX, wristY, dpr, scale, isLeft) {
if (!pose21 || pose21.length !== 21) return;
// Project landmarks to screen coordinates
const pts = pose21.map(pt => {
const lx = pt[0];
const ly = pt[1];
const lz = pt[2] || 0;
const depth = 1.0 / (1.0 - lz * 0.18);
return [
wristX + lx * scale * depth,
wristY + ly * scale * depth,
lz
];
});
// Palm Metacarpal Structure (cool titanium slate connecting wrist to the 4 knuckles)
const palmCol = 'rgba(145, 160, 175, 0.85)';
ctx.strokeStyle = palmCol;
ctx.lineWidth = 3.5 * dpr;
// Metacarpal rays: wrist to MCPs (5, 9, 13, 17)
[5, 9, 13, 17].forEach(mcp => {
ctx.beginPath();
ctx.moveTo(wristX, wristY);
ctx.lineTo(pts[mcp][0], pts[mcp][1]);
ctx.stroke();
});
// Knuckle transverse arch: connecting MCP 5 -> 9 -> 13 -> 17
ctx.lineWidth = 4.5 * dpr;
ctx.beginPath();
ctx.moveTo(pts[5][0], pts[5][1]);
ctx.lineTo(pts[9][0], pts[9][1]);
ctx.lineTo(pts[13][0], pts[13][1]);
ctx.lineTo(pts[17][0], pts[17][1]);
ctx.stroke();
// Finger Segments with exact reference colors:
// Thumb: Coral / Red-Pink (wrist 0 -> 1 -> 2 -> 3 -> 4)
// Index: Deep Electric Blue (5 -> 6 -> 7 -> 8)
// Middle: Bright Emerald Green (9 -> 10 -> 11 -> 12)
// Ring: Vibrant Cyan (13 -> 14 -> 15 -> 16)
// Pinky: Warm Orange (17 -> 18 -> 19 -> 20)
const fingerGroups = [
{ indices: [0, 1, 2, 3, 4], color: '#ff4d4d', width: 6.0 * dpr }, // Thumb
{ indices: [5, 6, 7, 8], color: '#2979ff', width: 6.0 * dpr }, // Index
{ indices: [9, 10, 11, 12], color: '#00e676', width: 6.0 * dpr }, // Middle
{ indices: [13, 14, 15, 16], color: '#00e5ff', width: 6.0 * dpr }, // Ring
{ indices: [17, 18, 19, 20], color: '#ff9800', width: 6.0 * dpr }, // Pinky
];
fingerGroups.forEach(group => {
ctx.strokeStyle = group.color;
ctx.lineWidth = group.width;
for (let k = 0; k < group.indices.length - 1; k++) {
const i1 = group.indices[k];
const i2 = group.indices[k + 1];
ctx.beginPath();
ctx.moveTo(pts[i1][0], pts[i1][1]);
ctx.lineTo(pts[i2][0], pts[i2][1]);
ctx.stroke();
}
});
// Joint caps: Clean pearl white dots
ctx.fillStyle = '#ffffff';
pts.forEach((pt, idx) => {
if (idx === 0) return; // Skip wrist, drawn specially below
const radius = (idx % 4 === 0) ? 2.5 * dpr : 2.0 * dpr;
ctx.beginPath();
ctx.arc(pt[0], pt[1], radius, 0, Math.PI * 2);
ctx.fill();
});
// Wrist Joint: Clean pearl white bead
ctx.fillStyle = '#ffffff';
ctx.beginPath();
ctx.arc(wristX, wristY, 5 * dpr, 0, Math.PI * 2);
ctx.fill();
}
// Draw Avatar Canvas
function drawAvatar() {
if (!canvas || !ctx) return;
const dpr = window.devicePixelRatio || 1;
const w = canvas.width;
const h = canvas.height;
ctx.save();
ctx.clearRect(0, 0, w, h);
// 1. Studio background (theme-aware)
const isLight = document.documentElement.getAttribute('data-theme') === 'light';
ctx.fillStyle = isLight ? '#eaedf4' : '#161619';
ctx.fillRect(0, 0, w, h);
// 2. Stylized Red Silhouette Avatar (Head, Face, Torso, Arms - matching RyloTranslate)
const red = '#d82222';
ctx.strokeStyle = red;
ctx.fillStyle = red;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.shadowBlur = 0;
// Shoulder & torso anchor points
const shoulderY = h * 0.48;
const leftShoulderX = w * 0.33;
const rightShoulderX = w * 0.71;
// Head dimensions
const headCx = w * 0.51;
const headCy = h * 0.25;
const headRx = w * 0.082;
const headRy = h * 0.125;
// Head contour
ctx.lineWidth = 5 * dpr;
ctx.beginPath();
ctx.ellipse(headCx, headCy, headRx, headRy, 0, 0, Math.PI * 2);
ctx.stroke();
// Eyebrows (bold expressive arches)
ctx.lineWidth = 7 * dpr;
ctx.beginPath();
ctx.arc(headCx - headRx * 0.44, headCy - headRy * 0.35, headRx * 0.34, Math.PI * 1.1, Math.PI * 1.9, false);
ctx.stroke();
ctx.beginPath();
ctx.arc(headCx + headRx * 0.44, headCy - headRy * 0.35, headRx * 0.34, Math.PI * 1.1, Math.PI * 1.9, false);
ctx.stroke();
// Eyes (almond shaped contours)
ctx.lineWidth = 3.5 * dpr;
ctx.beginPath();
ctx.ellipse(headCx - headRx * 0.42, headCy - headRy * 0.12, headRx * 0.24, headRy * 0.12, 0, 0, Math.PI * 2);
ctx.stroke();
ctx.beginPath();
ctx.ellipse(headCx + headRx * 0.42, headCy - headRy * 0.12, headRx * 0.24, headRy * 0.12, 0, 0, Math.PI * 2);
ctx.stroke();
// Mouth (expressive open oval)
ctx.lineWidth = 4.5 * dpr;
ctx.beginPath();
ctx.ellipse(headCx, headCy + headRy * 0.38, headRx * 0.32, headRy * 0.16, 0, 0, Math.PI * 2);
ctx.stroke();
// Torso Frame:
ctx.lineWidth = 5 * dpr;
// Clavicle / shoulder horizontal bar
ctx.beginPath();
ctx.moveTo(leftShoulderX, shoulderY);
ctx.lineTo(rightShoulderX, shoulderY);
ctx.stroke();
// Torso body lines (tapering downwards)
ctx.beginPath();
ctx.moveTo(leftShoulderX, shoulderY);
ctx.lineTo(w * 0.39, h * 0.98);
ctx.moveTo(rightShoulderX, shoulderY);
ctx.lineTo(w * 0.65, h * 0.98);
ctx.stroke();
// Determine dual-hand vs single-hand posture
const is2H = practiceCurrentPose && practiceCurrentPose.twoHanded && practiceCurrentPose.left;
const handScale = Math.min(w * 0.20, h * 0.20);
if (is2H) {
// TWO-HANDED MODE: Both arms raised into signing space
const offLx = (practiceCurrentPose.wristL ? practiceCurrentPose.wristL[0] : 0) * handScale;
const offLy = (practiceCurrentPose.wristL ? practiceCurrentPose.wristL[1] : 0) * handScale;
const offRx = (practiceCurrentPose.wristR ? practiceCurrentPose.wristR[0] : 0) * handScale;
const offRy = (practiceCurrentPose.wristR ? practiceCurrentPose.wristR[1] : 0) * handScale;
const wristL_X = w * 0.37 + offLx;
const wristL_Y = h * 0.65 + offLy;
const wristR_X = w * 0.63 + offRx;
const wristR_Y = h * 0.65 + offRy;
const elbowL_X = leftShoulderX - w * 0.07;
const elbowL_Y = (shoulderY + wristL_Y) / 2 + h * 0.08;
const elbowR_X = rightShoulderX + w * 0.07;
const elbowR_Y = (shoulderY + wristR_Y) / 2 + h * 0.08;
// Left Arm (viewer-left): Shoulder -> Elbow -> Wrist
ctx.beginPath();
ctx.moveTo(leftShoulderX, shoulderY);
ctx.lineTo(elbowL_X, elbowL_Y);
ctx.lineTo(wristL_X, wristL_Y);
ctx.stroke();
// Right Arm (viewer-right): Shoulder -> Elbow -> Wrist
ctx.beginPath();
ctx.moveTo(rightShoulderX, shoulderY);
ctx.lineTo(elbowR_X, elbowR_Y);
ctx.lineTo(wristR_X, wristR_Y);
ctx.stroke();
// Render both hand skeletons
drawHandSkeleton(ctx, practiceCurrentPose.left, wristL_X, wristL_Y, dpr, handScale, true);
drawHandSkeleton(ctx, practiceCurrentPose.right, wristR_X, wristR_Y, dpr, handScale, false);
} else {
// SINGLE-HANDED MODE: Dominant signing arm active, other arm resting naturally
const wristX = w * 0.34;
const wristY = h * 0.65;
const elbowL_X = w * 0.24;
const elbowL_Y = h * 0.84;
// Signing Arm (viewer-left): Shoulder -> Elbow -> Wrist
ctx.beginPath();
ctx.moveTo(leftShoulderX, shoulderY);
ctx.lineTo(elbowL_X, elbowL_Y);
ctx.lineTo(wristX, wristY);
ctx.stroke();
// Resting Arm (viewer-right): Shoulder -> Elbow -> Forearm down
const elbowR_X = w * 0.76;
const elbowR_Y = h * 0.82;
ctx.beginPath();
ctx.moveTo(rightShoulderX, shoulderY);
ctx.lineTo(elbowR_X, elbowR_Y);
ctx.lineTo(w * 0.68, h * 0.98);
ctx.stroke();
// Render single hand skeleton
const singlePose = practiceCurrentPose ? (practiceCurrentPose.right || practiceCurrentPose.left) : null;
if (singlePose) {
drawHandSkeleton(ctx, singlePose, wristX, wristY, dpr, handScale, false);
}
}
ctx.restore();
}
// Start animation loop
requestAnimationFrame(avatarAnimationLoop);
}
function activatePracticeStudio() {
const canvas = document.getElementById('avatar-canvas');
if (canvas && canvas.parentElement) {
const rect = canvas.parentElement.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
if (rect.width > 0 && rect.height > 0) {
canvas.width = Math.floor(rect.width) * dpr;
canvas.height = Math.floor(rect.height) * dpr;
}
}
}12345678910111213141516171819<!doctype html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width" /><title>My static Space</title><link rel="stylesheet" href="style.css" /></head><body><div class="card"><h1>Welcome to your static Space!</h1><p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p><p>Also don't forget to check the<a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.</p></div></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="color-scheme" content="dark" /><title>SignLens</title><link rel="preconnect" href="https://fonts.googleapis.com" /><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /><link href="https://fonts.googleapis.com/css2?family=Geist:wght@300;400;500;600;700&family=Geist+Mono:wght@400;500;600&display=swap" rel="stylesheet" /><link rel="stylesheet" href="style.css?v=14" /><!-- MediaPipe Tasks Vision loaded dynamically inside app.js initMediaPipe() --></head><body><!-- โโ TOP BAR โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ --><header class="topbar"><div class="brand"><!-- Single geometric mark: three ascending strokes, a hand reading as signal. --><svg class="brand-mark" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3" y="13" width="4" height="8" rx="2" /><rect x="10" y="7" width="4" height="14" rx="2" /><rect x="17" y="3" width="4" height="18" rx="2" /></svg><span class="brand-name">SignLens</span></div><div class="mode-toggle" id="mode-toggle" role="group" aria-label="Sign language"><button class="mode-btn active" data-mode="asl" id="btn-asl" aria-pressed="true">ASL</button><button class="mode-btn" data-mode="isl" id="btn-isl" aria-pressed="false">ISL</button><button class="mode-btn" data-mode="visually" id="btn-visually" aria-pressed="false">VISUALLY</button><span class="mode-slider" aria-hidden="true"></span></div><div class="topbar-right"><button class="ghost-btn guide-btn" popovertarget="panel-guide" id="btn-open-guide" aria-label="Open Sign Guide"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align: -2px; margin-right: 5px;"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"></path><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"></path></svg><span>Sign Guide</span></button><button class="ghost-btn" popovertarget="panel-settings">Settings</button><button class="ghost-btn" popovertarget="panel-help">Shortcuts</button><button class="ghost-btn theme-toggle-btn" id="btn-theme-toggle" aria-label="Toggle Light or Dark Mode" title="Toggle Light / Dark Mode"><span id="theme-toggle-icon" aria-hidden="true">โ๏ธ</span></button><div class="status-pill" id="status-pill"><span class="status-dot" aria-hidden="true"></span><span id="status-text" role="status" aria-live="polite">Connecting</span></div></div></header><!-- โโ WORKSPACE (LIVE CAMERA) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ --><main class="workspace" id="live-workspace"><!-- โโ Camera stage โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ --><section class="stage" aria-label="Camera"><div class="viewport"><video id="webcam-video" autoplay playsinline muted></video><canvas id="display-canvas"></canvas><div class="no-hand-overlay visible" id="no-hand-overlay"><div class="idle-title">Show your hand to the camera</div><div class="idle-sub">Tracking starts as soon as a hand is in frame.</div></div></div><!-- Live readout: the one thing the user actually watches --><div class="readout"><div class="readout-dial"><div class="dial-ring" aria-hidden="true"></div><div class="detected-letter" id="detected-letter" role="status" aria-live="polite" aria-atomic="true"></div></div><div class="readout-body"><div class="readout-line"><span class="detected-sub" id="detected-conf">Waiting</span><span class="hand-badge" id="hand-badge" role="status" aria-live="polite">NO HAND</span></div><div class="streak-row"><div class="streak-track"><div class="streak-fill" id="streak-bar"></div></div><span class="streak-label" id="streak-label">0 / 5</span></div></div><div class="stage-actions"><button class="ctrl-btn" popovertarget="panel-guide" id="stage-guide-btn" title="View official sign chart">Guide</button><button class="ctrl-btn" id="btn-pause-detection">Pause</button><button class="ctrl-btn active-btn" id="btn-camera-toggle">Stop Camera</button></div></div></section><!-- โโ Output rail โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ --><aside class="rail"><article class="panel" id="word-panel"><header class="panel-head"><h2 class="panel-title">Building word</h2></header><div class="word-display" id="word-display"><span class="ph">Start signing</span></div><div class="panel-actions"><button class="btn" id="btn-backspace">Delete</button><button class="btn" id="btn-add-space">Next word</button><button class="btn btn-quiet" id="btn-clear-word">Clear</button></div></article><article class="panel panel-grow" id="sentence-panel"><header class="panel-head"><h2 class="panel-title">Sentence</h2><div class="panel-head-actions"><button class="btn btn-sm" id="btn-speak">Speak</button><button class="btn btn-sm" id="btn-copy">Copy</button></div></header><div class="sentence-display" id="sentence-display" role="status" aria-live="polite"><em class="ph">Your sentence will appear here</em></div><div class="word-chips" id="word-chips"></div><button class="btn btn-danger" id="btn-clear-sentence">Clear all</button></article></aside></main><!-- โโ VISUALLY (PRACTICE STUDIO) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ --><section class="workspace visually-workspace hidden" id="visually-workspace" aria-label="Practice Studio"><!-- Left Column: Input, Speech Dictation, and Sequence Breakdown --><aside class="practice-input-rail"><article class="panel panel-grow practice-panel"><header class="panel-head"><div class="practice-head-title"><span class="practice-badge">PRACTICE STUDIO</span><h2 class="panel-title">Text to Sign</h2></div><div class="practice-dialect-toggle" id="practice-dialect-toggle"><button class="dialect-pill active" id="btn-practice-asl">ASL</button><button class="dialect-pill" id="btn-practice-isl">ISL</button></div></header><!-- Textarea with integrated voice mic & actions --><div class="practice-textarea-box"><textarea id="practice-input" placeholder="Type words or sentence (e.g. 'HI BABY', 'HOW ARE YOU')..." rows="4"></textarea><div class="practice-input-tools"><button class="tool-btn mic-btn" id="btn-mic" title="Voice Input (Speech-to-Sign)"><svg class="icon" viewBox="0 0 24 24" fill="currentColor"><path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5-3c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/></svg><span id="mic-label">Speak</span></button><button class="tool-btn" id="btn-speak-input" title="Speak text aloud"><svg class="icon" viewBox="0 0 24 24" fill="currentColor"><path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/></svg></button><button class="tool-btn" id="btn-clear-practice" title="Clear text">Clear</button><span class="char-count" id="practice-char-count">0/200</span></div></div><!-- Quick sample prompts --><div class="quick-samples"><span class="quick-label">Try:</span><button class="sample-chip" data-text="HI">HI</button><button class="sample-chip" data-text="HELLO">HELLO</button><button class="sample-chip" data-text="THANK YOU">THANK YOU</button><button class="sample-chip" data-text="HOW ARE YOU">HOW ARE YOU</button><button class="sample-chip" data-text="BABY">BABY</button></div><!-- Main Trigger & Speed --><div class="practice-action-row"><button class="btn btn-primary btn-demo" id="btn-start-sign"><svg class="icon-play" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg><span>Demonstrate Sign</span></button><div class="speed-control"><span class="speed-label">Speed</span><button class="speed-btn" data-speed="0.5">0.5x</button><button class="speed-btn active" data-speed="1.0">1.0x</button><button class="speed-btn" data-speed="1.5">1.5x</button></div></div><!-- Letter Tape Progression --><div class="sequence-section"><div class="sequence-head"><span class="seq-title">Sign Sequence Timeline</span><span class="seq-counter" id="seq-counter">0 / 0</span></div><div class="sequence-chips" id="sequence-chips"><span class="ph">Enter text above to preview gesture timelineโฆ</span></div></div></article></aside><!-- Right Column: Interactive 3D Avatar Skeleton Stage --><section class="practice-stage" aria-label="Avatar Stage"><div class="avatar-viewport"><canvas id="avatar-canvas"></canvas><!-- Active Letter Glow Badge --><div class="avatar-hud-letter" id="avatar-hud-letter"><span class="hud-letter-char" id="hud-letter-char">โ</span><span class="hud-letter-sub" id="hud-letter-sub">Waiting for input</span><span class="hud-letter-cue" id="hud-letter-cue" style="display: none;"></span></div><!-- Avatar Status Badge --><div class="avatar-hud-status" id="avatar-hud-status"><span class="status-badge-dot"></span><span id="avatar-status-text">Ready</span></div><!-- Real Human Sign Reference Card (Top-Right) --><div class="avatar-sign-preview" id="avatar-sign-preview" title="Official sign gesture photo reference" style="display: none;"><div class="avatar-sign-img-wrap"><img id="avatar-sign-img" src="" alt="Sign Gesture Reference" /><span class="avatar-sign-badge" id="avatar-sign-badge">ISL</span></div><div class="avatar-sign-info"><div class="avatar-sign-char-row"><span class="avatar-sign-char" id="avatar-sign-char">A</span><span class="avatar-sign-hands" id="avatar-sign-hands">1 Hand</span></div><span class="avatar-sign-desc" id="avatar-sign-desc">Sign gesture reference</span></div></div><!-- Playback Controls Floating Bar --><div class="avatar-controls-bar"><button class="avatar-ctrl-btn" id="btn-avatar-prev" title="Previous letter">โฎ</button><button class="avatar-ctrl-btn play-pause-btn" id="btn-avatar-playpause" title="Play/Pause">โธ</button><button class="avatar-ctrl-btn" id="btn-avatar-next" title="Next letter">โญ</button><button class="avatar-ctrl-btn" id="btn-avatar-replay" title="Replay all">โฒ</button><div class="avatar-progress-wrap"><input type="range" class="avatar-scrubber" id="avatar-scrubber" min="0" max="100" value="0" step="0.1" /></div></div></div></section></section><!-- โโ SETTINGS (top layer) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ --><div popover id="panel-settings" class="sheet" style="display: none;"><header class="sheet-head"><h2 class="sheet-title">Detection</h2><button class="ghost-btn" popovertarget="panel-settings" popovertargetaction="hide">Close</button></header><div class="field"><label for="set-confidence">Minimum confidence</label><div class="field-row"><input type="range" id="set-confidence" min="40" max="95" step="5" value="50" /><output class="field-value" id="out-confidence">50%</output></div><p class="field-help">Predictions below this are ignored. Raise it if letters are captured too eagerly.</p></div><div class="field"><label for="set-streak">Frames to confirm</label><div class="field-row"><input type="range" id="set-streak" min="3" max="15" step="1" value="5" /><output class="field-value" id="out-streak">5</output></div><p class="field-help">How long the same sign must hold before the letter is captured.</p></div><div class="field"><label for="set-timeout">Auto-push word delay</label><div class="field-row"><input type="range" id="set-timeout" min="1.0" max="5.0" step="0.5" value="3.0" /><output class="field-value" id="out-timeout">3.0s</output></div><p class="field-help">How long you must lower your hand before the word commits to sentence.</p></div></div><!-- โโ SHORTCUTS (top layer) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ --><div popover id="panel-help" class="sheet" style="display: none;"><header class="sheet-head"><h2 class="sheet-title">How it works</h2><button class="ghost-btn" popovertarget="panel-help" popovertargetaction="hide">Close</button></header><ol class="steps"><li><span class="step-n">1</span> Show a hand sign to the camera.</li><li><span class="step-n">2</span> Hold it steady while the ring fills.</li><li><span class="step-n">3</span> The letter is captured and added to the word.</li><li><span class="step-n">4</span> Drop your hand to commit the word to the sentence.</li></ol><div class="keys"><div class="key-row"><kbd>Space</kbd><span>Commit current word</span></div><div class="key-row"><kbd>Backspace</kbd><span>Delete last letter</span></div><div class="key-row"><kbd>1</kbd><span>Switch to ASL</span></div><div class="key-row"><kbd>2</kbd><span>Switch to ISL</span></div><div class="key-row"><kbd>3</kbd><span>Switch to Practice (VISUALLY)</span></div></div></div><!-- โโ SIGN REFERENCE GUIDE (top layer modal) โโโโโโโโโโโโโโโโโโโโโโโโโโโ --><div popover id="panel-guide" class="sheet sheet-wide" style="display: none;"><header class="sheet-head"><div class="sheet-title-group"><h2 class="sheet-title">Sign Reference Guide</h2><span class="sheet-sub">Official hand gestures, required hand counts & poses</span></div><div class="guide-tabs" role="tablist"><button class="guide-tab-btn active" id="tab-guide-isl" role="tab" aria-selected="true">๐ฎ๐ณ ISL (Indian Sign Language)</button><button class="guide-tab-btn" id="tab-guide-asl" role="tab" aria-selected="false">๐บ๐ธ ASL (American Sign Language)</button></div><button class="ghost-btn" id="btn-close-guide" popovertarget="panel-guide" popovertargetaction="hide">Close</button></header><!-- ISL Tab Content --><div class="guide-tab-content" id="guide-content-isl"><div class="guide-alert-banner"><span class="banner-icon">โ ๏ธ</span><div><strong>Crucial Rule in ISL:</strong> 20 alphabet letters (<kbd>A, B, D, E, F, G, H, J, K, M, N, P, Q, R, S, T, W, X, Y, Z</kbd>) strictly require <strong>TWO HANDS</strong>. Only numbers <kbd>1-9</kbd> and letters <kbd>C, I, L, O, U, V</kbd> use a single hand!</div></div><div class="guide-section"><div class="guide-section-head"><h3 class="guide-section-title">Single-Hand Gestures (15 Signs)</h3><span class="pill-badge pill-amber">1-Hand Required</span></div><div class="guide-cards-grid" id="isl-single-cards"></div></div><div class="guide-section" style="margin-top: 28px;"><div class="guide-section-head"><h3 class="guide-section-title">Dual-Hand Gestures (20 Signs)</h3><span class="pill-badge pill-blue">2-Hands Required</span></div><div class="guide-cards-grid" id="isl-dual-cards"></div></div></div><!-- ASL Tab Content --><div class="guide-tab-content hidden" id="guide-content-asl"><div class="guide-alert-banner"><span class="banner-icon">๐ก</span><div><strong>Rule in ASL:</strong> All 26 alphabet letters (<kbd>A to Z</kbd>) are performed using <strong>ONE dominant hand</strong>.</div></div><div class="guide-section"><div class="guide-section-head"><h3 class="guide-section-title">ASL Alphabet (26 Signs)</h3><span class="pill-badge pill-amber">1-Hand Only</span></div><div class="guide-cards-grid" id="asl-cards"></div></div></div></div><!-- โโ SIGN GUIDE LIGHTBOX POPUP (Top-layer native dialog) โโโโโโโโโโโโโโโโโโโโโโโโ --><dialog class="sign-lightbox-dialog" id="sign-lightbox-overlay"><div class="sign-lightbox" id="sign-lightbox"><button class="sign-lightbox-close" id="sign-lightbox-close" aria-label="Close preview">×</button><div class="sign-lightbox-img-wrap"><img id="sign-lightbox-img" src="" alt="Sign preview" /></div><div class="sign-lightbox-letter" id="sign-lightbox-letter"></div><span class="sign-lightbox-type" id="sign-lightbox-type"></span><p class="sign-lightbox-desc" id="sign-lightbox-desc"></p><div class="sign-lightbox-lang" id="sign-lightbox-lang"></div></div></dialog><div class="toast" id="toast" role="status" aria-live="polite"></div><script src="app.js?v=19"></script></body></html>
.gitattributes+2
ASL_Alphabet_Chart.pngAdded

Large File Pointer Details
- SHA256: 2c1dba6ed870a2f0c6e0f20e30548e2ba8acd14f7f7e733b1d5e1d1098472bb8
- Pointer size: 132 Bytes
- Size of remote file: 1.16 MB
ISL_Hand_Signs_Official.pngAdded

Large File Pointer Details
- SHA256: 792dc1b24e71fe43451a4d5751b9ef0a4a695fe844da0d9c5f7e259c61ae65bf
- Pointer size: 132 Bytes
- Size of remote file: 1.73 MB
README.md+36-3
app.jsAdded+2384
asl_landmarks_weights.jsonAdded
asl_signs/A.pngAdded

asl_signs/B.pngAdded

asl_signs/C.pngAdded

asl_signs/D.pngAdded

asl_signs/E.pngAdded

asl_signs/F.pngAdded

asl_signs/G.pngAdded

asl_signs/H.pngAdded

asl_signs/I.pngAdded

asl_signs/J.pngAdded

asl_signs/K.pngAdded

asl_signs/L.pngAdded

asl_signs/M.pngAdded

asl_signs/N.pngAdded

asl_signs/O.pngAdded

asl_signs/P.pngAdded

asl_signs/Q.pngAdded

asl_signs/R.pngAdded

asl_signs/S.pngAdded

asl_signs/T.pngAdded

asl_signs/U.pngAdded

asl_signs/V.pngAdded

asl_signs/W.pngAdded

asl_signs/X.pngAdded

asl_signs/Y.pngAdded

asl_signs/Z.pngAdded

index.html+393-19
isl_landmarks_weights.jsonAdded
isl_signs/1.pngAdded

isl_signs/2.pngAdded

isl_signs/3.pngAdded

isl_signs/4.pngAdded

isl_signs/5.pngAdded

isl_signs/6.pngAdded

isl_signs/7.pngAdded

isl_signs/8.pngAdded

isl_signs/9.pngAdded

isl_signs/A.pngAdded

isl_signs/B.pngAdded

isl_signs/C.pngAdded

isl_signs/D.pngAdded

isl_signs/E.pngAdded

isl_signs/F.pngAdded

isl_signs/G.pngAdded
