diff --git a/README.md b/README.md index eb85d7e..52ddcaa 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ A complete static Python and Git workshop for neuroscience and psychology resear - `tools/`: reproducible archives, notebook execution, site/link/snippet checks, scientific illustration generation, and a real local Git workflow check. - `.github/workflows/validate-and-deploy.yml`: validation and optional GitHub Pages deployment after the owner uploads this repository. -There is no backend, database, login, or paid service. Lessons are Markdown/Quarto; interactive behavior is plain JavaScript with no build tool. Quarto supplies navigation, search, highlighted/copied code, tabs, and theme switching. The live notebook lab runs real Python in a dedicated Web Worker using Pyodide 0.27.7 with bundled NumPy/pandas/Matplotlib. At build time, a download recipe fetches about 32 MB from the pinned official distribution and verifies wheel hashes. The built website serves these assets itself; browser execution needs no external CDN. A first build needs internet. Serving the built directory locally allows practice without external network access; no service worker/offline browser cache is promised. +There is no backend, database, login, or paid service. Lessons are Markdown/Quarto; interactive behavior is plain JavaScript with no build tool. Quarto supplies navigation, search, highlighted/copied code, tabs, and theme switching. The live notebook lab runs real Python in a dedicated Web Worker using Pyodide 0.27.7 with bundled NumPy/pandas/Matplotlib. At build time, a download recipe fetches about 32 MB from the pinned official distribution and verifies wheel hashes. The built website serves these assets itself; browser execution needs no external CDN. A first build needs internet. Serving the built directory locally allows practice without external network access. On HTTPS and localhost, a service worker caches the pinned runtime files so a fresh Python session can reuse the same download. The page and workshop data are loaded separately. Website: [Research / Code on GitHub Pages](https://yoavkedem1.github.io/labCodePractice/). diff --git a/site/_quarto.yml b/site/_quarto.yml index 9447881..359be1c 100644 --- a/site/_quarto.yml +++ b/site/_quarto.yml @@ -70,7 +70,7 @@ format: code-overflow: wrap highlight-style: github include-after-body: - - text: '' + - text: '' link-external-newwindow: true smooth-scroll: false lang: en diff --git a/site/assets/PYTHON-RUNTIME.md b/site/assets/PYTHON-RUNTIME.md index e800ef8..f46d8e6 100644 --- a/site/assets/PYTHON-RUNTIME.md +++ b/site/assets/PYTHON-RUNTIME.md @@ -4,7 +4,7 @@ The workshop bundles the official Pyodide **0.27.7** distribution from https://cdn.jsdelivr.net/pyodide/v0.27.7/full/ using `tools/fetch_pyodide.py`. Core assets are version-pinned. Wheel SHA-256 checksums are verified against the distribution's pyodide-lock.json. runtime-manifest.json records downloaded -files, byte counts, and hashes. The built site serves them locally. +files, byte counts, and hashes. The built site serves them locally. The asset-scoped service worker caches these files in browsers with Cache Storage. Its cache key comes from the pinned files and their hashes. Pyodide is MPL-2.0 licensed; its upstream license is retained in the runtime. The CPython license is retained separately as LICENSE-CPYTHON. Scientific diff --git a/site/assets/notebook-lab.js b/site/assets/notebook-lab.js index c1d9bc9..b60752b 100644 --- a/site/assets/notebook-lab.js +++ b/site/assets/notebook-lab.js @@ -9,6 +9,7 @@ const baseConfig = '[paths]\ndata = "../data/raw/trials.csv"\noutput = "../resul const baseHelper = 'def clean_trials(trials, min_rt_s=0.2, max_rt_s=2.0):\n return trials.loc[trials.reaction_time.between(min_rt_s, max_rt_s)].copy()\n'; const storageKey = 'research-code-notebook-v1'; const pythonLoadTimeout = 300000; +const pythonCacheReady = enablePythonCache(); const guide = q('[data-guide-action]'); const feedback = q('[data-guide-feedback]'); const stepPanel = q('#current-step'); @@ -31,6 +32,7 @@ let ready = false; let busy = false; let sequence = 0; let execution = 0; +let sessionGeneration = 0; const currentStep = () => lesson.steps[stepIndex]; const cellAt = index => q(`[data-cell="${index}"]`); @@ -76,6 +78,7 @@ function markOutputsStale() { } function terminate(reason) { + sessionGeneration++; worker?.terminate(); worker = null; ready = false; @@ -105,9 +108,47 @@ function request(action, values = {}, timeout = 15000) { }); } +async function enablePythonCache() { + try { + if (!navigator.serviceWorker) return; + const url = new URL('./python-runtime-cache.js', import.meta.url); + const registration = navigator.serviceWorker.register(url, {type: 'module', updateViaCache: 'none'}); + let timer; + let settled = false; + let service; + let onStateChange; + try { + await Promise.race([ + registration.then(reg => { + if (settled || reg.active?.state === 'activated') return; + service = reg.installing ?? reg.waiting ?? reg.active; + if (!service || ['activated', 'redundant'].includes(service.state)) return; + return new Promise(resolve => { + onStateChange = () => { + if (['activated', 'redundant'].includes(service.state)) resolve(); + }; + service.addEventListener('statechange', onStateChange); + }); + }), + new Promise(resolve => { timer = setTimeout(resolve, 2500); }) + ]); + } finally { + settled = true; + clearTimeout(timer); + if (onStateChange) service.removeEventListener('statechange', onStateChange); + } + } catch { + // Python can still start if service workers are disabled or unavailable. + } +} + async function start() { if (ready) return; - const activeWorker = new Worker(new URL('./python-worker.js', import.meta.url), {type: 'module'}); + const generation = sessionGeneration; + message('Starting Python…'); + await pythonCacheReady; + if (generation !== sessionGeneration) throw new Error('The Python session was cleared.'); + const activeWorker = new Worker(new URL('./python-worker.js?v=runtime-cache', import.meta.url), {type: 'module'}); worker = activeWorker; worker.onmessage = ({data}) => { if (worker !== activeWorker) return; @@ -126,7 +167,6 @@ async function start() { if (worker === activeWorker) terminate('Python could not load. Reload the page if retrying does not help.'); }; controls(); - message('Starting Python…'); const projectFiles = Object.fromEntries(Object.entries(filePaths).map(([file, path]) => [path, files[file]])); await request('init', {files: projectFiles}, pythonLoadTimeout); ready = true; diff --git a/site/assets/python-runtime-cache.js b/site/assets/python-runtime-cache.js new file mode 100644 index 0000000..e5d9694 --- /dev/null +++ b/site/assets/python-runtime-cache.js @@ -0,0 +1,43 @@ +import {runtimeKey, runtimeFiles} from './python-runtime/cache-config.js'; + +const cachePrefix = `lab-code-python:${self.registration.scope}:`; +const cacheName = cachePrefix + runtimeKey; +const files = new Set(runtimeFiles.map(file => new URL(`./python-runtime/${file}`, self.location.href).href)); + +self.addEventListener('install', event => event.waitUntil(self.skipWaiting())); +self.addEventListener('activate', event => { + event.waitUntil((async () => { + try { + const names = await caches.keys(); + await Promise.all(names.filter(name => name.startsWith(cachePrefix) && name !== cacheName) + .map(name => caches.delete(name))); + } catch { + // The runtime can still load through the browser's network cache. + } + await self.clients.claim(); + })()); +}); + +async function loadRuntimeFile(request) { + let cache; + try { + cache = await caches.open(cacheName); + const cached = await cache.match(request); + if (cached) return {response: cached}; + } catch { + // Storage may be unavailable in some browser sessions. + } + const response = await fetch(request); + const stored = cache && response.status === 200 && !response.redirected + ? cache.put(request, response.clone()).catch(() => {}) + : undefined; + return {response, stored}; +} + +self.addEventListener('fetch', event => { + const {request} = event; + if (request.method !== 'GET' || request.headers.has('Range') || !files.has(request.url)) return; + const result = loadRuntimeFile(request); + event.respondWith(result.then(({response}) => response)); + event.waitUntil(result.then(({stored}) => stored).catch(() => {})); +}); diff --git a/site/assets/python-worker.js b/site/assets/python-worker.js index 9985c40..427b5f9 100644 --- a/site/assets/python-worker.js +++ b/site/assets/python-worker.js @@ -1,9 +1,9 @@ import {loadPyodide} from './python-runtime/pyodide.mjs'; let python; async function initialize(files) { - self.postMessage({type:'status',text:'Downloading Python. The first run can take a few minutes.'}); + self.postMessage({type:'status',text:'Loading the Python runtime…'}); python = await loadPyodide({indexURL:new URL('./python-runtime/',import.meta.url).href}); - self.postMessage({type:'status',text:'Loading pandas, NumPy, and Matplotlib…'}); + self.postMessage({type:'status',text:'Preparing pandas, NumPy, and Matplotlib…'}); await python.loadPackage(['numpy','pandas','matplotlib']); self.postMessage({type:'status',text:'Preparing the workshop data…'}); const project = await fetch(new URL('./browser-project.json',import.meta.url)); diff --git a/site/assets/workshop.js b/site/assets/workshop.js index 5841ff5..dc9cee0 100644 --- a/site/assets/workshop.js +++ b/site/assets/workshop.js @@ -1,5 +1,5 @@ import './ui.js'; -if(document.querySelector('[data-notebook-lab]')) import('./notebook-lab.js'); +if(document.querySelector('[data-notebook-lab]')) import('./notebook-lab.js?v=runtime-cache'); if(document.querySelector('[data-git-dojo]')) import('./git-playground.js'); if(document.querySelector('[data-practice-plan]')) import('./practice.js'); diff --git a/site/notebook-lab.qmd b/site/notebook-lab.qmd index cd843e3..2a1360d 100644 --- a/site/notebook-lab.qmd +++ b/site/notebook-lab.qmd @@ -93,7 +93,7 @@ page-layout: full -

Drafts are saved in this browser when storage is available. Python starts with empty variables each visit. The first run loads about 32 MB.

+

Drafts are saved in this browser when storage is available. Python starts with empty variables each visit. The first run downloads about 32 MB. Your browser can reuse these files for fresh Python sessions.

Run the project in Jupyter

Download the complete project and follow local setup to run the three example notebooks. To run an exported exercise notebook, use the project root as the working directory. Put the exported helpers.py in the project root and analysis.toml in config/.

diff --git a/tools/fetch_pyodide.py b/tools/fetch_pyodide.py index f4031a9..56fdbd1 100644 --- a/tools/fetch_pyodide.py +++ b/tools/fetch_pyodide.py @@ -36,7 +36,7 @@ def fetch(name, expected=None): if not license_path.exists(): with urlopen(url, timeout=30) as response: license_path.write_bytes(response.read()) - fetch('pyodide-lock.json') + lock_asset = fetch('pyodide-lock.json') lock = json.loads((DEST/'pyodide-lock.json').read_text()) assert lock['info']['version'] == VERSION packages = set() @@ -52,5 +52,12 @@ def add(name): files += [(lock['packages'][name]['file_name'], lock['packages'][name]['sha256']) for name in sorted(packages)] with ThreadPoolExecutor(max_workers=6) as pool: manifest = list(pool.map(lambda entry: fetch(*entry), files)) + manifest.insert(0, lock_asset) (DEST/'runtime-manifest.json').write_text(json.dumps({'version': VERSION, 'source': BASE, 'files': manifest}, indent=2)+'\n') + digest = sha256(json.dumps(manifest, sort_keys=True).encode()).hexdigest() + cache_key = json.dumps(f'{VERSION}-{digest}') + cache_files = json.dumps([asset['file'] for asset in manifest]) + (DEST/'cache-config.js').write_text( + f'export const runtimeKey = {cache_key};\nexport const runtimeFiles = {cache_files};\n' + ) print(f'Browser Python {VERSION}: {len(files)} files, {sum(f["bytes"] for f in manifest)/1e6:.1f} MB; wheel checksums verified.')