Created
December 22, 2025 16:21
-
-
Save patrikbraborec/23d2b1b616a317fa49599e2ed7cf68e7 to your computer and use it in GitHub Desktop.
test.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import fs from 'node:fs' | |
| import { Buffer } from 'node:buffer' | |
| async function runPythonInApifySandbox({ baseUrl, pythonCode, timeoutMs }) { | |
| const res = await fetch(`${baseUrl}/execute-code`, { | |
| method: 'POST', | |
| headers: { 'content-type': 'application/json' }, | |
| body: JSON.stringify({ code: pythonCode, language: 'py', timeout: timeoutMs }), | |
| }) | |
| if (!res.ok) { | |
| const bodyText = await res.text().catch(() => '') | |
| throw new Error(`Sandbox request failed: ${res.status} ${res.statusText}\n${bodyText.slice(0, 4000)}`) | |
| } | |
| const text = await res.text() | |
| try { | |
| return JSON.parse(text) | |
| } catch { | |
| throw new Error(`Sandbox returned non-JSON response:\n${text.slice(0, 4000)}`) | |
| } | |
| } | |
| function generateSimpleNumericCsv({ rows = 1000 } = {}) { | |
| const lines = ['id,value'] | |
| for (let i = 0; i < rows; i++) { | |
| // 0..100 random float | |
| lines.push(`${i + 1},${(Math.random() * 100).toFixed(4)}`) | |
| } | |
| return lines.join('\n') + '\n' | |
| } | |
| async function main() { | |
| const baseUrl = process.env.APIFY_SANDBOX_BASE_URL || 'https://zlxhcfrhqcxr.runs.apify.net' | |
| // 1) Create a tiny random dataset locally | |
| const csv = generateSimpleNumericCsv({ rows: 1000 }) | |
| fs.writeFileSync('dataset.csv', csv, 'utf8') | |
| console.log('Generated dataset.csv') | |
| // 2) Encode dataset so Python can read it | |
| const csvB64 = Buffer.from(csv, 'utf8').toString('base64') | |
| // 3) Run a tiny analysis in the Apify sandbox (no AI, no extra deps) | |
| const pythonCode = ` | |
| import base64, csv, statistics | |
| csv_text = base64.b64decode("""${csvB64}""").decode("utf-8") | |
| reader = csv.DictReader(csv_text.splitlines()) | |
| values = [float(r["value"]) for r in reader] | |
| print("rows", len(values)) | |
| print("avg", round(statistics.mean(values), 4)) | |
| print("min", round(min(values), 4)) | |
| print("max", round(max(values), 4)) | |
| ` | |
| console.log('Running Python in Apify sandbox...') | |
| const result = await runPythonInApifySandbox({ | |
| baseUrl, | |
| pythonCode, | |
| timeoutMs: 30_000, | |
| }) | |
| if (result.exitCode !== 0) { | |
| console.error('Sandbox execution failed.') | |
| console.error(result.stderr || '') | |
| process.exitCode = 1 | |
| return | |
| } | |
| process.stdout.write(result.stdout || '') | |
| if (result.stderr) process.stderr.write(result.stderr) | |
| } | |
| await main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment