Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/).

Expand Down
2 changes: 1 addition & 1 deletion site/_quarto.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ format:
code-overflow: wrap
highlight-style: github
include-after-body:
- text: '<script type="module" src="/assets/workshop.js"></script>'
- text: '<script type="module" src="/assets/workshop.js?v=runtime-cache"></script>'
link-external-newwindow: true
smooth-scroll: false
lang: en
Expand Down
2 changes: 1 addition & 1 deletion site/assets/PYTHON-RUNTIME.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
44 changes: 42 additions & 2 deletions site/assets/notebook-lab.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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}"]`);
Expand Down Expand Up @@ -76,6 +78,7 @@ function markOutputsStale() {
}

function terminate(reason) {
sessionGeneration++;
worker?.terminate();
worker = null;
ready = false;
Expand Down Expand Up @@ -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;
Expand All @@ -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;
Expand Down
43 changes: 43 additions & 0 deletions site/assets/python-runtime-cache.js
Original file line number Diff line number Diff line change
@@ -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(() => {}));
});
4 changes: 2 additions & 2 deletions site/assets/python-worker.js
Original file line number Diff line number Diff line change
@@ -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));
Expand Down
2 changes: 1 addition & 1 deletion site/assets/workshop.js
Original file line number Diff line number Diff line change
@@ -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');

Expand Down
2 changes: 1 addition & 1 deletion site/notebook-lab.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ page-layout: full
</section>
</div>

<p class="small-note lab-footnote">Drafts are saved in this browser when storage is available. Python starts with empty variables each visit. The first run loads about 32 MB.</p>
<p class="small-note lab-footnote">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.</p>
<details class="notebook-reference">
<summary>Run the project in Jupyter</summary>
<p><a href="downloads/motion-perception.zip">Download the complete project</a> and follow <a href="setup.html">local setup</a> to run the three example notebooks. To run an exported exercise notebook, use the project root as the working directory. Put the exported <code>helpers.py</code> in the project root and <code>analysis.toml</code> in <code>config/</code>.</p>
Expand Down
9 changes: 8 additions & 1 deletion tools/fetch_pyodide.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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.')
Loading