RynnHub commited on
Commit
d8f7b5b
·
0 Parent(s):
Files changed (4) hide show
  1. Dockerfile +22 -0
  2. README.md +12 -0
  3. app.js +137 -0
  4. package.json +26 -0
Dockerfile ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM mcr.microsoft.com/playwright:focal
2
+
3
+ ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD 1
4
+
5
+ WORKDIR /app
6
+
7
+ COPY package*.json ./
8
+
9
+ RUN npm install
10
+
11
+ RUN apt-get update && apt-get install -y \
12
+ imagemagick \
13
+ ffmpeg \
14
+ && rm -rf /var/lib/apt/lists/*
15
+
16
+ COPY . .
17
+
18
+ RUN npx playwright install --with-deps
19
+
20
+ EXPOSE 7860
21
+
22
+ CMD ["npm", "start"]
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Playwright Api
3
+ emoji: 🔥
4
+ colorFrom: blue
5
+ colorTo: yellow
6
+ sdk: docker
7
+ pinned: false
8
+ license: mit
9
+ short_description: API for executing Playwright scripts
10
+ ---
11
+
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.js ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const { chromium } = require('playwright');
3
+ const cors = require('cors');
4
+ const dotenv = require('dotenv');
5
+ const { NodeVM } = require('vm2');
6
+ const os = require('os');
7
+ const axios = require('axios');
8
+ const fetch = require('node-fetch');
9
+
10
+ dotenv.config();
11
+
12
+ const app = express();
13
+
14
+ app.set('json spaces', 2);
15
+ app.use(express.json());
16
+ app.use(cors());
17
+
18
+ app.get('/', (req, res) => {
19
+ const formatMemory = (bytes) => {
20
+ const gb = bytes / 1024 / 1024 / 1024;
21
+ if (gb >= 1) {
22
+ return gb.toFixed(2) + ' GB';
23
+ } else {
24
+ return (bytes / 1024 / 1024).toFixed(2) + ' MB';
25
+ }
26
+ };
27
+
28
+ const cpuModel = os.cpus().length > 0
29
+ ? os.cpus()[0].model.replace(/\s+/g, ' ').trim()
30
+ : 'Unknown';
31
+
32
+ const uptime = (() => {
33
+ const totalSeconds = os.uptime();
34
+ const days = Math.floor(totalSeconds / (3600 * 24));
35
+ const hours = Math.floor((totalSeconds % (3600 * 24)) / 3600);
36
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
37
+ return `${days}d ${hours}h ${minutes}m`;
38
+ })();
39
+
40
+ const memoryUsedPercentage = ((os.totalmem() - os.freemem()) / os.totalmem() * 100).toFixed(2);
41
+
42
+ res.json({
43
+ status: "online",
44
+ uptime: uptime,
45
+ cpu: {
46
+ model: cpuModel,
47
+ cores: os.cpus().length,
48
+ load: os.loadavg()[0].toFixed(2) + '%'
49
+ },
50
+ memory: {
51
+ total: formatMemory(os.totalmem()),
52
+ used: formatMemory(os.totalmem() - os.freemem()) + ` (${memoryUsedPercentage}%)`,
53
+ free: formatMemory(os.freemem())
54
+ },
55
+ info_api: [
56
+ {
57
+ path: '/run',
58
+ method: 'POST',
59
+ description: 'Run Playwright code in a sandboxed VM environment',
60
+ body: {
61
+ code: 'JavaScript code to execute (required)',
62
+ timeout: 'Execution timeout in milliseconds (optional, default: 300000)'
63
+ }
64
+ }
65
+ ]
66
+ });
67
+ });
68
+
69
+ app.post('/run', async (req, res) => {
70
+ const { code, timeout = 300000 } = req.body;
71
+ if (!code) return res.status(400).json({ error: 'Code cannot be empty' });
72
+
73
+ let output = [];
74
+ const originalLog = console.log;
75
+
76
+ console.log = (...args) => {
77
+ const message = args.map(arg => (typeof arg === 'object' ? JSON.stringify(arg) : arg)).join(' ');
78
+ output.push(message);
79
+ originalLog.apply(console, args);
80
+ };
81
+
82
+ const vm = new NodeVM({
83
+ console: 'inherit',
84
+ sandbox: {},
85
+ require: {
86
+ external: true,
87
+ builtin: ['fs', 'path'],
88
+ root: './',
89
+ mock: {
90
+ playwright: { chromium },
91
+ axios,
92
+ 'node-fetch': fetch,
93
+ },
94
+ },
95
+ });
96
+
97
+ const script = `
98
+ module.exports = async () => {
99
+ ${code}
100
+ };
101
+ `;
102
+
103
+ let runCode;
104
+ try {
105
+ runCode = vm.run(script, 'sandbox.js');
106
+ } catch (error) {
107
+ console.log = originalLog;
108
+ return res.status(500).json({ error: 'Failed to run code', details: error.message });
109
+ }
110
+
111
+ try {
112
+ await runCode();
113
+
114
+ const startTime = Date.now();
115
+ while (output.length === 0 && Date.now() - startTime < timeout) {
116
+ await new Promise(resolve => setTimeout(resolve, 1000));
117
+ }
118
+
119
+ const result = output.length > 0 ? output.pop() : 'No results found.';
120
+ console.log = originalLog;
121
+
122
+ res.json({ output: result });
123
+ } catch (err) {
124
+ console.log = originalLog;
125
+ res.status(500).json({ error: 'Error while executing code', details: err.message });
126
+ }
127
+ });
128
+
129
+ const PORT = process.env.PORT || 7860;
130
+
131
+ app.listen(PORT, async () => {
132
+ console.log(`Server running on port ${PORT}`);
133
+ });
134
+
135
+ process.on('SIGINT', async () => {
136
+ process.exit(0);
137
+ });
package.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "playwright-api",
3
+ "version": "1.0.0",
4
+ "description": "API for executing Playwright scripts with system information",
5
+ "main": "index.js",
6
+ "type": "commonjs",
7
+ "scripts": {
8
+ "start": "node app.js",
9
+ "dev": "nodemon app.js"
10
+ },
11
+ "keywords": ["playwright", "express", "API"],
12
+ "author": "Rynn",
13
+ "license": "MIT",
14
+ "dependencies": {
15
+ "axios": "latest",
16
+ "node-fetch": "latest",
17
+ "express": "latest",
18
+ "playwright": "latest",
19
+ "cors": "latest",
20
+ "dotenv": "latest",
21
+ "vm2": "latest"
22
+ },
23
+ "devDependencies": {
24
+ "nodemon": "latest"
25
+ }
26
+ }