Spaces:
Sleeping
Sleeping
Commit ·
2be007a
1
Parent(s): fd607ef
MERGE EVERYTHING from feature/integration-cleaned :((((((((((((((((((((((((((((((((((((((((((((((( so tired
Browse filesFiles changed (17)
- README.md+6
- main.py+24-5
- models/face_mesh.py+6-1
- models/head_pose.py+2
- package-lock.json+9
- src/App.css+758-39
- src/App.jsx+6-5
- src/components/Achievement.jsx+10
- src/components/Customise.jsx+21-21
- src/components/FocusPage.jsx+17-17
- src/components/FocusPageLocal.jsx+405-168
- src/components/Home.jsx+7-7
- src/components/Records.jsx+368-35
- src/utils/VideoManager.jsDeleted-347
- src/utils/VideoManagerLocal.js+123-51
- ui/pipeline.py+2
- vite.config.js+22-14
45 unmodified lines46474849505145 unmodified linesThen open http://localhost:7860.**OpenCV demo:**```bash45 unmodified lines46474849505152535455565745 unmodified linesThen open http://localhost:7860.**Frontend dev server (optional, for React development):**```bashnpm run dev```**OpenCV demo:**```bash
123176 unmodified lines180181182183184185318 unmodified lines50450550650750850965 unmodified lines57557657757857958058175 unmodified lines657658659660661662663664665666from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Requestfrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import FileResponse176 unmodified linesprint("[OK] XGBoostPipeline loaded")except Exception as e:print(f"[ERR] Failed to load XGBoostPipeline: {e}")yield_inference_executor.shutdown(wait=False)print(" Shutting down Focus Guard API...")318 unmodified lineswith _pipeline_locks[model_name]:return pipeline.process_frame(frame)# ================ WEBRTC SIGNALING ================@app.post("/api/webrtc/offer")65 unmodified linesrunning = Trueevent_buffer = _EventBuffer(flush_interval=2.0)# Latest frame slot — only the most recent frame is kept, older ones are dropped.# Using a dict so nested functions can mutate without nonlocal issues._slot = {"frame": None}_frame_ready = asyncio.Event()75 unmodified linescontinueframe = cv2.resize(frame, (640, 480))model_name = _cached_model_nameif model_name not in pipelines or pipelines.get(model_name) is None:model_name = "mlp"active_pipeline = pipelines.get(model_name)landmarks_list = Noneif active_pipeline is not None:12345176 unmodified lines182183184185186187188189190191192193194195196197198318 unmodified lines51751851952052152252352452552652752852953065 unmodified lines59659759859960060160275 unmodified lines678679680681682683684685from __future__ import annotationsfrom fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Requestfrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import FileResponse176 unmodified linesprint("[OK] XGBoostPipeline loaded")except Exception as e:print(f"[ERR] Failed to load XGBoostPipeline: {e}")resolved_model = _first_available_pipeline_name(_cached_model_name)if resolved_model is not None and resolved_model != _cached_model_name:_cached_model_name = resolved_modelasync with aiosqlite.connect(db_path) as db:await db.execute("UPDATE user_settings SET model_name = ? WHERE id = 1",(_cached_model_name,),)await db.commit()if resolved_model is not None:print(f"[OK] Active model set to {resolved_model}")yield_inference_executor.shutdown(wait=False)print(" Shutting down Focus Guard API...")318 unmodified lineswith _pipeline_locks[model_name]:return pipeline.process_frame(frame)def _first_available_pipeline_name(preferred: str | None = None) -> str | None:if preferred and preferred in pipelines and pipelines.get(preferred) is not None:return preferredfor name, pipeline in pipelines.items():if pipeline is not None:return namereturn None# ================ WEBRTC SIGNALING ================@app.post("/api/webrtc/offer")65 unmodified linesrunning = Trueevent_buffer = _EventBuffer(flush_interval=2.0)# Latest frame slot: keep only the newest frame and drop stale ones.# Using a dict so nested functions can mutate without nonlocal issues._slot = {"frame": None}_frame_ready = asyncio.Event()75 unmodified linescontinueframe = cv2.resize(frame, (640, 480))model_name = _first_available_pipeline_name(_cached_model_name)active_pipeline = pipelines.get(model_name) if model_name is not None else Nonelandmarks_list = Noneif active_pipeline is not None:
12340 unmodified lines44454647484950import osimport timefrom pathlib import Path40 unmodified lines):model_path = _ensure_model()options = FaceLandmarkerOptions(base_options=mp_tasks.BaseOptions(model_asset_path=model_path),num_faces=max_num_faces,min_face_detection_confidence=min_detection_confidence,min_face_presence_confidence=min_detection_confidence,1234540 unmodified lines46474849505152535455from __future__ import annotationsimport osimport timefrom pathlib import Path40 unmodified lines):model_path = _ensure_model()options = FaceLandmarkerOptions(base_options=mp_tasks.BaseOptions(model_asset_path=model_path,delegate=mp_tasks.BaseOptions.Delegate.CPU,),num_faces=max_num_faces,min_face_detection_confidence=min_detection_confidence,min_face_presence_confidence=min_detection_confidence,
123import mathimport cv212345from __future__ import annotationsimport mathimport cv2
53 unmodified lines5455565758591368 unmodified lines14281429143014311432143335 unmodified lines14691470147114721473147499 unmodified lines157415751576157715781579215 unmodified lines179517961797179817991800680 unmodified lines24812482248324842485248655 unmodified lines254225432544254525462547227 unmodified lines277527762777277827792780115 unmodified lines28962897289828992900290153 unmodified lines"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==","dev": true,"license": "MIT","dependencies": {"@babel/code-frame": "^7.29.0","@babel/generator": "^7.29.0",1368 unmodified lines"integrity": "sha512-tORuanb01iEzWvMGVGv2ZDhYZVeRMrw453DCSAIn/5yvcSVnMoUMTyf33nQJLahYEnv9xqrTNbgz4qY5EfSh0g==","dev": true,"license": "MIT","dependencies": {"csstype": "^3.2.2"}35 unmodified lines"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==","dev": true,"license": "MIT","bin": {"acorn": "bin/acorn"},99 unmodified lines}],"license": "MIT","dependencies": {"baseline-browser-mapping": "^2.9.0","caniuse-lite": "^1.0.30001759",215 unmodified lines"integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==","dev": true,"license": "MIT","dependencies": {"@eslint-community/eslint-utils": "^4.8.0","@eslint-community/regexpp": "^4.12.1",680 unmodified lines"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT","engines": {"node": ">=12"},55 unmodified lines"resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz","integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==","license": "MIT","engines": {"node": ">=0.10.0"}227 unmodified lines"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==","dev": true,"license": "MIT","dependencies": {"esbuild": "^0.27.0","fdir": "^6.5.0",115 unmodified lines"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==","dev": true,"license": "MIT","funding": {"url": "https://github.com/sponsors/colinhacks"}53 unmodified lines545556575859601368 unmodified lines142914301431143214331434143535 unmodified lines147114721473147414751476147799 unmodified lines1577157815791580158115821583215 unmodified lines1799180018011802180318041805680 unmodified lines248624872488248924902491249255 unmodified lines2548254925502551255225532554227 unmodified lines2782278327842785278627872788115 unmodified lines290429052906290729082909291053 unmodified lines"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==","dev": true,"license": "MIT","peer": true,"dependencies": {"@babel/code-frame": "^7.29.0","@babel/generator": "^7.29.0",1368 unmodified lines"integrity": "sha512-tORuanb01iEzWvMGVGv2ZDhYZVeRMrw453DCSAIn/5yvcSVnMoUMTyf33nQJLahYEnv9xqrTNbgz4qY5EfSh0g==","dev": true,"license": "MIT","peer": true,"dependencies": {"csstype": "^3.2.2"}35 unmodified lines"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==","dev": true,"license": "MIT","peer": true,"bin": {"acorn": "bin/acorn"},99 unmodified lines}],"license": "MIT","peer": true,"dependencies": {"baseline-browser-mapping": "^2.9.0","caniuse-lite": "^1.0.30001759",215 unmodified lines"integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==","dev": true,"license": "MIT","peer": true,"dependencies": {"@eslint-community/eslint-utils": "^4.8.0","@eslint-community/regexpp": "^4.12.1",680 unmodified lines"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT","peer": true,"engines": {"node": ">=12"},55 unmodified lines"resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz","integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==","license": "MIT","peer": true,"engines": {"node": ">=0.10.0"}227 unmodified lines"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==","dev": true,"license": "MIT","peer": true,"dependencies": {"esbuild": "^0.27.0","fdir": "^6.5.0",115 unmodified lines"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==","dev": true,"license": "MIT","peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}
39 unmodified lines404142434445464748495055 unmodified lines10610710810911011111211311411511611711811912023 unmodified lines1441451461471481491501511521531541551564 unmodified lines161162163164165166167168169170171172173191 unmodified lines36536636736836937038 unmodified lines4094104114124134144154164174184194204211 unmodified line42342442542642742872 unmodified lines501502503504505506507508509510511512108 unmodified lines621622623624625626110 unmodified lines7377387397407417427437447457467477487497507511 unmodified line7537547557567577587597607617627637647651 unmodified line7677687697707717727738 unmodified lines7827837847857867877881 unmodified line79079179279379479579617 unmodified lines81481581681781881982082182282382482582682782882983083112 unmodified lines8448458468478488498508518528538548558568578588598608618628638648658668678688698708718728733 unmodified lines87787887988039 unmodified linesdisplay: flex;align-items: center;justify-content: center; /* Center buttons horizontally */box-shadow: 0 2px 5px rgba(0,0,0,0.05);position: fixed;top: 0;width: 100%;z-index: 1000;}.menu-btn {55 unmodified lines/* PAGE A SPECIFIC */#page-a {justify-content: center; /* Center vertically */margin-top: -40px;flex: 1;}#page-a h1 {font-size: 80px;margin: 0 0 10px 0;color: #000;text-align: center;}#page-a p {23 unmodified lines#page-b {justify-content: space-evenly; /* Distribute vertical space */padding-bottom: 20px;min-height: calc(100vh - 60px);}/* 1. Display Area */#display-area {width: 60%;height: 50vh;min-height: 300px;border: 2px solid #ddd;border-radius: 12px;4 unmodified linescolor: #555;font-size: 24px;position: relative;overflow: hidden;}#display-area video {width: 100%;height: 100%;object-fit: cover;}/* 2. Timeline Area */191 unmodified lines#focus-chart {display: block;margin: 0 auto;max-width: 100%;}38 unmodified lines}.btn-view {padding: 6px 12px;background: #007BFF;color: white;border: none;border-radius: 5px;cursor: pointer;font-family: 'Nunito', sans-serif;transition: background 0.2s;}1 unmodified linebackground: #0056b3;}/* ================ SETTINGS PAGE ================ */.settings-container {72 unmodified linesfont-family: 'Nunito', sans-serif;}.setting-group .action-btn {display: inline-block;width: 48%;margin: 15px 1%;text-align: center;box-sizing: border-box;}#save-settings {108 unmodified lines}/* ================ SESSION SUMMARY MODAL ================ */.modal-overlay {position: fixed;top: 0;110 unmodified lineswidth: 90%;flex-direction: column;}}/* SESSION RESULT OVERLAY */.session-result-overlay {position: absolute;top: 0;left: 0;width: 100%;height: 100%;background-color: rgba(0, 0, 0, 0.85);display: flex;flex-direction: column;justify-content: center;1 unmodified linecolor: white;z-index: 10;animation: fadeIn 0.5s ease;backdrop-filter: blur(5px);}.session-result-overlay h3 {font-size: 32px;margin-bottom: 30px;color: #4cd137;text-transform: uppercase;letter-spacing: 2px;}1 unmodified line.session-result-overlay .result-item {display: flex;justify-content: space-between;width: 200px;margin-bottom: 15px;font-size: 20px;border-bottom: 1px solid rgba(255,255,255,0.2);8 unmodified lines.session-result-overlay .value {color: #fff;font-weight: bold;font-family: 'Courier New', monospace;}@keyframes fadeIn {1 unmodified lineto { opacity: 1; transform: scale(1); }}/* welcome modal */.welcome-modal-overlay {position: fixed;top: 0; left: 0; right: 0; bottom: 0;17 unmodified lines.welcome-modal p { margin-bottom: 30px; color: #ccc; }.welcome-buttons { display: flex; gap: 20px; justify-content: center; }/* top avatar */#top-menu {position: relative;display: flex;justify-content: center;align-items: center;}.avatar-container {position: absolute;left: 20px;cursor: pointer;}.avatar-circle {12 unmodified lines.avatar-circle.user { background-color: #555; }.avatar-circle.admin { background-color: #ffaa00; border-color: #fff; box-shadow: 0 0 10px rgba(255, 170, 0, 0.5); }/* home 2x2 button grid */.home-button-grid {display: grid;grid-template-columns: 1fr 1fr;gap: 20px;width: 100%;max-width: 500px;margin: 40px auto 0 auto;}.home-button-grid .btn-main {width: 100%;height: 60px;margin: 0;padding: 10px;font-size: 1rem;display: flex;justify-content: center;align-items: center;text-align: center;box-sizing: border-box;}@media (max-width: 600px) {.home-button-grid {gap: 15px;max-width: 90%;3 unmodified linesheight: 50px;font-size: 0.85rem;}}39 unmodified lines4041424344454647484950515253545556575855 unmodified lines11411511611711811912012112212312412512612712812923 unmodified lines1531541551561571581591601611621631641654 unmodified lines170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499191 unmodified lines69169269369469569669738 unmodified lines7367377387397407417427437447457467477487497501 unmodified line75275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106872 unmodified lines1141114211431144114511461147114811491150115111521153108 unmodified lines1262126312641265126612671268110 unmodified lines137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611 unmodified line14631464146514661467146814691470147114721473147414751 unmodified line14771478147914801481148214838 unmodified lines14921493149414951496149714981 unmodified line150015011502150315041505150617 unmodified lines15241525152615271528152915301531153215331534153512 unmodified lines1548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115923 unmodified lines159615971598159939 unmodified linesdisplay: flex;align-items: center;justify-content: center; /* Center buttons horizontally */gap: 0;padding: 0 24px 0 76px;box-sizing: border-box;box-shadow: 0 2px 5px rgba(0,0,0,0.05);position: fixed;top: 0;left: 0;right: 0;width: 100%;z-index: 1000;overflow-x: auto;overflow-y: hidden;white-space: nowrap;}.menu-btn {55 unmodified lines/* PAGE A SPECIFIC */#page-a {justify-content: center; /* Center vertically *//* Fine-tune this margin if the Home screen sits slightly too low. */margin-top: -40px;flex: 1; /* Fill the remaining height so vertical centering still works. */}#page-a h1 {font-size: 80px;margin: 0 0 10px 0;color: #000;text-align: center; /* Keep the heading centered. */}#page-a p {23 unmodified lines#page-b {justify-content: space-evenly; /* Distribute vertical space */padding-bottom: 20px;min-height: calc(100vh - 60px); /* Ensure the page still fills the viewport. */}/* 1. Display Area */#display-area {width: 60%;height: 50vh; /* Use viewport height to scale more consistently across screens. */min-height: 300px;border: 2px solid #ddd;border-radius: 12px;4 unmodified linescolor: #555;font-size: 24px;position: relative;/* Keep video content centered without overflowing the frame. */overflow: hidden;}.focus-display-shell {background: linear-gradient(180deg, #f7f5f2 0%, #f1f0ec 100%);}.focus-flow-overlay {position: fixed;top: 76px;right: 20px;bottom: 20px;left: 20px;display: flex;align-items: center;justify-content: center;padding: 0;background: rgba(17, 31, 52, 0.18);backdrop-filter: blur(10px);z-index: 900;}.focus-flow-card {width: min(1040px, 100%);background: #fff;border-radius: 24px;padding: 30px 34px;box-shadow: 0 28px 80px rgba(14, 44, 88, 0.18);border: 1px solid rgba(0, 123, 255, 0.12);box-sizing: border-box;}.focus-flow-header {display: flex;align-items: center;justify-content: space-between;gap: 24px;margin-bottom: 18px;}.focus-flow-eyebrow {display: inline-block;padding: 6px 12px;border-radius: 999px;background: #e7f3ff;color: #007BFF;font-size: 0.82rem;font-weight: 800;letter-spacing: 0.04em;text-transform: uppercase;}.focus-flow-header h2 {margin: 14px 0 0;color: #333;font-size: clamp(1.8rem, 2.5vw, 2.5rem);line-height: 1.1;}.focus-flow-icon {flex: 0 0 auto;display: flex;align-items: center;justify-content: center;width: 116px;height: 116px;border-radius: 24px;background: linear-gradient(180deg, #f4f9ff 0%, #edf5ff 100%);border: 1px solid rgba(0, 123, 255, 0.12);}.focus-flow-lead {margin: 0 0 20px;color: #4a4a4a;font-size: 1rem;line-height: 1.6;}.focus-flow-grid {display: grid;grid-template-columns: repeat(3, minmax(0, 1fr));gap: 16px;}.focus-flow-panel {background: #f8fbff;border: 1px solid #d9eaff;border-radius: 14px;padding: 18px;}.focus-flow-panel h3,.focus-flow-step-copy h3 {margin: 0 0 8px;color: #333;font-size: 1rem;}.focus-flow-panel p,.focus-flow-step-copy p {margin: 0;color: #5e6670;font-size: 0.95rem;line-height: 1.6;}.focus-flow-steps {display: grid;grid-template-columns: repeat(3, minmax(0, 1fr));gap: 14px;}.focus-flow-step {display: flex;align-items: flex-start;gap: 14px;background: #f8fbff;border: 1px solid #d9eaff;border-radius: 14px;padding: 16px 18px;min-height: 100px;box-sizing: border-box;}.focus-flow-step-number {flex: 0 0 auto;display: inline-flex;align-items: center;justify-content: center;width: 34px;height: 34px;border-radius: 50%;background: #007BFF;color: #fff;font-size: 0.95rem;font-weight: 800;}.focus-flow-step-copy {min-width: 0;}.focus-flow-footer {display: flex;align-items: center;justify-content: space-between;gap: 16px;margin-top: 20px;}.focus-flow-note {color: #667281;font-size: 0.94rem;line-height: 1.6;}.focus-flow-button,.focus-flow-secondary {border: none;border-radius: 999px;padding: 13px 24px;font-family: 'Nunito', sans-serif;font-size: 0.98rem;font-weight: 800;cursor: pointer;transition: transform 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease;}.focus-flow-button {background: #007BFF;color: #fff;box-shadow: 0 12px 24px rgba(0, 123, 255, 0.18);}.focus-flow-button:hover {background: #0069d9;border-color: transparent;transform: translateY(-1px);}.focus-flow-secondary {background: #eef3f8;color: #4b5a6b;}.focus-flow-secondary:hover {background: #e2eaf3;border-color: transparent;}.focus-state-pill {position: absolute;top: 18px;left: 18px;display: inline-flex;align-items: center;gap: 10px;padding: 10px 16px;border-radius: 999px;color: #fff;font-size: 0.88rem;font-weight: 800;letter-spacing: 0.04em;text-transform: uppercase;z-index: 2;box-shadow: 0 12px 24px rgba(0, 0, 0, 0.18);}.focus-state-pill.pending {background: rgba(87, 96, 111, 0.92);}.focus-state-pill.focused {background: rgba(33, 163, 102, 0.94);}.focus-state-pill.not-focused {background: rgba(215, 68, 68, 0.94);}.focus-state-dot {width: 10px;height: 10px;border-radius: 50%;background: currentColor;box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.16);}.focus-idle-overlay {position: absolute;inset: 0;display: flex;flex-direction: column;align-items: center;justify-content: center;gap: 10px;background: radial-gradient(circle at center, rgba(255, 255, 255, 0.12), rgba(0, 0, 0, 0.72));color: #fff;text-align: center;z-index: 1;}.focus-idle-overlay p {margin: 0;font-size: 1.6rem;font-weight: 800;}.focus-idle-overlay span {max-width: 420px;color: rgba(255, 255, 255, 0.82);font-size: 0.98rem;line-height: 1.5;}.focus-inline-error {margin-top: 18px;padding: 12px 16px;max-width: 620px;border-radius: 12px;background: #fff1ee;color: #b54028;font-size: 0.95rem;font-weight: 700;box-shadow: 0 10px 20px rgba(181, 64, 40, 0.08);}.focus-inline-error-standalone {width: 60%;box-sizing: border-box;}.focus-debug-panel {position: absolute;top: 10px;right: 10px;background: rgba(0,0,0,0.7);color: white;padding: 10px;border-radius: 5px;font-size: 12px;font-family: monospace;}.focus-model-strip {display: flex;align-items: center;justify-content: center;gap: 8px;padding: 8px 16px;background: #1a1a2e;border-radius: 8px;margin: 8px auto;max-width: 600px;}.focus-model-label {color: #aaa;font-size: 13px;margin-right: 4px;}.focus-model-button {padding: 5px 14px;border-radius: 16px;border: 1px solid #555;background: transparent;color: #ccc;font-size: 12px;font-weight: 600;text-transform: uppercase;}.focus-model-button.active {border: 2px solid #007BFF;background: #007BFF;color: #fff;}#display-area video {width: 100%;height: 100%;object-fit: cover; /* Behaves similarly to background-size: cover. */}/* 2. Timeline Area */191 unmodified lines#focus-chart {display: block;margin: 0 auto;/* Make sure the chart scales within its container. */max-width: 100%;}38 unmodified lines}.btn-view {padding: 6px 18px;background: #007BFF;color: white;border: none;border-radius: 999px;cursor: pointer;font-family: 'Nunito', sans-serif;font-size: 12px;font-weight: 700;transition: background 0.2s;}1 unmodified linebackground: #0056b3;}.records-detail-modal {width: min(960px, 92vw);max-width: 960px;max-height: 86vh;overflow-y: auto;padding: 30px;box-sizing: border-box;}.records-detail-header {display: flex;justify-content: space-between;align-items: flex-start;gap: 20px;margin-bottom: 24px;}.records-detail-kicker {color: #007BFF;font-size: 12px;font-weight: 800;letter-spacing: 0.08em;text-transform: uppercase;}.records-detail-header h2 {margin: 10px 0 8px;color: #333;text-align: left;}.records-detail-subtitle {margin: 0;color: #667281;line-height: 1.6;}.records-detail-close {border: 1px solid #d6e6fa;background: #f4f9ff;color: #3569a8;border-radius: 999px;padding: 10px 18px;font-family: 'Nunito', sans-serif;font-weight: 700;cursor: pointer;}.records-detail-close:hover {border-color: #bfd9f7;background: #e9f4ff;}.records-detail-feedback {padding: 18px 20px;border-radius: 14px;background: #f7f9fc;color: #516173;font-weight: 700;}.records-detail-feedback-error {background: #fff1ee;color: #b54028;}.records-detail-summary {display: grid;grid-template-columns: repeat(4, minmax(0, 1fr));gap: 14px;margin-bottom: 18px;}.records-detail-stat {padding: 18px;border-radius: 14px;background: #f8fbff;border: 1px solid #d9eaff;}.records-detail-stat.excellent {background: #eef9f0;border-color: #cdebd3;}.records-detail-stat.good {background: #fff9eb;border-color: #f8e3a8;}.records-detail-stat.fair {background: #fff4eb;border-color: #ffd6af;}.records-detail-stat.low {background: #fff0f0;border-color: #f3c7c7;}.records-detail-stat-label {display: block;margin-bottom: 8px;color: #667281;font-size: 13px;font-weight: 700;text-transform: uppercase;letter-spacing: 0.04em;}.records-detail-stat-value {display: block;color: #1f2d3d;font-size: 28px;line-height: 1.1;}.records-detail-grid {display: grid;grid-template-columns: repeat(2, minmax(0, 1fr));gap: 16px;margin-bottom: 16px;}.records-detail-card {background: white;border: 1px solid #e8eef5;border-radius: 16px;padding: 20px;box-shadow: 0 8px 24px rgba(20, 44, 74, 0.06);margin-bottom: 16px;}.records-detail-card:last-child {margin-bottom: 0;}.records-detail-card h3 {margin: 0 0 16px;color: #333;font-size: 18px;}.records-detail-list {display: grid;grid-template-columns: repeat(2, minmax(0, 1fr));gap: 14px 18px;}.records-detail-item {display: flex;flex-direction: column;gap: 6px;}.records-detail-item-label {color: #7a8795;font-size: 12px;font-weight: 700;text-transform: uppercase;letter-spacing: 0.05em;}.records-detail-item-value {color: #263445;font-size: 15px;font-weight: 700;line-height: 1.5;}.records-detail-section-head {display: flex;align-items: center;justify-content: space-between;gap: 12px;margin-bottom: 16px;}.records-detail-section-head span {color: #7a8795;font-size: 13px;font-weight: 700;}.records-detail-timeline {display: grid;grid-template-columns: repeat(auto-fit, minmax(10px, 1fr));gap: 5px;}.records-detail-segment {height: 48px;border-radius: 999px;}.records-detail-segment.focused {background: linear-gradient(180deg, #3ab86a 0%, #23a057 100%);}.records-detail-segment.mixed {background: linear-gradient(180deg, #f1b447 0%, #df9a1e 100%);}.records-detail-segment.distracted {background: linear-gradient(180deg, #ec7d7d 0%, #d9534f 100%);}.records-detail-legend {display: flex;flex-wrap: wrap;gap: 16px;margin-top: 14px;color: #667281;font-size: 13px;font-weight: 700;}.records-detail-legend span {display: inline-flex;align-items: center;gap: 8px;}.records-detail-dot {width: 10px;height: 10px;border-radius: 50%;display: inline-block;}.records-detail-dot.focused {background: #23a057;}.records-detail-dot.mixed {background: #df9a1e;}.records-detail-dot.distracted {background: #d9534f;}.records-detail-events {display: grid;gap: 10px;max-height: 280px;overflow-y: auto;}.records-detail-event {display: grid;grid-template-columns: auto 1fr auto;align-items: center;gap: 12px;padding: 12px 14px;background: #f8fbff;border: 1px solid #e1edf9;border-radius: 14px;}.records-detail-event-time {min-width: 52px;color: #3569a8;font-size: 13px;font-weight: 800;}.records-detail-event-copy {min-width: 0;}.records-detail-event-status {color: #243345;font-size: 14px;font-weight: 800;}.records-detail-event-meta {margin-top: 4px;color: #6f7d8c;font-size: 12px;line-height: 1.5;}.records-detail-event-badge {padding: 7px 12px;border-radius: 999px;font-size: 11px;font-weight: 800;letter-spacing: 0.04em;text-transform: uppercase;}.records-detail-event-badge.focused {background: #eaf8ef;color: #1f8a4c;}.records-detail-event-badge.distracted {background: #fff1f1;color: #c24c49;}.records-detail-empty {padding: 16px 18px;border-radius: 14px;background: #f7f9fc;color: #708090;font-weight: 700;}/* ================ SETTINGS PAGE ================ */.settings-container {72 unmodified linesfont-family: 'Nunito', sans-serif;}/* Center the settings buttons and give them more width. */.setting-group .action-btn {display: inline-block; /* Allow buttons to sit side by side. */width: 48%; /* Roughly half-width each, with a small gutter. */margin: 15px 1%; /* Vertical spacing plus horizontal separation. */text-align: center; /* Center the label text. */box-sizing: border-box; /* Prevent borders from forcing an early wrap. */}#save-settings {108 unmodified lines}/* ================ SESSION SUMMARY MODAL ================ *//* These modal styles can be reused for future overlays. */.modal-overlay {position: fixed;top: 0;110 unmodified lineswidth: 90%;flex-direction: column;}.focus-inline-error-standalone {width: 90%;}.focus-flow-overlay {top: 70px;right: 10px;bottom: 10px;left: 10px;}.focus-flow-card {padding: 22px 20px;}.focus-flow-header {flex-direction: column;align-items: flex-start;}.focus-flow-icon {width: 92px;height: 92px;}.focus-flow-grid {grid-template-columns: 1fr;}.focus-flow-steps {grid-template-columns: 1fr;}.focus-flow-footer {flex-direction: column;align-items: stretch;}.focus-flow-button,.focus-flow-secondary {width: 100%;}.records-detail-modal {width: 94vw;padding: 22px 18px;}.records-detail-header,.records-detail-section-head {flex-direction: column;align-items: flex-start;}.records-detail-summary,.records-detail-grid,.records-detail-list {grid-template-columns: 1fr;}.records-detail-event {grid-template-columns: 1fr;align-items: flex-start;}}/* =========================================SESSION RESULT OVERLAY========================================= */.session-result-overlay {position: absolute;top: 0;left: 0;width: 100%;height: 100%;background-color: rgba(0, 0, 0, 0.85); /* Dark semi-transparent backdrop. */display: flex;flex-direction: column;justify-content: center;1 unmodified linecolor: white;z-index: 10;animation: fadeIn 0.5s ease;backdrop-filter: blur(5px); /* Optional background blur. */}.session-result-overlay h3 {font-size: 32px;margin-bottom: 30px;color: #4cd137; /* Green title accent. */text-transform: uppercase;letter-spacing: 2px;}1 unmodified line.session-result-overlay .result-item {display: flex;justify-content: space-between;width: 200px; /* Keep the stat row compact. */margin-bottom: 15px;font-size: 20px;border-bottom: 1px solid rgba(255,255,255,0.2);8 unmodified lines.session-result-overlay .value {color: #fff;font-weight: bold;font-family: 'Courier New', monospace; /* Give the values a data-like look. */}@keyframes fadeIn {1 unmodified lineto { opacity: 1; transform: scale(1); }}/* ================= Welcome modal styles ================= */.welcome-modal-overlay {position: fixed;top: 0; left: 0; right: 0; bottom: 0;17 unmodified lines.welcome-modal p { margin-bottom: 30px; color: #ccc; }.welcome-buttons { display: flex; gap: 20px; justify-content: center; }/* ================= Top-left avatar styles ================= */.avatar-container {position: absolute;left: 20px;cursor: pointer;z-index: 1;}.avatar-circle {12 unmodified lines.avatar-circle.user { background-color: #555; }.avatar-circle.admin { background-color: #ffaa00; border-color: #fff; box-shadow: 0 0 10px rgba(255, 170, 0, 0.5); }/* ================= Home page 2x2 responsive button grid ================= */.home-button-grid {display: grid;grid-template-columns: 1fr 1fr; /* Force a clean two-column split. */gap: 20px; /* Spacing between buttons. */width: 100%;max-width: 500px; /* Cap the width so the grid does not feel oversized. */margin: 40px auto 0 auto; /* Add top spacing and keep the grid centered. */}.home-button-grid .btn-main {width: 100%;height: 60px; /* Keep all tiles at the same height. */margin: 0; /* Remove default outer spacing. */padding: 10px;font-size: 1rem;display: flex;justify-content: center;align-items: center;text-align: center;box-sizing: border-box; /* Prevent padding and borders from breaking the grid. */}/* Mobile-only scaling for screens below 600px. */@media (max-width: 600px) {#top-menu {justify-content: flex-start;padding: 0 12px 0 68px;}.menu-btn {padding: 10px 14px;font-size: 0.92rem;}.separator {margin: 0 2px;}.home-button-grid {gap: 15px;max-width: 90%;3 unmodified linesheight: 50px;font-size: 0.85rem;}}
15 unmodified lines1617181920212214 unmodified lines373839404142438 unmodified lines5253545556575817 unmodified lines767778798081821 unmodified line8485868788893 unmodified lines9394959615 unmodified linesconst [sessionResult, setSessionResult] = useState(null);const [role, setRole] = useState('user');//useEffect(() => {fetch('/api/history', { method: 'DELETE' }).catch(err => console.error(err));14 unmodified lines};}, []);//const handleAvatarClick = () => {setActiveTab('home');};8 unmodified lines</div><button className={`menu-btn ${activeTab === 'focus' ? 'active' : ''}`} onClick={() => setActiveTab('focus')}>Start Focus {isSessionActive && <span style={{marginLeft: '8px', color: '#00FF00'}}>●</span>}</button><div className="separator"></div>17 unmodified lines</button></nav>{/* pass state to Home */}{activeTab === 'home' && <Home setActiveTab={setActiveTab} role={role} setRole={setRole} />}<FocusPageLocal1 unmodified linesessionResult={sessionResult}setSessionResult={setSessionResult}isActive={activeTab === 'focus'}/>{activeTab === 'achievement' && <Achievement />}{activeTab === 'records' && <Records />}3 unmodified lines);}export default App;15 unmodified lines1617181920212214 unmodified lines373839404142438 unmodified lines5253545556575817 unmodified lines767778798081821 unmodified line848586878889903 unmodified lines9495969715 unmodified linesconst [sessionResult, setSessionResult] = useState(null);const [role, setRole] = useState('user');// Clear persisted history on the initial page load without showing a prompt.useEffect(() => {fetch('/api/history', { method: 'DELETE' }).catch(err => console.error(err));14 unmodified lines};}, []);// Clicking the avatar always returns the user to the Home tab.const handleAvatarClick = () => {setActiveTab('home');};8 unmodified lines</div><button className={`menu-btn ${activeTab === 'focus' ? 'active' : ''}`} onClick={() => setActiveTab('focus')}>Start Focus {isSessionActive && <span style={{ marginLeft: '8px', color: '#00FF00' }}>●</span>}</button><div className="separator"></div>17 unmodified lines</button></nav>{/* Pass the current role controls down to the Home view. */}{activeTab === 'home' && <Home setActiveTab={setActiveTab} role={role} setRole={setRole} />}<FocusPageLocal1 unmodified linesessionResult={sessionResult}setSessionResult={setSessionResult}isActive={activeTab === 'focus'}role={role}/>{activeTab === 'achievement' && <Achievement />}{activeTab === 'records' && <Records />}3 unmodified lines);}export default App;
10 unmodified lines1112131415161 unmodified line1819202122238 unmodified lines3233343536379 unmodified lines4748495051524 unmodified lines5758596061624 unmodified lines6768697071724 unmodified lines7778798081824 unmodified lines87888990919214 unmodified lines1071081091101111124 unmodified lines11711811912012112210 unmodified linesconst [badges, setBadges] = useState([]);const [loading, setLoading] = useState(true);const formatTime = (seconds) => {const hours = Math.floor(seconds / 3600);const minutes = Math.floor((seconds % 3600) / 60);1 unmodified linereturn `${minutes}m`;};useEffect(() => {fetch('/api/stats/summary').then(res => res.json())8 unmodified lines});}, []);useEffect(() => {const fetchSystem = () => {fetch('/api/stats/system')9 unmodified linesconst calculateBadges = (data) => {const earnedBadges = [];if (data.total_sessions >= 1) {earnedBadges.push({id: 'first-session',4 unmodified lines});}if (data.total_sessions >= 10) {earnedBadges.push({id: 'ten-sessions',4 unmodified lines});}if (data.total_sessions >= 50) {earnedBadges.push({id: 'fifty-sessions',4 unmodified lines});}if (data.avg_focus_score >= 0.8 && data.total_sessions >= 5) {earnedBadges.push({id: 'focus-master',4 unmodified lines});}if (data.streak_days >= 7) {earnedBadges.push({id: 'week-streak',14 unmodified lines});}if (data.total_focus_time >= 36000) {earnedBadges.push({id: 'ten-hours',4 unmodified lines});}const allBadges = [{id: 'first-session',10 unmodified lines111213141516171 unmodified line192021222324258 unmodified lines343536373839409 unmodified lines505152535455564 unmodified lines616263646566674 unmodified lines727374757677784 unmodified lines838485868788894 unmodified lines94959697989910014 unmodified lines1151161171181191201214 unmodified lines12612712812913013113210 unmodified linesconst [badges, setBadges] = useState([]);const [loading, setLoading] = useState(true);// Format total focus time for display.const formatTime = (seconds) => {const hours = Math.floor(seconds / 3600);const minutes = Math.floor((seconds % 3600) / 60);1 unmodified linereturn `${minutes}m`;};// Load summary statistics.useEffect(() => {fetch('/api/stats/summary').then(res => res.json())8 unmodified lines});}, []);// Derive unlocked badges from summary statistics.useEffect(() => {const fetchSystem = () => {fetch('/api/stats/system')9 unmodified linesconst calculateBadges = (data) => {const earnedBadges = [];// First-session badgeif (data.total_sessions >= 1) {earnedBadges.push({id: 'first-session',4 unmodified lines});}// 10-session badgeif (data.total_sessions >= 10) {earnedBadges.push({id: 'ten-sessions',4 unmodified lines});}// 50-session badgeif (data.total_sessions >= 50) {earnedBadges.push({id: 'fifty-sessions',4 unmodified lines});}// Focus Master badge (average focus score > 80%)if (data.avg_focus_score >= 0.8 && data.total_sessions >= 5) {earnedBadges.push({id: 'focus-master',4 unmodified lines});}// Streak badgesif (data.streak_days >= 7) {earnedBadges.push({id: 'week-streak',14 unmodified lines});}// Total focus time badge (10+ hours)if (data.total_focus_time >= 36000) {earnedBadges.push({id: 'ten-hours',4 unmodified lines});}// Full badge catalog, including locked examplesconst allBadges = [{id: 'first-session',
5 unmodified lines67891011121314158 unmodified lines2425262728293015 unmodified lines464748495051525354555657585960616263646566676869707172737475767778792 unmodified lines8283848586878889909192934 unmodified lines98991001011021031041051061071081099 unmodified lines11912012112212312412512612712812913013155 unmodified lines1871881891901911921933 unmodified lines1971981992002012022032042052062072082092102112122135 unmodified linesconst [notificationsEnabled, setNotificationsEnabled] = useState(true);const [threshold, setThreshold] = useState(30);//const fileInputRef = useRef(null);//useEffect(() => {fetch('/api/settings').then(res => res.json())8 unmodified lines.catch(err => console.error("Failed to load settings", err));}, []);//const handleSave = async () => {const settings = {sensitivity: parseInt(sensitivity),15 unmodified lines}};//const handleExport = async () => {try {//const response = await fetch('/api/sessions?filter=all');if (!response.ok) throw new Error("Failed to fetch data");const data = await response.json();//const jsonString = JSON.stringify(data, null, 2);//localStorage.setItem('focus_magic_backup', jsonString);const blob = new Blob([jsonString], { type: 'application/json' });//const url = URL.createObjectURL(blob);const link = document.createElement('a');link.href = url;//link.download = `focus-guard-backup-${new Date().toISOString().slice(0, 10)}.json`;//document.body.appendChild(link);link.click();//document.body.removeChild(link);URL.revokeObjectURL(url);} catch (error) {2 unmodified lines}};//const triggerImport = () => {fileInputRef.current.click();};//const handleFileChange = async (event) => {const file = event.target.files[0];if (!file) return;4 unmodified linesconst content = e.target.result;const sessions = JSON.parse(content);//if (!Array.isArray(sessions)) {throw new Error("Invalid file format: Expected a list of sessions.");}//const response = await fetch('/api/import', {method: 'POST',headers: { 'Content-Type': 'application/json' },9 unmodified lines} catch (err) {alert("Error parsing file: " + err.message);}//event.target.value = '';};reader.readAsText(file);};//const handleClearHistory = async () => {if (!window.confirm("Are you sure? This will delete ALL your session history permanently.")) {return;55 unmodified lines<div className="setting-group"><h2>Data Management</h2>{/* hidden file input, json only */}<inputtype="file"ref={fileInputRef}3 unmodified lines/><div style={{ display: 'flex', gap: '10px', justifyContent: 'center', flexWrap: 'wrap' }}>{/* Export */}<button id="export-data" className="action-btn blue" onClick={handleExport} style={{ width: '30%', minWidth: '120px' }}>Export Data</button>{/* Import */}<button id="import-data" className="action-btn yellow" onClick={triggerImport} style={{ width: '30%', minWidth: '120px' }}>Import Data</button>{/* Clear */}<button id="clear-history" className="action-btn red" onClick={handleClearHistory} style={{ width: '30%', minWidth: '120px' }}>Clear History</button>5 unmodified lines67891011121314158 unmodified lines2425262728293015 unmodified lines464748495051525354555657585960616263646566676869707172737475767778792 unmodified lines8283848586878889909192934 unmodified lines98991001011021031041051061071081099 unmodified lines11912012112212312412512612712812913013155 unmodified lines1871881891901911921933 unmodified lines1971981992002012022032042052062072082092102112122135 unmodified linesconst [notificationsEnabled, setNotificationsEnabled] = useState(true);const [threshold, setThreshold] = useState(30);// Reference to the hidden import input.const fileInputRef = useRef(null);// 1. Load persisted settings.useEffect(() => {fetch('/api/settings').then(res => res.json())8 unmodified lines.catch(err => console.error("Failed to load settings", err));}, []);// 2. Save settings.const handleSave = async () => {const settings = {sensitivity: parseInt(sensitivity),15 unmodified lines}};// 3. Export data.const handleExport = async () => {try {// Fetch the full session history.const response = await fetch('/api/sessions?filter=all');if (!response.ok) throw new Error("Failed to fetch data");const data = await response.json();// Build a JSON blob for download.const jsonString = JSON.stringify(data, null, 2);// Keep a copy in local storage for quick recovery.localStorage.setItem('focus_magic_backup', jsonString);const blob = new Blob([jsonString], { type: 'application/json' });// Create a temporary download link.const url = URL.createObjectURL(blob);const link = document.createElement('a');link.href = url;// Include the current date in the export filename.link.download = `focus-guard-backup-${new Date().toISOString().slice(0, 10)}.json`;// Trigger the browser download.document.body.appendChild(link);link.click();// Clean up temporary elements and URLs.document.body.removeChild(link);URL.revokeObjectURL(url);} catch (error) {2 unmodified lines}};// 4. Trigger the import file chooser.const triggerImport = () => {fileInputRef.current.click();};// 5. Handle file import.const handleFileChange = async (event) => {const file = event.target.files[0];if (!file) return;4 unmodified linesconst content = e.target.result;const sessions = JSON.parse(content);// Basic validation: imported content must be an array.if (!Array.isArray(sessions)) {throw new Error("Invalid file format: Expected a list of sessions.");}// Send the imported payload to the backend for storage.const response = await fetch('/api/import', {method: 'POST',headers: { 'Content-Type': 'application/json' },9 unmodified lines} catch (err) {alert("Error parsing file: " + err.message);}// Reset the input so the same file can be selected again.event.target.value = '';};reader.readAsText(file);};// 6. Clear all history.const handleClearHistory = async () => {if (!window.confirm("Are you sure? This will delete ALL your session history permanently.")) {return;55 unmodified lines<div className="setting-group"><h2>Data Management</h2>{/* Hidden file input that only accepts JSON files. */}<inputtype="file"ref={fileInputRef}3 unmodified lines/><div style={{ display: 'flex', gap: '10px', justifyContent: 'center', flexWrap: 'wrap' }}>{/* Export button */}<button id="export-data" className="action-btn blue" onClick={handleExport} style={{ width: '30%', minWidth: '120px' }}>Export Data</button>{/* Import button */}<button id="import-data" className="action-btn yellow" onClick={triggerImport} style={{ width: '30%', minWidth: '120px' }}>Import Data</button>{/* Clear button */}<button id="clear-history" className="action-btn red" onClick={handleClearHistory} style={{ width: '30%', minWidth: '120px' }}>Clear History</button>
5 unmodified lines678910111213144 unmodified lines192021222324251 unmodified line27282930313233343536374 unmodified lines4243444546474865 unmodified lines11411511611711811912012112212312412512612712812925 unmodified lines1551561571581591601613 unmodified lines1651661671681691701716 unmodified lines17817918018118218318413 unmodified lines19819920020120220320416 unmodified lines2212222232242252262272282292302312322332342352362 unmodified lines2392402412422432442455 unmodified linesconst videoRef = displayVideoRef;//const formatDuration = (seconds) => {//if (seconds === 0) return "0s";const mins = Math.floor(seconds / 60);4 unmodified linesuseEffect(() => {if (!videoManager) return;//const originalOnStatusUpdate = videoManager.callbacks.onStatusUpdate;videoManager.callbacks.onStatusUpdate = (isFocused) => {setTimelineEvents(prev => {1 unmodified lineif (newEvents.length > 60) newEvents.shift();return newEvents;});//if (originalOnStatusUpdate) originalOnStatusUpdate(isFocused);};//return () => {if (videoManager) {videoManager.callbacks.onStatusUpdate = originalOnStatusUpdate;4 unmodified linesconst handleStart = async () => {try {if (videoManager) {setSessionResult(null);setTimelineEvents([]);console.log('🎬 Initializing camera...');65 unmodified lines}};//const handleFloatingWindow = () => {handlePiP();};// ==========================================//// ==========================================const handlePreview = () => {//setSessionResult({duration_seconds: 0,focus_score: 025 unmodified linesreturn (<main id="page-b" className="page" style={pageStyle}>{/* 1. Camera / Display Area */}<section id="display-area" style={{ position: 'relative', overflow: 'hidden' }}><videoref={videoRef}3 unmodified linesstyle={{ width: '100%', height: '100%', objectFit: 'contain' }}/>{/* result overlay */}{sessionResult && (<div className="session-result-overlay"><h3>Session Complete!</h3>6 unmodified lines<span className="value">{(sessionResult.focus_score * 100).toFixed(1)}%</span></div>{/* close preview */}<buttononClick={handleCloseOverlay}style={{13 unmodified lines</section>{/* 2. Timeline Area */}<section id="timeline-area"><div className="timeline-label">Timeline</div><div id="timeline-visuals">16 unmodified lines<div id="timeline-line"></div></section>{/* 3. Control Buttons */}<section id="control-panel"><button id="btn-cam-start" className="action-btn green" onClick={handleStart}>Start</button><button id="btn-floating" className="action-btn yellow" onClick={handleFloatingWindow}>Floating Window</button>{/* preview button */}<buttonid="btn-preview"className="action-btn"style={{ backgroundColor: '#6c5ce7' }}onClick={handlePreview}>Preview Result2 unmodified lines<button id="btn-cam-stop" className="action-btn red" onClick={handleStop}>Stop</button></section>{/* 4. Frame Control */}<section id="frame-control"><label htmlFor="frame-slider">Frame</label><input5 unmodified lines678910111213144 unmodified lines192021222324251 unmodified line27282930313233343536374 unmodified lines4243444546474865 unmodified lines11411511611711811912012112212312412512612712812925 unmodified lines1551561571581591601613 unmodified lines1651661671681691701716 unmodified lines17817918018118218318413 unmodified lines19819920020120220320416 unmodified lines2212222232242252262272282292302312322332342352362 unmodified lines2392402412422432442455 unmodified linesconst videoRef = displayVideoRef;// Helper for formatting a duration in seconds.const formatDuration = (seconds) => {// Show a compact zero state instead of "0m 0s".if (seconds === 0) return "0s";const mins = Math.floor(seconds / 60);4 unmodified linesuseEffect(() => {if (!videoManager) return;// Override the status callback so the timeline updates live.const originalOnStatusUpdate = videoManager.callbacks.onStatusUpdate;videoManager.callbacks.onStatusUpdate = (isFocused) => {setTimelineEvents(prev => {1 unmodified lineif (newEvents.length > 60) newEvents.shift();return newEvents;});// Preserve the original callback if one was already registered.if (originalOnStatusUpdate) originalOnStatusUpdate(isFocused);};// Cleanup only restores callbacks and does not force-stop the session.return () => {if (videoManager) {videoManager.callbacks.onStatusUpdate = originalOnStatusUpdate;4 unmodified linesconst handleStart = async () => {try {if (videoManager) {setSessionResult(null); // Clear any previous summary overlay before starting.setTimelineEvents([]);console.log('🎬 Initializing camera...');65 unmodified lines}};// Floating window helper.const handleFloatingWindow = () => {handlePiP();};// ==========================================// Preview button handler// ==========================================const handlePreview = () => {// Inject placeholder data so the overlay can be previewed on demand.setSessionResult({duration_seconds: 0,focus_score: 025 unmodified linesreturn (<main id="page-b" className="page" style={pageStyle}>{/* 1. Camera / display area */}<section id="display-area" style={{ position: 'relative', overflow: 'hidden' }}><videoref={videoRef}3 unmodified linesstyle={{ width: '100%', height: '100%', objectFit: 'contain' }}/>{/* Session result overlay */}{sessionResult && (<div className="session-result-overlay"><h3>Session Complete!</h3>6 unmodified lines<span className="value">{(sessionResult.focus_score * 100).toFixed(1)}%</span></div>{/* Add a lightweight close button for preview mode. */}<buttononClick={handleCloseOverlay}style={{13 unmodified lines</section>{/* 2. Timeline area */}<section id="timeline-area"><div className="timeline-label">Timeline</div><div id="timeline-visuals">16 unmodified lines<div id="timeline-line"></div></section>{/* 3. Control buttons */}<section id="control-panel"><button id="btn-cam-start" className="action-btn green" onClick={handleStart}>Start</button><button id="btn-floating" className="action-btn yellow" onClick={handleFloatingWindow}>Floating Window</button>{/* Temporarily repurpose the Models button as a preview action. */}<buttonid="btn-preview"className="action-btn"style={{ backgroundColor: '#6c5ce7' }} // Use purple so the preview action stands out.onClick={handlePreview}>Preview Result2 unmodified lines<button id="btn-cam-stop" className="action-btn red" onClick={handleStop}>Stop</button></section>{/* 4. Frame control */}<section id="frame-control"><label htmlFor="frame-slider">Frame</label><input
12345678910111213141516171819202122232425262728293031323334353637381 unmodified line4041424344454647481 unmodified line50515253545556575859606125 unmodified lines878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261275 unmodified lines13313413513613713813914014174 unmodified lines21621721821922022122222322427 unmodified lines2522532542552562572582 unmodified lines26126226326426526626746 unmodified lines31431531631731831932032132232332432532632732832933033133233333433533633725 unmodified lines36336436536636736836937037137237323 unmodified lines3973983994004014024034044054064074084094104114124134144157 unmodified lines42342442542642742842916 unmodified lines446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555import React, { useState, useEffect, useRef } from 'react';function FocusPageLocal({ videoManager, sessionResult, setSessionResult, isActive }) {const [currentFrame, setCurrentFrame] = useState(15);const [timelineEvents, setTimelineEvents] = useState([]);const [stats, setStats] = useState(null);const [systemStats, setSystemStats] = useState(null);const [availableModels, setAvailableModels] = useState([]);const [currentModel, setCurrentModel] = useState('mlp');const localVideoRef = useRef(null);const displayCanvasRef = useRef(null);const pipVideoRef = useRef(null);const pipStreamRef = useRef(null);const formatDuration = (seconds) => {if (seconds === 0) return "0s";const mins = Math.floor(seconds / 60);const secs = Math.floor(seconds % 60);return `${mins}m ${secs}s`;};useEffect(() => {if (!videoManager) return;const originalOnStatusUpdate = videoManager.callbacks.onStatusUpdate;videoManager.callbacks.onStatusUpdate = (isFocused) => {setTimelineEvents(prev => {const newEvents = [...prev, { isFocused, timestamp: Date.now() }];if (newEvents.length > 60) newEvents.shift();return newEvents;});if (originalOnStatusUpdate) originalOnStatusUpdate(isFocused);};const statsInterval = setInterval(() => {if (videoManager && videoManager.getStats) {setStats(videoManager.getStats());1 unmodified line}, 1000);return () => {if (videoManager) {videoManager.callbacks.onStatusUpdate = originalOnStatusUpdate;}clearInterval(statsInterval);};}, [videoManager]);1 unmodified line// Fetch available models on mountuseEffect(() => {fetch('/api/models').then(res => res.json()).then(data => {if (data.available) setAvailableModels(data.available);if (data.current) setCurrentModel(data.current);}).catch(err => console.error('Failed to fetch models:', err));}, []);// Poll server CPU/memory for UI25 unmodified lines}};const handleStart = async () => {try {if (videoManager) {setSessionResult(null);setTimelineEvents([]);console.log('Initializing local camera...');await videoManager.initCamera(localVideoRef.current, displayCanvasRef.current);console.log('Camera initialized');console.log('Starting local streaming...');await videoManager.startStreaming();console.log('Streaming started successfully');}} catch (err) {console.error('Start error:', err);let errorMessage = "Failed to start: ";if (err.name === 'NotAllowedError') {errorMessage += "Camera permission denied. Please allow camera access.";} else if (err.name === 'NotFoundError') {errorMessage += "No camera found. Please connect a camera.";} else if (err.name === 'NotReadableError') {errorMessage += "Camera is already in use by another application.";} else {errorMessage += err.message || "Unknown error occurred.";}alert(errorMessage + "\n\nCheck browser console for details.");}};const handleStop = async () => {if (videoManager) {videoManager.stopStreaming();}try {if (document.pictureInPictureElement === pipVideoRef.current) {5 unmodified linespipVideoRef.current.srcObject = null;}if (pipStreamRef.current) {pipStreamRef.current.getTracks().forEach(t => t.stop());pipStreamRef.current = null;}};const handlePiP = async () => {74 unmodified linestry {await pipVideo.play();} catch (_) {//}//if (isSafariPiP) {27 unmodified lines} catch (err) {console.error('PiP error:', err);alert('Failed to enter Picture-in-Picture: ' + err.message);}};2 unmodified lines};const handleFrameChange = (val) => {const rate = parseInt(val);setCurrentFrame(rate);if (videoManager) {videoManager.setFrameRate(rate);46 unmodified linespointerEvents: 'none'};useEffect(() => {return () => {if (pipVideoRef.current) {pipVideoRef.current.pause();pipVideoRef.current.srcObject = null;}if (pipStreamRef.current) {pipStreamRef.current.getTracks().forEach(t => t.stop());pipStreamRef.current = null;}};}, []);return (<main id="page-b" className="page" style={pageStyle}>{/* 1. Camera / Display Area */}<section id="display-area" style={{ position: 'relative', overflow: 'hidden' }}>{/* hidden PiP video element */}<videoref={pipVideoRef}muted25 unmodified lineswidth: '100%',height: '100%',objectFit: 'contain',backgroundColor: '#000'}}/>{/* result overlay */}{sessionResult && (<div className="session-result-overlay"><h3>Session Complete!</h3>23 unmodified lines</div>)}{/* stats overlay */}{stats && stats.isStreaming && (<div style={{position: 'absolute',top: '10px',right: '10px',background: 'rgba(0,0,0,0.7)',color: 'white',padding: '10px',borderRadius: '5px',fontSize: '12px',fontFamily: 'monospace'}}><div>Session: {stats.sessionId}</div><div>Sent: {stats.framesSent}</div><div>Processed: {stats.framesProcessed}</div>7 unmodified lines</div>)}</div>)}</section>{/* Server CPU / Memory (always visible) */}16 unmodified lines</section>)}{/* 2. Model Selector */}{availableModels.length > 0 && (<section style={{display: 'flex',alignItems: 'center',justifyContent: 'center',gap: '8px',padding: '8px 16px',background: '#1a1a2e',borderRadius: '8px',margin: '8px auto',maxWidth: '600px'}}><span style={{ color: '#aaa', fontSize: '13px', marginRight: '4px' }}>Model:</span>{availableModels.map(name => (<buttonkey={name}onClick={() => handleModelChange(name)}style={{padding: '5px 14px',borderRadius: '16px',border: currentModel === name ? '2px solid #007BFF' : '1px solid #555',background: currentModel === name ? '#007BFF' : 'transparent',color: currentModel === name ? '#fff' : '#ccc',fontSize: '12px',fontWeight: currentModel === name ? 'bold' : 'normal',cursor: 'pointer',textTransform: 'uppercase',transition: 'all 0.2s'}}>{name}</button>))}</section>)}{/* 3. Timeline Area */}<section id="timeline-area"><div className="timeline-label">Timeline</div><div id="timeline-visuals">{timelineEvents.map((event, index) => (<divkey={index}className="timeline-block"style={{backgroundColor: event.isFocused ? '#00FF00' : '#FF0000',width: '10px',height: '20px',display: 'inline-block',marginRight: '2px',borderRadius: '2px'}}title={event.isFocused ? 'Focused' : 'Distracted'}/>))}</div><div id="timeline-line"></div></section>{/* 4. Control Buttons */}<section id="control-panel"><button id="btn-cam-start" className="action-btn green" onClick={handleStart}>Start</button><button id="btn-floating" className="action-btn yellow" onClick={handleFloatingWindow}>Floating Window</button><buttonid="btn-preview"className="action-btn"style={{ backgroundColor: '#6c5ce7' }}onClick={handlePreview}>Preview Result</button><button id="btn-cam-stop" className="action-btn red" onClick={handleStop}>Stop</button></section>{/* 5. Frame Control */}<section id="frame-control"><label htmlFor="frame-slider">Frame Rate (FPS)</label><inputtype="range"id="frame-slider"min="10"max="30"value={currentFrame}onChange={(e) => handleFrameChange(e.target.value)}/><inputtype="number"id="frame-input"min="10"max="30"value={currentFrame}onChange={(e) => handleFrameChange(e.target.value)}/></section></main>);}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341 unmodified line1361371381391401411421431 unmodified line14514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318425 unmodified lines2102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582595 unmodified lines26526626726826927027127227327427527674 unmodified lines35135235335435535635727 unmodified lines3853863873883893903912 unmodified lines39439539639739839940046 unmodified lines44744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758825 unmodified lines61461561661761861962062162262362462562662762862963063163263363463563663763823 unmodified lines6626636646656666676686697 unmodified lines67767867968068168268316 unmodified lines700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792import React, { useState, useEffect, useRef } from 'react';const FLOW_STEPS = {intro: 'intro',permission: 'permission',ready: 'ready'};const FOCUS_STATES = {pending: 'pending',focused: 'focused',notFocused: 'not-focused'};function HelloIcon() {return (<svg width="96" height="96" viewBox="0 0 96 96" aria-hidden="true"><circle cx="48" cy="48" r="40" fill="#007BFF" /><path d="M30 38c0-4 2.7-7 6-7s6 3 6 7" fill="none" stroke="#fff" strokeWidth="6" strokeLinecap="round" /><path d="M54 38c0-4 2.7-7 6-7s6 3 6 7" fill="none" stroke="#fff" strokeWidth="6" strokeLinecap="round" /><path d="M30 52c3 11 10 17 18 17s15-6 18-17" fill="none" stroke="#fff" strokeWidth="6" strokeLinecap="round" /></svg>);}function CameraIcon() {return (<svg width="110" height="110" viewBox="0 0 110 110" aria-hidden="true"><rect x="30" y="36" width="50" height="34" rx="5" fill="none" stroke="#007BFF" strokeWidth="6" /><path d="M24 72h62c0 9-7 16-16 16H40c-9 0-16-7-16-16Z" fill="none" stroke="#007BFF" strokeWidth="6" /><path d="M55 28v8" stroke="#007BFF" strokeWidth="6" strokeLinecap="round" /><circle cx="55" cy="36" r="14" fill="none" stroke="#007BFF" strokeWidth="6" /><circle cx="55" cy="36" r="4" fill="#007BFF" /><path d="M46 83h18" stroke="#007BFF" strokeWidth="6" strokeLinecap="round" /></svg>);}function FocusPageLocal({ videoManager, sessionResult, setSessionResult, isActive, role }) {const [currentFrame, setCurrentFrame] = useState(15);const [timelineEvents, setTimelineEvents] = useState([]);const [stats, setStats] = useState(null);const [systemStats, setSystemStats] = useState(null);const [availableModels, setAvailableModels] = useState([]);const [currentModel, setCurrentModel] = useState('mlp');const [flowStep, setFlowStep] = useState(FLOW_STEPS.intro);const [cameraReady, setCameraReady] = useState(false);const [isStarting, setIsStarting] = useState(false);const [focusState, setFocusState] = useState(FOCUS_STATES.pending);const [cameraError, setCameraError] = useState('');const localVideoRef = useRef(null);const displayCanvasRef = useRef(null);const pipVideoRef = useRef(null);const pipStreamRef = useRef(null);const previewFrameRef = useRef(null);const formatDuration = (seconds) => {if (seconds === 0) return '0s';const mins = Math.floor(seconds / 60);const secs = Math.floor(seconds % 60);return `${mins}m ${secs}s`;};const stopPreviewLoop = () => {if (previewFrameRef.current) {cancelAnimationFrame(previewFrameRef.current);previewFrameRef.current = null;}};const startPreviewLoop = () => {stopPreviewLoop();const renderPreview = () => {const canvas = displayCanvasRef.current;const video = localVideoRef.current;if (!canvas || !video || !cameraReady || videoManager?.isStreaming) {previewFrameRef.current = null;return;}if (video.readyState >= 2) {const ctx = canvas.getContext('2d');ctx.drawImage(video, 0, 0, canvas.width, canvas.height);}previewFrameRef.current = requestAnimationFrame(renderPreview);};previewFrameRef.current = requestAnimationFrame(renderPreview);};const getErrorMessage = (err) => {if (err?.name === 'NotAllowedError') {return 'Camera permission denied. Please allow camera access.';}if (err?.name === 'NotFoundError') {return 'No camera found. Please connect a camera.';}if (err?.name === 'NotReadableError') {return 'Camera is already in use by another application.';}if (err?.target?.url) {return `WebSocket connection failed: ${err.target.url}. Check that the backend server is running.`;}return err?.message || 'Failed to start focus session.';};useEffect(() => {if (!videoManager) return;const originalOnStatusUpdate = videoManager.callbacks.onStatusUpdate;const originalOnSessionEnd = videoManager.callbacks.onSessionEnd;videoManager.callbacks.onStatusUpdate = (isFocused) => {setTimelineEvents((prev) => {const newEvents = [...prev, { isFocused, timestamp: Date.now() }];if (newEvents.length > 60) newEvents.shift();return newEvents;});setFocusState(isFocused ? FOCUS_STATES.focused : FOCUS_STATES.notFocused);if (originalOnStatusUpdate) originalOnStatusUpdate(isFocused);};videoManager.callbacks.onSessionEnd = (summary) => {setFocusState(FOCUS_STATES.pending);setCameraReady(false);if (originalOnSessionEnd) originalOnSessionEnd(summary);};const statsInterval = setInterval(() => {if (videoManager && videoManager.getStats) {setStats(videoManager.getStats());1 unmodified line}, 1000);return () => {videoManager.callbacks.onStatusUpdate = originalOnStatusUpdate;videoManager.callbacks.onSessionEnd = originalOnSessionEnd;clearInterval(statsInterval);};}, [videoManager]);1 unmodified line// Fetch available models on mountuseEffect(() => {fetch('/api/models').then((res) => res.json()).then((data) => {if (data.available) setAvailableModels(data.available);if (data.current) setCurrentModel(data.current);}).catch((err) => console.error('Failed to fetch models:', err));}, []);useEffect(() => {if (flowStep === FLOW_STEPS.ready && cameraReady && !videoManager?.isStreaming) {startPreviewLoop();return;}stopPreviewLoop();}, [cameraReady, flowStep, videoManager?.isStreaming]);useEffect(() => {if (!isActive) {stopPreviewLoop();}}, [isActive]);useEffect(() => {return () => {stopPreviewLoop();if (pipVideoRef.current) {pipVideoRef.current.pause();pipVideoRef.current.srcObject = null;}if (pipStreamRef.current) {pipStreamRef.current.getTracks().forEach((t) => t.stop());pipStreamRef.current = null;}};}, []);// Poll server CPU/memory for UI25 unmodified lines}};const handleEnableCamera = async () => {if (!videoManager) return;try {setCameraError('');await videoManager.initCamera(localVideoRef.current, displayCanvasRef.current);setCameraReady(true);setFlowStep(FLOW_STEPS.ready);setFocusState(FOCUS_STATES.pending);} catch (err) {const errorMessage = getErrorMessage(err);setCameraError(errorMessage);console.error('Camera init error:', err);}};const handleStart = async () => {try {setIsStarting(true);setSessionResult(null);setTimelineEvents([]);setFocusState(FOCUS_STATES.pending);setCameraError('');if (!cameraReady) {await videoManager.initCamera(localVideoRef.current, displayCanvasRef.current);setCameraReady(true);setFlowStep(FLOW_STEPS.ready);}await videoManager.startStreaming();} catch (err) {const errorMessage = getErrorMessage(err);setCameraError(errorMessage);setFocusState(FOCUS_STATES.pending);console.error('Start error:', err);alert(`Failed to start: ${errorMessage}\n\nCheck browser console for details.`);} finally {setIsStarting(false);}};const handleStop = async () => {if (videoManager) {await videoManager.stopStreaming();}try {if (document.pictureInPictureElement === pipVideoRef.current) {5 unmodified linespipVideoRef.current.srcObject = null;}if (pipStreamRef.current) {pipStreamRef.current.getTracks().forEach((t) => t.stop());pipStreamRef.current = null;}stopPreviewLoop();setFocusState(FOCUS_STATES.pending);setCameraReady(false);};const handlePiP = async () => {74 unmodified linestry {await pipVideo.play();} catch (_) {}//if (isSafariPiP) {27 unmodified lines} catch (err) {console.error('PiP error:', err);alert(`Failed to enter Picture-in-Picture: ${err.message}`);}};2 unmodified lines};const handleFrameChange = (val) => {const rate = parseInt(val, 10);setCurrentFrame(rate);if (videoManager) {videoManager.setFrameRate(rate);46 unmodified linespointerEvents: 'none'};const focusStateLabel = {[FOCUS_STATES.pending]: 'Pending',[FOCUS_STATES.focused]: 'Focused',[FOCUS_STATES.notFocused]: 'Not Focused'}[focusState];const introHighlights = [{title: 'Live focus tracking',text: 'Head pose, gaze, and eye openness are read continuously during the session.'},{title: 'Quick setup',text: 'Front-facing light and a stable camera angle give the cleanest preview.'},{title: 'Private by default',text: 'Only session metadata is stored, not the raw camera footage.'}];const permissionSteps = [{title: 'Allow browser access',text: 'Approve the camera prompt so the preview can appear immediately.'},{title: 'Check your framing',text: 'Keep your face visible and centered for more stable landmark detection.'},{title: 'Start when ready',text: 'After the preview appears, use the page controls to begin or stop.'}];const renderIntroCard = () => {if (flowStep === FLOW_STEPS.intro) {return (<div className="focus-flow-overlay"><div className="focus-flow-card"><div className="focus-flow-header"><div><div className="focus-flow-eyebrow">Focus Session</div><h2>Before you begin</h2></div><div className="focus-flow-icon"><HelloIcon /></div></div><p className="focus-flow-lead">The focus page uses your live camera preview to estimate attention in real time.Review the setup notes below, then continue to camera access.</p><div className="focus-flow-grid">{introHighlights.map((item) => (<article key={item.title} className="focus-flow-panel"><h3>{item.title}</h3><p>{item.text}</p></article>))}</div><div className="focus-flow-footer"><div className="focus-flow-note">You can still change frame rate and available model options after the preview loads.</div><button className="focus-flow-button" onClick={() => setFlowStep(FLOW_STEPS.permission)}>Continue</button></div></div></div>);}if (flowStep === FLOW_STEPS.permission && !cameraReady) {return (<div className="focus-flow-overlay"><div className="focus-flow-card"><div className="focus-flow-header"><div><div className="focus-flow-eyebrow">Camera Setup</div><h2>Enable camera access</h2></div><div className="focus-flow-icon"><CameraIcon /></div></div><p className="focus-flow-lead">Once access is granted, your preview appears here and the rest of the Focus pagebehaves like the other dashboard screens.</p><div className="focus-flow-steps">{permissionSteps.map((item, index) => (<div key={item.title} className="focus-flow-step"><div className="focus-flow-step-number">{index + 1}</div><div className="focus-flow-step-copy"><h3>{item.title}</h3><p>{item.text}</p></div></div>))}</div>{cameraError ? <div className="focus-inline-error">{cameraError}</div> : null}<div className="focus-flow-footer"><buttontype="button"className="focus-flow-secondary"onClick={() => setFlowStep(FLOW_STEPS.intro)}>Back</button><button className="focus-flow-button" onClick={handleEnableCamera}>Enable Camera</button></div></div></div>);}return null;};return (<main id="page-b" className="page" style={pageStyle}>{renderIntroCard()}<section id="display-area" className="focus-display-shell"><videoref={pipVideoRef}muted25 unmodified lineswidth: '100%',height: '100%',objectFit: 'contain',backgroundColor: '#101010'}}/>{flowStep === FLOW_STEPS.ready ? (<><div className={`focus-state-pill ${focusState}`}><span className="focus-state-dot" />{focusStateLabel}</div>{!cameraReady && !videoManager?.isStreaming ? (<div className="focus-idle-overlay"><p>Camera is paused.</p><span>Use Start to enable the camera and begin detection.</span></div>) : null}</>) : null}{sessionResult && (<div className="session-result-overlay"><h3>Session Complete!</h3>23 unmodified lines</div>)}{role === 'admin' && stats && stats.isStreaming ? (<div className="focus-debug-panel"><div>Session: {stats.sessionId}</div><div>Sent: {stats.framesSent}</div><div>Processed: {stats.framesProcessed}</div>7 unmodified lines</div>)}</div>) : null}</section>{/* Server CPU / Memory (always visible) */}16 unmodified lines</section>)}{flowStep === FLOW_STEPS.ready ? (<>{availableModels.length > 0 ? (<section className="focus-model-strip"><span className="focus-model-label">Model:</span>{availableModels.map((name) => (<buttonkey={name}onClick={() => handleModelChange(name)}className={`focus-model-button ${currentModel === name ? 'active' : ''}`}>{name}</button>))}</section>) : null}<section id="timeline-area"><div className="timeline-label">Timeline</div><div id="timeline-visuals">{timelineEvents.map((event, index) => (<divkey={index}className="timeline-block"style={{backgroundColor: event.isFocused ? '#00FF00' : '#FF0000',width: '10px',height: '20px',display: 'inline-block',marginRight: '2px',borderRadius: '2px'}}title={event.isFocused ? 'Focused' : 'Distracted'}/>))}</div><div id="timeline-line" /></section><section id="control-panel"><button id="btn-cam-start" className="action-btn green" onClick={handleStart} disabled={isStarting}>{isStarting ? 'Starting...' : 'Start'}</button><button id="btn-floating" className="action-btn yellow" onClick={handlePiP}>Floating Window</button><buttonid="btn-preview"className="action-btn"style={{ backgroundColor: '#ff7a52' }}onClick={handlePreview}>Preview Result</button><button id="btn-cam-stop" className="action-btn red" onClick={handleStop}>Stop</button></section>{cameraError ? (<div className="focus-inline-error focus-inline-error-standalone">{cameraError}</div>) : null}<section id="frame-control"><label htmlFor="frame-slider">Frame Rate (FPS)</label><inputtype="range"id="frame-slider"min="10"max="30"value={currentFrame}onChange={(e) => handleFrameChange(e.target.value)}/><inputtype="number"id="frame-input"min="10"max="30"value={currentFrame}onChange={(e) => handleFrameChange(e.target.value)}/></section></>) : null}</main>);}
2 unmodified lines345678910111213141517 unmodified lines3334353637383917 unmodified lines5758596061626332 unmodified lines9697989910010110210310410517 unmodified lines1231241251262 unmodified linesfunction Home({ setActiveTab, role, setRole }) {const fileInputRef = useRef(null);//const handleNewStart = async () => {await fetch('/api/history', { method: 'DELETE' });setActiveTab('focus');};//const handleAutoImport = async () => {const backup = localStorage.getItem('focus_magic_backup');if (backup) {17 unmodified lines}};//const handleFileChange = async (event) => {const file = event.target.files[0];if (!file) return;17 unmodified linesreader.readAsText(file);};//const handleAdminToggle = async () => {if (role === 'admin') {if (window.confirm("Switch back to User mode? Current data will be cleared.")) {32 unmodified lines<h1>FocusGuard</h1><p>Your productivity monitor assistant.</p>{/* hidden file input outside grid */}<input type="file" ref={fileInputRef} style={{ display: 'none' }} accept=".json" onChange={handleFileChange} />{/* 2x2 button grid */}<div className="home-button-grid"><button className="btn-main" onClick={handleNewStart}>17 unmodified lines);}export default Home;2 unmodified lines345678910111213141517 unmodified lines3334353637383917 unmodified lines5758596061626332 unmodified lines9697989910010110210310410517 unmodified lines1231241251262 unmodified linesfunction Home({ setActiveTab, role, setRole }) {const fileInputRef = useRef(null);// 1. Start a fresh focus workflow.const handleNewStart = async () => {await fetch('/api/history', { method: 'DELETE' });setActiveTab('focus');};// 2. Restore a backup automatically from local storage.const handleAutoImport = async () => {const backup = localStorage.getItem('focus_magic_backup');if (backup) {17 unmodified lines}};// 3. Import a backup file manually.const handleFileChange = async (event) => {const file = event.target.files[0];if (!file) return;17 unmodified linesreader.readAsText(file);};// 4. Toggle between Admin and User modes.const handleAdminToggle = async () => {if (role === 'admin') {if (window.confirm("Switch back to User mode? Current data will be cleared.")) {32 unmodified lines<h1>FocusGuard</h1><p>Your productivity monitor assistant.</p>{/* Keep the hidden file input outside the button grid so it never affects layout. */}<input type="file" ref={fileInputRef} style={{ display: 'none' }} accept=".json" onChange={handleFileChange} />{/* Render the four main actions inside a clean 2x2 grid. */}<div className="home-button-grid"><button className="btn-main" onClick={handleNewStart}>17 unmodified lines);}export default Home;
3 unmodified lines456789101112131415161718194 unmodified lines242526272829308 unmodified lines394041424344452 unmodified lines484950515253544 unmodified lines59606162636465666768697071727374752 unmodified lines787980818283842 unmodified lines878889909192932 unmodified lines969798991001011021031041051061071081094 unmodified lines114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148133 unmodified lines2822832842852862872882892902912922932942952962972982993004 unmodified lines3053063073083093103 unmodified linesconst [filter, setFilter] = useState('all');const [sessions, setSessions] = useState([]);const [loading, setLoading] = useState(false);const chartRef = useRef(null);//const formatDuration = (seconds) => {const mins = Math.floor(seconds / 60);const secs = seconds % 60;return `${mins}m ${secs}s`;};//const formatDate = (dateString) => {const date = new Date(dateString);return date.toLocaleDateString('en-US', {4 unmodified lines});};//const loadSessions = async (filterType) => {setLoading(true);try {8 unmodified lines}};//const drawChart = (data) => {const canvas = chartRef.current;if (!canvas) return;2 unmodified linesconst width = canvas.width = canvas.offsetWidth;const height = canvas.height = 300;//ctx.clearRect(0, 0, width, height);if (data.length === 0) {4 unmodified linesreturn;}//const displayData = data.slice(0, 20).reverse();const padding = 50;const chartWidth = width - padding * 2;const chartHeight = height - padding * 2;const barWidth = chartWidth / displayData.length;//const maxScore = 1.0;//ctx.strokeStyle = '#E0E0E0';ctx.lineWidth = 2;ctx.beginPath();2 unmodified linesctx.lineTo(width - padding, height - padding);ctx.stroke();//ctx.fillStyle = '#666';ctx.font = '12px Nunito';ctx.textAlign = 'right';2 unmodified linesconst value = (maxScore * i / 4 * 100).toFixed(0);ctx.fillText(value + '%', padding - 10, y + 4);//ctx.strokeStyle = '#F0F0F0';ctx.lineWidth = 1;ctx.beginPath();2 unmodified linesctx.stroke();}//displayData.forEach((session, index) => {const barHeight = (session.focus_score / maxScore) * chartHeight;const x = padding + index * barWidth + barWidth * 0.1;const y = height - padding - barHeight;const barActualWidth = barWidth * 0.8;//const score = session.focus_score;let color;if (score >= 0.8) color = '#4A90E2';4 unmodified linesctx.fillStyle = color;ctx.fillRect(x, y, barActualWidth, barHeight);//ctx.strokeStyle = color;ctx.lineWidth = 1;ctx.strokeRect(x, y, barActualWidth, barHeight);});//ctx.textAlign = 'left';ctx.font = 'bold 14px Nunito';ctx.fillStyle = '#4A90E2';ctx.fillText('Focus Score by Session', padding, 30);};//useEffect(() => {loadSessions(filter);}, [filter]);//const handleFilterClick = (filterType) => {setFilter(filterType);};//const handleViewDetails = (sessionId) => {//alert(`View details for session ${sessionId}\n(Feature can be extended later)`);};return (<main id="page-d" className="page"><h1 className="page-title">My Records</h1>133 unmodified lines<td style={{ padding: '15px', textAlign: 'center' }}><buttononClick={() => handleViewDetails(session.id)}style={{padding: '6px 20px',background: '#4A90E2',border: 'none',color: 'white',borderRadius: '6px',cursor: 'pointer',fontSize: '12px',fontWeight: '500',transition: 'background 0.3s'}}onMouseOver={(e) => e.target.style.background = '#357ABD'}onMouseOut={(e) => e.target.style.background = '#4A90E2'}>View</button>4 unmodified lines</table>)}</div></main>);}3 unmodified lines45678910111213141516171819202122232425264 unmodified lines3132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621638 unmodified lines1721731741751761771782 unmodified lines1811821831841851861874 unmodified lines1921931941951961971981992002012022032042052062072082 unmodified lines2112122132142152162172 unmodified lines2202212222232242252262 unmodified lines2292302312322332342352362372382392402412424 unmodified lines247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329133 unmodified lines4634644654664674684694 unmodified lines4744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426433 unmodified linesconst [filter, setFilter] = useState('all');const [sessions, setSessions] = useState([]);const [loading, setLoading] = useState(false);const [detailState, setDetailState] = useState({open: false,loading: false,error: '',session: null});const chartRef = useRef(null);// Format a session duration.const formatDuration = (seconds) => {const safeSeconds = Math.max(0, Number(seconds) || 0);const mins = Math.floor(safeSeconds / 60);const secs = safeSeconds % 60;return `${mins}m ${secs}s`;};// Format a session timestamp for table display.const formatDate = (dateString) => {const date = new Date(dateString);return date.toLocaleDateString('en-US', {4 unmodified lines});};const formatDateTime = (dateString) => {if (!dateString) return 'Not available';const date = new Date(dateString);return date.toLocaleString('en-US', {month: 'short',day: 'numeric',year: 'numeric',hour: '2-digit',minute: '2-digit'});};const parseMetadata = (detectionData) => {if (!detectionData) return {};if (typeof detectionData === 'object') return detectionData;try {return JSON.parse(detectionData);} catch (_) {return {};}};const averageOf = (values) => {const valid = values.filter((value) => Number.isFinite(value));if (valid.length === 0) return null;return valid.reduce((sum, value) => sum + value, 0) / valid.length;};const buildTimelineSegments = (events, maxSegments = 48) => {if (!events.length) return [];const segmentSize = Math.ceil(events.length / maxSegments);const segments = [];for (let i = 0; i < events.length; i += segmentSize) {const slice = events.slice(i, i + segmentSize);const focusedCount = slice.filter((event) => event.isFocused).length;const focusRatio = focusedCount / slice.length;const confidence = averageOf(slice.map((event) => event.confidence));let tone = 'distracted';if (focusRatio >= 0.75) tone = 'focused';else if (focusRatio >= 0.35) tone = 'mixed';segments.push({tone,focusRatio,confidence,count: slice.length});}return segments;};const buildDetailView = (session) => {if (!session) return null;const parsedEvents = (session.events || []).map((event) => {const metadata = parseMetadata(event.detection_data);return {...event,metadata,isFocused: Boolean(event.is_focused),confidence: Number(event.confidence) || 0};});const focusRatio = session.total_frames? session.focused_frames / session.total_frames: parsedEvents.length? parsedEvents.filter((event) => event.isFocused).length / parsedEvents.length: 0;const modelCounts = parsedEvents.reduce((counts, event) => {const model = event.metadata?.model;if (model) counts[model] = (counts[model] || 0) + 1;return counts;}, {});const dominantModel = Object.entries(modelCounts).sort((a, b) => b[1] - a[1])[0]?.[0] || 'Unavailable';const avgConfidence = averageOf(parsedEvents.map((event) => event.confidence));const avgFaceScore = averageOf(parsedEvents.map((event) => Number(event.metadata?.s_face)));const avgEyeScore = averageOf(parsedEvents.map((event) => Number(event.metadata?.s_eye)));const avgMar = averageOf(parsedEvents.map((event) => Number(event.metadata?.mar)));const startTime = session.start_time ? new Date(session.start_time) : null;const timeline = buildTimelineSegments(parsedEvents);const recentEvents = parsedEvents.slice(-10).reverse();return {parsedEvents,focusRatio,dominantModel,avgConfidence,avgFaceScore,avgEyeScore,avgMar,timeline,recentEvents,formatOffset(timestamp) {if (!startTime || !timestamp) return '--';const offsetSeconds = Math.max(0, Math.round((new Date(timestamp) - startTime) / 1000));const mins = Math.floor(offsetSeconds / 60);const secs = offsetSeconds % 60;return mins > 0 ? `${mins}m ${secs}s` : `${secs}s`;}};};const getScoreTone = (score) => {if (score >= 0.8) return 'excellent';if (score >= 0.6) return 'good';if (score >= 0.4) return 'fair';return 'low';};const closeDetails = () => {setDetailState({open: false,loading: false,error: '',session: null});};// Load session rows for the selected filter.const loadSessions = async (filterType) => {setLoading(true);try {8 unmodified lines}};// Draw the session score chart.const drawChart = (data) => {const canvas = chartRef.current;if (!canvas) return;2 unmodified linesconst width = canvas.width = canvas.offsetWidth;const height = canvas.height = 300;// Clear the canvas before each redraw.ctx.clearRect(0, 0, width, height);if (data.length === 0) {4 unmodified linesreturn;}// Use at most the latest 20 sessions in the chart.const displayData = data.slice(0, 20).reverse();const padding = 50;const chartWidth = width - padding * 2;const chartHeight = height - padding * 2;const barWidth = chartWidth / displayData.length;// Use a normalized max score for chart scaling.const maxScore = 1.0;// Draw the chart axes.ctx.strokeStyle = '#E0E0E0';ctx.lineWidth = 2;ctx.beginPath();2 unmodified linesctx.lineTo(width - padding, height - padding);ctx.stroke();// Draw Y-axis labels.ctx.fillStyle = '#666';ctx.font = '12px Nunito';ctx.textAlign = 'right';2 unmodified linesconst value = (maxScore * i / 4 * 100).toFixed(0);ctx.fillText(value + '%', padding - 10, y + 4);// Draw horizontal grid lines.ctx.strokeStyle = '#F0F0F0';ctx.lineWidth = 1;ctx.beginPath();2 unmodified linesctx.stroke();}// Draw the bar chart.displayData.forEach((session, index) => {const barHeight = (session.focus_score / maxScore) * chartHeight;const x = padding + index * barWidth + barWidth * 0.1;const y = height - padding - barHeight;const barActualWidth = barWidth * 0.8;// Map each score to a blue-toned color band.const score = session.focus_score;let color;if (score >= 0.8) color = '#4A90E2';4 unmodified linesctx.fillStyle = color;ctx.fillRect(x, y, barActualWidth, barHeight);// Draw a matching outline around each bar.ctx.strokeStyle = color;ctx.lineWidth = 1;ctx.strokeRect(x, y, barActualWidth, barHeight);});// Draw the chart title.ctx.textAlign = 'left';ctx.font = 'bold 14px Nunito';ctx.fillStyle = '#4A90E2';ctx.fillText('Focus Score by Session', padding, 30);};// Initial load.useEffect(() => {loadSessions(filter);}, [filter]);useEffect(() => {if (!detailState.open) return undefined;const previousOverflow = document.body.style.overflow;document.body.style.overflow = 'hidden';const handleKeyDown = (event) => {if (event.key === 'Escape') {closeDetails();}};window.addEventListener('keydown', handleKeyDown);return () => {document.body.style.overflow = previousOverflow;window.removeEventListener('keydown', handleKeyDown);};}, [detailState.open]);// Filter button handler.const handleFilterClick = (filterType) => {setFilter(filterType);};// Open the detail modal for one session.const handleViewDetails = async (sessionId) => {setDetailState({open: true,loading: true,error: '',session: null});try {const response = await fetch(`/api/sessions/${sessionId}`);if (!response.ok) {throw new Error('Failed to load session details.');}const data = await response.json();setDetailState({open: true,loading: false,error: '',session: data});} catch (error) {setDetailState({open: true,loading: false,error: error.message || 'Failed to load session details.',session: null});}};const detailView = buildDetailView(detailState.session);return (<main id="page-d" className="page"><h1 className="page-title">My Records</h1>133 unmodified lines<td style={{ padding: '15px', textAlign: 'center' }}><buttononClick={() => handleViewDetails(session.id)}className="btn-view">View</button>4 unmodified lines</table>)}</div>{detailState.open ? (<div className="modal-overlay" onClick={closeDetails}><div className="modal-content records-detail-modal" onClick={(event) => event.stopPropagation()}><div className="records-detail-header"><div><div className="records-detail-kicker">Session Detail</div><h2>{detailState.session ? formatDateTime(detailState.session.start_time) : 'Loading session'}</h2><p className="records-detail-subtitle">Review score, capture quality, and a condensed event timeline for this session.</p></div><button type="button" className="records-detail-close" onClick={closeDetails}>Close</button></div>{detailState.loading ? (<div className="records-detail-feedback">Loading session details...</div>) : detailState.error ? (<div className="records-detail-feedback records-detail-feedback-error">{detailState.error}</div>) : detailState.session && detailView ? (<><section className="records-detail-summary"><article className={`records-detail-stat ${getScoreTone(detailState.session.focus_score)}`}><span className="records-detail-stat-label">Focus Score</span><strong className="records-detail-stat-value">{(detailState.session.focus_score * 100).toFixed(1)}%</strong></article><article className="records-detail-stat"><span className="records-detail-stat-label">Duration</span><strong className="records-detail-stat-value">{formatDuration(detailState.session.duration_seconds)}</strong></article><article className="records-detail-stat"><span className="records-detail-stat-label">Frames Analysed</span><strong className="records-detail-stat-value">{detailState.session.total_frames}</strong></article><article className="records-detail-stat"><span className="records-detail-stat-label">Focused Frames</span><strong className="records-detail-stat-value">{(detailView.focusRatio * 100).toFixed(1)}%</strong></article></section><section className="records-detail-grid"><article className="records-detail-card"><h3>Session Info</h3><div className="records-detail-list"><div className="records-detail-item"><span className="records-detail-item-label">Started</span><span className="records-detail-item-value">{formatDateTime(detailState.session.start_time)}</span></div><div className="records-detail-item"><span className="records-detail-item-label">Ended</span><span className="records-detail-item-value">{formatDateTime(detailState.session.end_time)}</span></div><div className="records-detail-item"><span className="records-detail-item-label">Dominant Model</span><span className="records-detail-item-value">{detailView.dominantModel}</span></div><div className="records-detail-item"><span className="records-detail-item-label">Event Samples</span><span className="records-detail-item-value">{detailView.parsedEvents.length}</span></div></div></article><article className="records-detail-card"><h3>Signal Quality</h3><div className="records-detail-list"><div className="records-detail-item"><span className="records-detail-item-label">Avg Confidence</span><span className="records-detail-item-value">{detailView.avgConfidence !== null ? `${(detailView.avgConfidence * 100).toFixed(1)}%` : '--'}</span></div><div className="records-detail-item"><span className="records-detail-item-label">Avg Face Score</span><span className="records-detail-item-value">{detailView.avgFaceScore !== null ? detailView.avgFaceScore.toFixed(3) : '--'}</span></div><div className="records-detail-item"><span className="records-detail-item-label">Avg Eye Score</span><span className="records-detail-item-value">{detailView.avgEyeScore !== null ? detailView.avgEyeScore.toFixed(3) : '--'}</span></div><div className="records-detail-item"><span className="records-detail-item-label">Avg MAR</span><span className="records-detail-item-value">{detailView.avgMar !== null ? detailView.avgMar.toFixed(3) : '--'}</span></div></div></article></section><section className="records-detail-card"><div className="records-detail-section-head"><h3>Focus Timeline</h3><span>{detailView.parsedEvents.length} events condensed</span></div>{detailView.timeline.length > 0 ? (<><div className="records-detail-timeline">{detailView.timeline.map((segment, index) => (<divkey={`${segment.tone}-${index}`}className={`records-detail-segment ${segment.tone}`}title={`${(segment.focusRatio * 100).toFixed(0)}% focused, ${segment.count} events`}/>))}</div><div className="records-detail-legend"><span><i className="records-detail-dot focused" />Focused</span><span><i className="records-detail-dot mixed" />Mixed</span><span><i className="records-detail-dot distracted" />Distracted</span></div></>) : (<div className="records-detail-empty">No event timeline was recorded for this session.</div>)}</section><section className="records-detail-card"><div className="records-detail-section-head"><h3>Recent Events</h3><span>Last {detailView.recentEvents.length} samples</span></div>{detailView.recentEvents.length > 0 ? (<div className="records-detail-events">{detailView.recentEvents.map((event) => (<article key={event.id} className="records-detail-event"><div className="records-detail-event-time">{detailView.formatOffset(event.timestamp)}</div><div className="records-detail-event-copy"><div className="records-detail-event-status">{event.isFocused ? 'Focused' : 'Distracted'}</div><div className="records-detail-event-meta">{event.metadata?.model || 'model n/a'} · confidence {(event.confidence * 100).toFixed(1)}%</div></div><div className={`records-detail-event-badge ${event.isFocused ? 'focused' : 'distracted'}`}>{event.isFocused ? 'OK' : 'Alert'}</div></article>))}</div>) : (<div className="records-detail-empty">No individual event samples are available.</div>)}</section></>) : null}</div></div>) : null}</main>);}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347// src/utils/VideoManager.js
export class VideoManager { constructor(callbacks) { this.callbacks = callbacks || {};
this.videoElement = null; this.stream = null; this.pc = null; this.dataChannel = null;
this.isStreaming = false; this.sessionId = null; this.frameRate = 30;
this.currentStatus = false; this.statusBuffer = []; this.bufferSize = 5;
this.latestDetectionData = null; this.lastConfidence = 0; this.detectionHoldMs = 30;
this.notificationEnabled = true; this.notificationThreshold = 30; this.unfocusedStartTime = null; this.lastNotificationTime = null; this.notificationCooldown = 60000; }
async initCamera(videoRef) { try { this.stream = await navigator.mediaDevices.getUserMedia({ video: { width: { ideal: 640 }, height: { ideal: 480 }, facingMode: 'user' }, audio: false });
this.videoElement = videoRef; return true; } catch (error) { console.error('Camera init error:', error); throw error; } }
async startStreaming() { if (!this.stream) { console.error('❌ No stream available'); throw new Error('Camera stream not initialized'); } this.isStreaming = true;
console.log('📹 Starting streaming...');
// await this.requestNotificationPermission(); // await this.loadNotificationSettings();
this.pc = new RTCPeerConnection({ iceServers: [ { urls: 'stun:stun.l.google.com:19302' }, { urls: 'stun:stun1.l.google.com:19302' }, { urls: 'stun:stun2.l.google.com:19302' }, { urls: 'stun:stun3.l.google.com:19302' }, { urls: 'stun:stun4.l.google.com:19302' } ], iceCandidatePoolSize: 10 });
// this.pc.onconnectionstatechange = () => { console.log('🔗 Connection state:', this.pc.connectionState); };
this.pc.oniceconnectionstatechange = () => { console.log('🧊 ICE connection state:', this.pc.iceConnectionState); };
this.pc.onicegatheringstatechange = () => { console.log('📡 ICE gathering state:', this.pc.iceGatheringState); };
// DataChannel for status updates this.dataChannel = this.pc.createDataChannel('status'); this.dataChannel.onmessage = (event) => { try { const data = JSON.parse(event.data); this.handleServerMessage(data); } catch (e) { console.error('Failed to parse data channel message:', e); } };
this.pc.ontrack = (event) => { const stream = event.streams[0]; if (this.videoElement) { this.videoElement.srcObject = stream; this.videoElement.autoplay = true; this.videoElement.playsInline = true; this.videoElement.play().catch(() => {}); } };
// Add local camera tracks this.stream.getTracks().forEach((track) => { this.pc.addTrack(track, this.stream); });
const offer = await this.pc.createOffer(); await this.pc.setLocalDescription(offer);
// Wait for ICE gathering to complete so SDP includes candidates await new Promise((resolve) => { if (this.pc.iceGatheringState === 'complete') { resolve(); return; } const onIce = () => { if (this.pc.iceGatheringState === 'complete') { this.pc.removeEventListener('icegatheringstatechange', onIce); resolve(); } }; this.pc.addEventListener('icegatheringstatechange', onIce); });
console.log('📤 Sending offer to server...'); const response = await fetch('/api/webrtc/offer', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sdp: this.pc.localDescription.sdp, type: this.pc.localDescription.type }) });
if (!response.ok) { const errorText = await response.text(); console.error('❌ Server error:', errorText); throw new Error(`Server returned ${response.status}: ${errorText}`); }
const answer = await response.json(); console.log('✅ Received answer from server, session_id:', answer.session_id);
await this.pc.setRemoteDescription(answer); console.log('��� Remote description set successfully');
this.sessionId = answer.session_id; if (this.callbacks.onSessionStart) { this.callbacks.onSessionStart(this.sessionId); }
}
async requestNotificationPermission() { if ('Notification' in window && Notification.permission === 'default') { try { await Notification.requestPermission(); } catch (error) { console.error('Failed to request notification permission:', error); } } }
async loadNotificationSettings() { try { const response = await fetch('/api/settings'); const settings = await response.json(); if (settings) { this.notificationEnabled = settings.notification_enabled ?? true; this.notificationThreshold = settings.notification_threshold ?? 30; } } catch (error) { console.error('Failed to load notification settings:', error); } }
sendNotification(title, message) { if (!this.notificationEnabled) return; if ('Notification' in window && Notification.permission === 'granted') { try { const notification = new Notification(title, { body: message, icon: '/vite.svg', badge: '/vite.svg', tag: 'focus-guard-distraction', requireInteraction: false });
// setTimeout(() => notification.close(), 3000); } catch (error) { console.error('Failed to send notification:', error); } } }
handleServerMessage(data) { switch (data.type) { case 'detection': this.updateStatus(data.focused); this.latestDetectionData = { detections: data.detections || [], confidence: data.confidence || 0, focused: data.focused, timestamp: performance.now() }; this.lastConfidence = data.confidence || 0;
if (this.callbacks.onStatusUpdate) { this.callbacks.onStatusUpdate(this.currentStatus); } break; default: break; } }
updateStatus(newFocused) { this.statusBuffer.push(newFocused); if (this.statusBuffer.length > this.bufferSize) { this.statusBuffer.shift(); }
if (this.statusBuffer.length < this.bufferSize) return false;
const focusedCount = this.statusBuffer.filter(f => f).length; const focusedRatio = focusedCount / this.statusBuffer.length;
const previousStatus = this.currentStatus;
if (focusedRatio >= 0.75) { this.currentStatus = true; } else if (focusedRatio <= 0.25) { this.currentStatus = false; }
// this.handleNotificationLogic(previousStatus, this.currentStatus); }
handleNotificationLogic(previousStatus, currentStatus) { const now = Date.now();
// if (previousStatus && !currentStatus) { this.unfocusedStartTime = now; }
// if (!previousStatus && currentStatus) { this.unfocusedStartTime = null; }
// if (!currentStatus && this.unfocusedStartTime) { const unfocusedDuration = (now - this.unfocusedStartTime) / 1000;
// if (unfocusedDuration >= this.notificationThreshold) { const canSendNotification = !this.lastNotificationTime || (now - this.lastNotificationTime) >= this.notificationCooldown;
if (canSendNotification) { this.sendNotification( '⚠️ Focus Alert', `You've been distracted for ${Math.floor(unfocusedDuration)} seconds. Get back to work!` ); this.lastNotificationTime = now; } } } }
async stopStreaming() { this.isStreaming = false;
try { if (document.pictureInPictureElement) { await document.exitPictureInPicture(); } if (this.videoElement && typeof this.videoElement.webkitSetPresentationMode === 'function') { if (this.videoElement.webkitPresentationMode === 'picture-in-picture') { this.videoElement.webkitSetPresentationMode('inline'); } } } catch (e) { // ignore PiP exit errors }
if (this.pc) { try { this.pc.getSenders().forEach(sender => sender.track && sender.track.stop()); this.pc.close(); } catch (e) { console.error('Failed to close RTCPeerConnection:', e); } this.pc = null; }
if (this.stream) { this.stream.getTracks().forEach(track => track.stop()); this.stream = null; }
if (this.videoElement) { this.videoElement.srcObject = null; }
if (this.sessionId) { try { const response = await fetch('/api/sessions/end', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ session_id: this.sessionId }) }); const summary = await response.json(); if (this.callbacks.onSessionEnd) { this.callbacks.onSessionEnd(summary); } } catch (e) { console.error('Failed to end session:', e); } }
// this.unfocusedStartTime = null; this.lastNotificationTime = null; this.sessionId = null; }
setFrameRate(rate) { this.frameRate = Math.max(1, Math.min(60, rate)); if (this.stream) { const videoTrack = this.stream.getVideoTracks()[0]; if (videoTrack && videoTrack.applyConstraints) { videoTrack.applyConstraints({ frameRate: { ideal: this.frameRate, max: this.frameRate } }).catch(() => {}); } } }}1234567891011121 unmodified line141516171819202122232425263 unmodified lines3031323334353637383940412 unmodified lines44454647484910 unmodified lines60616263646566676869706 unmodified lines7778798081827 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241 unmodified line1261271281291301311321331341351361371381391401411422 unmodified lines14514614714814915015115215315415515615715815916016116216316416516697 unmodified lines264265266267268269270307 unmodified lines57857958058158258358458558658758858959059159259359459559659759811 unmodified lines6106116126136146156168 unmodified lines6256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606615 unmodified lines667668669670671672673// src/utils/VideoManagerLocal.js// WebSocket + Canvas (no WebRTC)export class VideoManagerLocal {constructor(callbacks) {this.callbacks = callbacks || {};this.localVideoElement = null;this.displayVideoElement = null;this.canvas = null;this.stream = null;this.ws = null;1 unmodified linethis.isStreaming = false;this.sessionId = null;this.sessionStartTime = null;this.frameRate = 15;this.captureInterval = null;this.currentStatus = false;this.statusBuffer = [];this.bufferSize = 3;this.latestDetectionData = null;this.lastConfidence = 0;3 unmodified lines// Continuous render loopthis._animFrameId = null;this.notificationEnabled = true;this.notificationThreshold = 30;this.unfocusedStartTime = null;this.lastNotificationTime = null;this.notificationCooldown = 60000;this.stats = {framesSent: 0,framesProcessed: 0,2 unmodified lines};}async initCamera(localVideoRef, displayCanvasRef) {try {console.log('Initializing local camera...');10 unmodified linesthis.localVideoElement = localVideoRef;this.displayCanvas = displayCanvasRef;if (this.localVideoElement) {this.localVideoElement.srcObject = this.stream;this.localVideoElement.play();}this.canvas = document.createElement('canvas');this.canvas.width = 320;this.canvas.height = 240;6 unmodified lines}}async startStreaming() {if (!this.stream) {throw new Error('Camera not initialized');7 unmodified linesconsole.log('Starting WebSocket streaming...');this.isStreaming = true;// Fetch tessellation topology (once)if (!this._tessellation) {try {const res = await fetch('/api/mesh-topology');const data = await res.json();this._tessellation = data.tessellation; // [[start, end], ...]} catch (e) {console.warn('Failed to fetch mesh topology:', e);}}//await this.requestNotificationPermission();await this.loadNotificationSettings();//await this.connectWebSocket();//this.startCapture();// Start continuous render loop for smooth videothis._lastDetection = null;this._startRenderLoop();console.log('Streaming started');}//async connectWebSocket() {return new Promise((resolve, reject) => {const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';1 unmodified lineconsole.log('Connecting to WebSocket:', wsUrl);this.ws = new WebSocket(wsUrl);this.ws.onopen = () => {console.log('WebSocket connected');//this.ws.send(JSON.stringify({ type: 'start_session' }));resolve();};this.ws.onmessage = (event) => {try {const data = JSON.parse(event.data);this.handleServerMessage(data);2 unmodified lines}};this.ws.onerror = (error) => {console.error('WebSocket error:', error);reject(error);};this.ws.onclose = () => {console.log('WebSocket disconnected');if (this.isStreaming) {console.log('Attempting to reconnect...');setTimeout(() => this.connectWebSocket(), 2000);}};});}//startCapture() {const interval = 1000 / this.frameRate;this._sendingBlob = false; // prevent overlapping toBlob calls97 unmodified lines}}//handleServerMessage(data) {switch (data.type) {case 'session_started':307 unmodified linesthis.isStreaming = false;// Stop render loopthis._stopRenderLoop();this._lastDetection = null;//if (this.captureInterval) {clearInterval(this.captureInterval);this.captureInterval = null;}//if (this.ws && this.ws.readyState === WebSocket.OPEN && this.sessionId) {const sessionId = this.sessionId;//const waitForSessionEnd = new Promise((resolve) => {const originalHandler = this.ws.onmessage;const timeout = setTimeout(() => {11 unmodified linesthis.ws.onmessage = originalHandler;resolve();} else {//this.handleServerMessage(data);}} catch (e) {8 unmodified linessession_id: sessionId}));//await waitForSessionEnd;}//await new Promise(resolve => setTimeout(resolve, 200));//if (this.ws) {this.ws.close();this.ws = null;}//if (this.stream) {this.stream.getTracks().forEach(track => track.stop());this.stream = null;}//if (this.localVideoElement) {this.localVideoElement.srcObject = null;}//if (this.displayCanvas) {const ctx = this.displayCanvas.getContext('2d');ctx.clearRect(0, 0, this.displayCanvas.width, this.displayCanvas.height);}//this.unfocusedStartTime = null;this.lastNotificationTime = null;5 unmodified linesthis.frameRate = Math.max(10, Math.min(30, rate));console.log(`Frame rate set to ${this.frameRate} FPS`);//if (this.isStreaming && this.captureInterval) {clearInterval(this.captureInterval);this.startCapture();1234567891011121 unmodified line141516171819202122232425262728293 unmodified lines33343536373839404142434445462 unmodified lines4950515253545510 unmodified lines666768697071727374757677786 unmodified lines858687888990917 unmodified lines991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621 unmodified line1641651661671681691701711721731741751761771781791801811821831841851861871881891901912 unmodified lines19419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223397 unmodified lines331332333334335336337307 unmodified lines64564664764864965065165265365465565665765865966066166266366466566666766866967011 unmodified lines6826836846856866876888 unmodified lines6976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327335 unmodified lines739740741742743744745// src/utils/VideoManagerLocal.js// Local video processing implementation using WebSocket + Canvas, without WebRTC.export class VideoManagerLocal {constructor(callbacks) {this.callbacks = callbacks || {};this.localVideoElement = null; // Local camera preview element.this.displayVideoElement = null; // Processed output display element.this.canvas = null;this.stream = null;this.ws = null;1 unmodified linethis.isStreaming = false;this.sessionId = null;this.sessionStartTime = null;this.frameRate = 15; // Lower FPS reduces transfer and processing load.this.captureInterval = null;this.reconnectTimeout = null;// Status smoothingthis.currentStatus = false;this.statusBuffer = [];this.bufferSize = 3;// Detection datathis.latestDetectionData = null;this.lastConfidence = 0;3 unmodified lines// Continuous render loopthis._animFrameId = null;// Notification statethis.notificationEnabled = true;this.notificationThreshold = 30;this.unfocusedStartTime = null;this.lastNotificationTime = null;this.notificationCooldown = 60000;// Performance metricsthis.stats = {framesSent: 0,framesProcessed: 0,2 unmodified lines};}// Initialize the cameraasync initCamera(localVideoRef, displayCanvasRef) {try {console.log('Initializing local camera...');10 unmodified linesthis.localVideoElement = localVideoRef;this.displayCanvas = displayCanvasRef;// Show the local camera streamif (this.localVideoElement) {this.localVideoElement.srcObject = this.stream;this.localVideoElement.play();}// Create a smaller capture canvas for faster encoding and transfer.this.canvas = document.createElement('canvas');this.canvas.width = 320;this.canvas.height = 240;6 unmodified lines}}// Start streamingasync startStreaming() {if (!this.stream) {throw new Error('Camera not initialized');7 unmodified linesconsole.log('Starting WebSocket streaming...');this.isStreaming = true;try {// Fetch tessellation topology (once)if (!this._tessellation) {try {const res = await fetch('/api/mesh-topology');const data = await res.json();this._tessellation = data.tessellation; // [[start, end], ...]} catch (e) {console.warn('Failed to fetch mesh topology:', e);}}// Request notification permissionawait this.requestNotificationPermission();await this.loadNotificationSettings();// Open the WebSocket connectionawait this.connectWebSocket();// Start sending captured frames on a timerthis.startCapture();// Start continuous render loop for smooth videothis._lastDetection = null;this._startRenderLoop();console.log('Streaming started');} catch (error) {this.isStreaming = false;this._stopRenderLoop();this._lastDetection = null;if (this.captureInterval) {clearInterval(this.captureInterval);this.captureInterval = null;}if (this.reconnectTimeout) {clearTimeout(this.reconnectTimeout);this.reconnectTimeout = null;}if (this.ws) {this.ws.onopen = null;this.ws.onmessage = null;this.ws.onerror = null;this.ws.onclose = null;try {this.ws.close();} catch (_) {}this.ws = null;}throw error instanceof Error ? error : new Error('Failed to start video streaming.');}}// Connect the WebSocketasync connectWebSocket() {return new Promise((resolve, reject) => {const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';1 unmodified lineconsole.log('Connecting to WebSocket:', wsUrl);const socket = new WebSocket(wsUrl);this.ws = socket;let settled = false;let opened = false;const rejectWithMessage = (message) => {if (settled) return;settled = true;reject(new Error(message));};socket.onopen = () => {opened = true;settled = true;console.log('WebSocket connected');// Send the start-session control messagesocket.send(JSON.stringify({ type: 'start_session' }));resolve();};socket.onmessage = (event) => {try {const data = JSON.parse(event.data);this.handleServerMessage(data);2 unmodified lines}};socket.onerror = () => {console.error('WebSocket error:', { url: wsUrl, readyState: socket.readyState });rejectWithMessage(`Failed to connect to ${wsUrl}. Check that the backend server is running and reachable.`);};socket.onclose = (event) => {console.log('WebSocket disconnected', event.code, event.reason);if (this.ws === socket) {this.ws = null;}if (!opened) {rejectWithMessage(`WebSocket closed before connection was established (${event.code || 'no code'}). Check that the backend server is running on the expected port.`);return;}if (this.isStreaming) {console.log('Attempting to reconnect...');if (this.reconnectTimeout) {clearTimeout(this.reconnectTimeout);}this.reconnectTimeout = setTimeout(() => {this.reconnectTimeout = null;if (!this.isStreaming) return;this.connectWebSocket().catch((error) => {console.error('Reconnect failed:', error);});}, 2000);}};});}// Capture and send frames (binary blobs for speed)startCapture() {const interval = 1000 / this.frameRate;this._sendingBlob = false; // prevent overlapping toBlob calls97 unmodified lines}}// Handle messages from the serverhandleServerMessage(data) {switch (data.type) {case 'session_started':307 unmodified linesthis.isStreaming = false;if (this.reconnectTimeout) {clearTimeout(this.reconnectTimeout);this.reconnectTimeout = null;}// Stop the render loopthis._stopRenderLoop();this._lastDetection = null;// Stop frame captureif (this.captureInterval) {clearInterval(this.captureInterval);this.captureInterval = null;}// Send the end-session request and wait for the responseif (this.ws && this.ws.readyState === WebSocket.OPEN && this.sessionId) {const sessionId = this.sessionId;// Wait for the session_ended messageconst waitForSessionEnd = new Promise((resolve) => {const originalHandler = this.ws.onmessage;const timeout = setTimeout(() => {11 unmodified linesthis.ws.onmessage = originalHandler;resolve();} else {// Continue handling non-terminal messagesthis.handleServerMessage(data);}} catch (e) {8 unmodified linessession_id: sessionId}));// Wait for the response or a timeoutawait waitForSessionEnd;}// Delay socket shutdown briefly so pending messages can flushawait new Promise(resolve => setTimeout(resolve, 200));// Close the WebSocketif (this.ws) {this.ws.close();this.ws = null;}// Stop the cameraif (this.stream) {this.stream.getTracks().forEach(track => track.stop());this.stream = null;}// Clear the video elementif (this.localVideoElement) {this.localVideoElement.srcObject = null;}// Clear the canvasif (this.displayCanvas) {const ctx = this.displayCanvas.getContext('2d');ctx.clearRect(0, 0, this.displayCanvas.width, this.displayCanvas.height);}// Reset transient statethis.unfocusedStartTime = null;this.lastNotificationTime = null;5 unmodified linesthis.frameRate = Math.max(10, Math.min(30, rate));console.log(`Frame rate set to ${this.frameRate} FPS`);// Restart capture if streaming is already activeif (this.isStreaming && this.captureInterval) {clearInterval(this.captureInterval);this.startCapture();
123import collectionsimport globimport json12345from __future__ import annotationsimport collectionsimport globimport json
12345678910111213141516171819import { defineConfig } from 'vite'import react from '@vitejs/plugin-react'export default defineConfig({plugins: [react()],server: {proxy: {'/api': {target: 'http://localhost:8000',changeOrigin: true,secure: false,},'/ws': {target: 'ws://localhost:8000',ws: true,}}}})123456789101112131415161718192021222324252627import { defineConfig, loadEnv } from 'vite'import react from '@vitejs/plugin-react'export default defineConfig(({ mode }) => {const env = loadEnv(mode, process.cwd(), '')const backendUrl = env.VITE_BACKEND_URL || 'http://localhost:7860'const backendWsUrl = backendUrl.replace(/^http/, 'ws')return {plugins: [react()],server: {proxy: {'/api': {target: backendUrl,changeOrigin: true,secure: false,},'/ws': {target: backendWsUrl,ws: true,changeOrigin: true,secure: false,}}}}})
README.md+6
main.py+24-5
models/face_mesh.py+6-1
models/head_pose.py+2
package-lock.json+9
src/App.css+758-39
src/App.jsx+6-5
src/components/Achievement.jsx+10
src/components/Customise.jsx+21-21
src/components/FocusPage.jsx+17-17
src/components/FocusPageLocal.jsx+405-168
src/components/Home.jsx+7-7
src/components/Records.jsx+368-35
src/utils/VideoManager.jsDeleted-347
src/utils/VideoManagerLocal.js+123-51
ui/pipeline.py+2
vite.config.js+22-14