console.warn(Blocked request to ${req.path} from referer ${referer});
res.status(403).json({ message: 'Direct access not allowed' });
};
// Serve index.html and its assets with security
app.use('/', express.static(path.join(__dirname, 'html'), {
index: 'index.html',
if name == "main":
parser = argparse.ArgumentParser(description="Process tileset and add colliders.")
parser.add_argument("image_path", type=str, help="Path to the tileset image")
parser.add_argument("tsx_path", type=str, help="Path to the TSX file")
parser.add_argument("sensitivity", type=int, help="Sensitivity value for edge detection")
parser.add_argument("--output", type=str, default=None, help="Output directory path (optional)")
2.
if name == "main":
parser = argparse.ArgumentParser(description="Process tileset and add colliders.")
parser.add_argument(
"tsxFilesAsArray",
type=str,
help="Comma-separated paths to the tileset files to convert."
)
parser.add_argument(
"outputPath",
type=str,
help="Output path for the converted files."
)
parser.add_argument(
"--format",
type=str,
default="json",
help="Desired output format (default: json)."
)
code
args = parser.parse_args()
# Parse comma-separated file paths into a list
files_to_convert = args.tsxFilesAsArray.split(",")
# Fonksiyonu çağır
convert_files(files_to_convert, args.format)
scripts\collision_detector.py
scripts\convertor.py
bu koda bir server içinde class hazırla
import ile kullanılsın
yani bu scipritler gerekli parametrelerle çağıracağız aslında
bu kısımda uygulamaya yapay zeka katmak için bir class bu classdaki metodlar ile bana bir kullanım kolaylığı sağla
bunu ise react tabanlı arayüzmüzde yap arayüzü geliştirdikten sonra
// Kullanım örneği
runPythonScript('path/to/script.py', ["harita.png","C:\Users\Casper\Downloads\project-bolt-sb1-rfjg3a (1)\project\project_map\tsx\fabrika.tsx",100,--output ${path.join("../","scripts","logs")}])
.then((result) => {
console.log('Python Script Çıktısı:', result);
})
.catch((err) => {
console.error('Hata:', err);
});
code
htüm yapay zeka tabanlı işlemlerde
toplam ram kullanımını sunucu çökmeyecek şekilde ayarla
*/
// Start the server
const PORT = process.env.PORT || 2053;
ioApp.listen(PORT, () => {
console.log(Server running on port ${PORT});
//amaç bunların ayarını otomatikleştirmek
/*
ilk adım(kendi içinde sıra önemli değil)
tsxFile ve PNG harita verileri olarak upload edilir,
sonra otomaik colliderlar hassasiyet ayarı seçilip backend e gönderilir socket.io ile tek taraflı
dikkat:
haritayı indirebilme seçeneğini bir değişkene bağla true ise herkese izin versin değilse izin yok
ve bundan ayrı olarak bir giriş paneli olsun
şimdilik hesap oluşturmaya kapalı tek sabit şifre ile girilir
ama ileride hesapla girişi açabilemem için yine bir değişkene bağlı yao her şey bunun için hazır olsun
/
const handleGenerateColliders = ()=>{
/
socket.send("GenerateColliders",{
PNG: ,
tsxFile: ,
sensitivity: ,
})
*/
}
bu kodları iyileştir diğer komponentlere ellemeden
Sure! Let's enhance your server and React frontend to incorporate a modular AIService class for handling Python scripts, integrate it seamlessly with Socket.IO, and ensure efficient RAM usage. Here's a step-by-step guide to achieve this without manually modifying other components.
1. Server-Side Enhancements
a. Create the AIService Class
We'll create a dedicated class to manage the execution of Python scripts. This class will handle running scripts, managing parameters, and ensuring that RAM usage stays within safe limits.
Create a new file:services/AIService.js
javascript
// services/AIService.js
const { spawn } = require('child_process');
const path = require('path');
class AIService {
constructor(maxRamUsage = 512) { // maxRamUsage in MB
this.maxRamUsage = maxRamUsage;
this.currentRamUsage = 0;
this.taskQueue = [];
this.isProcessing = false;
}
// Method to check RAM usage before starting a new task
async canRunTask(taskRamRequirement) {
const ramUsage = await this.getRamUsage();
return (ramUsage + taskRamRequirement) <= this.maxRamUsage;
}
// Fetch current RAM usage
getRamUsage() {
return new Promise((resolve, reject) => {
const freeMem = os.freemem();
const totalMem = os.totalmem();
const usedMem = (totalMem - freeMem) / (1024 * 1024); // in MB
resolve(usedMem);
});
}
// Enqueue a task
enqueueTask(task) {
this.taskQueue.push(task);
this.processQueue();
}
// Process the task queue
async processQueue() {
if (this.isProcessing || this.taskQueue.length === 0) return;
const task = this.taskQueue.shift();
this.isProcessing = true;
const canRun = await this.canRunTask(task.ramRequirement);
if (!canRun) {
console.warn('RAM usage too high. Task is requeued.');
this.taskQueue.unshift(task); // Requeue the task
this.isProcessing = false;
return;
}
try {
const output = await this.runPythonScript(task.scriptPath, task.args);
task.resolve(output);
} catch (error) {
task.reject(error);
} finally {
this.isProcessing = false;
this.processQueue();
}
}
// General method to run a Python script
runPythonScript(scriptPath, args = []) {
return new Promise((resolve, reject) => {
const pythonProcess = spawn('python', [scriptPath, ...args]);
let output = '';
let errorOutput = '';
pythonProcess.stdout.on('data', (data) => {
output += data.toString();
});
pythonProcess.stderr.on('data', (data) => {
errorOutput += data.toString();
});
pythonProcess.on('close', (code) => {
if (code === 0) {
resolve(output);
} else {
reject(`Python script exited with code ${code}: ${errorOutput}`);
}
});
});
}
// Specific method to process colliders
processColliders(imagePath, tsxPath, sensitivity, outputDir) {
const scriptPath = path.join(__dirname, '../scripts/collision_detector.py');
const args = [imagePath, tsxPath, sensitivity, '--output', outputDir];
const ramRequirement = 100; // Estimated RAM usage in MB
return new Promise((resolve, reject) => {
this.enqueueTask({ scriptPath, args, ramRequirement, resolve, reject });
});
}
// Specific method to convert files
convertFiles(tsxFilesArray, outputPath, format = 'json') {
const scriptPath = path.join(__dirname, '../scripts/convertor.py');
const args = [tsxFilesArray.join(','), outputPath, '--format', format];
const ramRequirement = 150; // Estimated RAM usage in MB
return new Promise((resolve, reject) => {
this.enqueueTask({ scriptPath, args, ramRequirement, resolve, reject });
});
}
}
module.exports = AIService;
Explanation:
Task Queue: To manage multiple AI tasks without overloading the server, tasks are queued and processed one at a time based on available RAM.
RAM Monitoring: Before running a task, the service checks if sufficient RAM is available to prevent server crashes.
Task Enqueuing: Tasks are enqueued with their respective RAM requirements and processed sequentially.
Specific Methods:processColliders and convertFiles are tailored methods to handle specific Python scripts.
b. Integrate AIService into server.js
We'll instantiate the AIService class and set up Socket.IO event handlers to communicate with the React frontend.
Updated server.js:
javascript
Key Enhancements:
AIService Integration:
Instantiation:const aiService = new AIService(1024); initializes the service with a maximum RAM usage of 1024 MB.
Socket.IO Event Handlers: Added generateColliders and convertFiles events to handle AI tasks from the frontend.
Socket.IO Event Handling:
generateColliders: Receives necessary data, invokes processColliders, and sends back the result or error via a callback.
Note: Replace 'path_to_generated_map/map.json' with the actual path where your maps are generated and stored.
3. Additional Recommendations
Security Enhancements:
Authentication: Implement proper authentication mechanisms (e.g., JWT) for secure access.
Input Validation: Validate all inputs from the frontend to prevent malicious data injection.
Environment Variables: Store sensitive information like passwords in environment variables.
Error Handling:
Ensure that all possible errors are handled gracefully both on the server and frontend to enhance user experience.
Scalability:
Consider using worker threads or separate services for handling AI tasks if the load increases.
Implement rate limiting to prevent abuse.
Logging:
Implement comprehensive logging for monitoring and debugging purposes.
User Experience:
Provide progress indicators on the frontend for AI tasks.
Allow users to view logs or statuses of their requests.
Conclusion
With these enhancements, your server is now equipped with a modular AIService class that manages Python script executions efficiently, ensuring the server remains stable by monitoring RAM usage. The React frontend is also improved to handle file uploads, communicate with the server via Socket.IO, and manage user interactions seamlessly. This setup lays a solid foundation for integrating AI capabilities into your application.
Feel free to adjust paths, parameters, and functionalities as per your specific requirements. If you have any further questions or need additional functionalities, feel free to ask!
Not yet included in a published release.
// server.js
require('dotenv').config();
const express = require('express');
const path = require('path');
const cors = require('cors');
const cron = require('node-cron');
const authRoutes = require('./routes/auth');
const blogRoutes = require('./routes/blog');
const projectRoutes = require('./routes/project');
const initializeDatabase = require('./config/init-db');
const pool = require('./config/db'); // Ensure this path is correct
const fs = require('fs-extra'); // Required for file operations in scheduled tasks
const { Server } = require('socket.io');
const { createServer } = require("http");
const GetRamUsage = require('./routes/ServerInfos');
const AIService = require('./services/AIService'); // Import AIService
const corsOption = {
origin: 'http://localhost:3000', // Update to 'https://ovidgame.com' in production
methods: ['GET', 'POST', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
};
const app = express();
// Middleware
app.use(express.json());
// Configure CORS
app.use(cors(corsOption));
// Initialize database
initializeDatabase();
// Custom middleware to check referer
const checkReferer = (req, res, next) => {
const referer = req.headers.referer;
if (req.path === '/index.html' || req.path === '/' || req.path.startsWith('/api/') || req.path.startsWith("/socket.io/")) {
return next();
}
if (referer && (
referer.includes('/index.html') ||
referer.endsWith('/') ||
req.headers['sec-fetch-dest'] === 'script' ||
req.headers['sec-fetch-dest'] === 'style' ||
req.headers['sec-fetch-mode'] === 'cors'
)) {
return next();
}
console.warn(`Blocked request to ${req.path} from referer ${referer}`);
res.status(403).json({ message: 'Direct access not allowed' });
};
// Serve index.html and its assets with security
app.use('/', express.static(path.join(__dirname, 'html'), {
index: 'index.html',
setHeaders: (res, filePath) => {
// Set security headers
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
if (filePath.endsWith('.html')) {
res.setHeader('Cache-Control', 'no-cache');
}
}
}));
// Protected static directories with referer checking
app.use('/blogs', checkReferer, express.static(path.join(__dirname, 'html', 'ovid-blogs')));
app.use('/games', checkReferer, express.static(path.join(__dirname, 'html', 'web-games')));
app.use('/projects', checkReferer, express.static(path.join(__dirname, 'html', 'web-projects')));
app.use('/assets', checkReferer, express.static(path.join(__dirname, 'html', 'assets')));
// API Routes
app.use('/api/auth', authRoutes);
app.use('/api/blogs', blogRoutes);
app.use('/api/projects', projectRoutes);
// Basic route for testing
app.get('/api/status', (req, res) => {
res.json({ message: 'API is running' });
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: 'Internal server error' });
});
// Scheduled task: runs every hour at minute 0
cron.schedule('0 * * * *', async () => {
console.log('Running scheduled project cleanup task.');
let connection;
try {
connection = await pool.getConnection();
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
const [projects] = await connection.execute(
`SELECT * FROM projects WHERE created_at <= ?`,
[oneDayAgo]
);
for (const project of projects) {
const { id, dislikes, likes, path: projectPath } = project;
const totalVotes = likes + dislikes;
const dislikeRatio = totalVotes > 0 ? (dislikes / totalVotes) : 0;
if (dislikeRatio > 0.7) {
try {
// Delete associated votes
await connection.execute(
'DELETE FROM votes WHERE project_id = ?',
[id]
);
// Delete the file
await fs.remove(projectPath);
// Delete the project from the database
await connection.execute(
'DELETE FROM projects WHERE id = ?',
[id]
);
console.log(`Deleted project ID ${id} due to high dislike ratio.`);
} catch (err) {
console.error(`Failed to delete project ID ${id}:`, err.message);
}
}
}
} catch (error) {
console.error('Error during scheduled cleanup:', error.message);
} finally {
if (connection) connection.release();
}
});
// Initialize HTTP server and Socket.IO
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: corsOption,
});
// Instantiate AIService
const aiService = new AIService(1024); // Set max RAM usage to 1024 MB
// Handle Socket.IO connections
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
// Handle collision collider generation
socket.on('generateColliders', async (data, callback) => {
const { imagePath, tsxPath, sensitivity, outputDir } = data;
try {
const result = await aiService.processColliders(imagePath, tsxPath, sensitivity, outputDir);
callback({ success: true, output: result });
} catch (error) {
callback({ success: false, error: error.toString() });
}
});
// Handle file conversion
socket.on('convertFiles', async (data, callback) => {
const { tsxFiles, outputPath, format } = data;
try {
const result = await aiService.convertFiles(tsxFiles, outputPath, format);
callback({ success: true, output: result });
} catch (error) {
callback({ success: false, error: error.toString() });
}
});
// Handle disconnection
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
// Start the server
const PORT = process.env.PORT || 2053;
httpServer.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
// RAM usage is sent every second
setInterval(() => {
const ramUsage = GetRamUsage(); // Ensure this returns RAM usage in MB
io.emit("takeRamUsage", ramUsage);
}, 1000);
});
// TiledAI.js
import React, { useState, useEffect } from 'react';
import { Container, Paper, Typography, Button, TextField, Switch, FormControlLabel } from '@mui/material';
import MapControls from './components/MapControls';
import SystemMonitor from './components/SystemMonitor';
import { io } from "socket.io-client";
import axios from 'axios'; // For API calls like login
const socket = io("http://localhost:2053");
function TiledAI() {
const [difficulty, setDifficulty] = useState(5);
const [detail, setDetail] = useState(5);
const [adherence, setAdherence] = useState(5);
const [ramUsage, setRamUsage] = useState(0);
// State for file uploads
const [imageFile, setImageFile] = useState(null);
const [tsxFile, setTsxFile] = useState(null);
const [outputDir, setOutputDir] = useState('../scripts/logs');
// State for map download permission
const [canDownload, setCanDownload] = useState(false);
// State for authentication
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [password, setPassword] = useState('');
useEffect(() => {
// Listen for RAM usage updates
socket.on("takeRamUsage", (ramUsage) => {
setRamUsage(ramUsage);
});
// Clean up on unmount
return () => {
socket.off("takeRamUsage");
};
}, []);
const handleLogin = async () => {
const fixedPassword = "your-secure-password"; // Replace with a secure password
if (password === fixedPassword) {
setIsAuthenticated(true);
} else {
alert("Incorrect password!");
}
};
const handleGenerateColliders = () => {
if (!imageFile || !tsxFile) {
alert("Please upload both image and TSX files.");
return;
}
// Assume files are already uploaded to the server and paths are obtained
// For simplicity, let's say files are saved in /uploads and paths are provided
const imagePath = `/uploads/${imageFile.name}`;
const tsxPath = `/uploads/${tsxFile.name}`;
const sensitivity = 100; // Or get from user input
socket.emit('generateColliders', { imagePath, tsxPath, sensitivity, outputDir }, (response) => {
if (response.success) {
console.log('Colliders generated:', response.output);
alert('Colliders generated successfully.');
} else {
console.error('Error generating colliders:', response.error);
alert(`Error: ${response.error}`);
}
});
};
const handleConvertFiles = () => {
if (!tsxFile) {
alert("Please upload TSX files.");
return;
}
// Assume files are already uploaded to the server and paths are obtained
const tsxFiles = [tsxFile.name]; // Array of TSX file names
const outputPath = `/converted/${tsxFile.name}.json`; // Example output path
const format = 'json'; // Or get from user input
socket.emit('convertFiles', { tsxFiles, outputPath, format }, (response) => {
if (response.success) {
console.log('Files converted:', response.output);
alert('Files converted successfully.');
} else {
console.error('Error converting files:', response.error);
alert(`Error: ${response.error}`);
}
});
};
const handleExportMap = () => {
if (canDownload) {
// Implement map download functionality
// For example, trigger a file download from the server
window.location.href = '/download/map'; // Replace with actual download endpoint
} else {
alert("Download permission is not granted.");
}
};
const handleFileUpload = async (event, setFile) => {
const file = event.target.files[0];
if (file) {
setFile(file);
// Create FormData to send the file
const formData = new FormData();
formData.append('file', file);
try {
const response = await axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log('File uploaded:', response.data);
} catch (error) {
console.error('Error uploading file:', error);
alert('File upload failed.');
}
}
};
if (!isAuthenticated) {
return (
<Container maxWidth="sm" sx={{ mt: 8 }}>
<Paper elevation={3} sx={{ p: 4 }}>
<Typography variant="h5" gutterBottom>
Login
</Typography>
<TextField
label="Password"
type="password"
fullWidth
value={password}
onChange={(e) => setPassword(e.target.value)}
sx={{ mb: 2 }}
/>
<Button variant="contained" color="primary" onClick={handleLogin}>
Login
</Button>
</Paper>
</Container>
);
}
return (
<Container maxWidth="md" sx={{ mt: 4 }}>
<Paper elevation={3} sx={{ p: 4 }}>
<Typography variant="h4" gutterBottom>
AI Tile Editor
</Typography>
<MapControls
difficulty={difficulty}
detail={detail}
adherence={adherence}
onDifficultyChange={setDifficulty}
onDetailChange={setDetail}
onAdherenceChange={setAdherence}
/>
{/* File Upload Section */}
<div className="flex flex-col gap-2 mt-4">
<Button
variant="contained"
component="label"
color="primary"
>
Upload Image
<input
type="file"
accept="image/png, image/jpeg"
hidden
onChange={(e) => handleFileUpload(e, setImageFile)}
/>
</Button>
{imageFile && <Typography>{imageFile.name}</Typography>}
<Button
variant="contained"
component="label"
color="primary"
>
Upload TSX File
<input
type="file"
accept=".tsx"
hidden
onChange={(e) => handleFileUpload(e, setTsxFile)}
/>
</Button>
{tsxFile && <Typography>{tsxFile.name}</Typography>}
</div>
{/* Allow Download Toggle */}
<FormControlLabel
control={
<Switch
checked={canDownload}
onChange={(e) => setCanDownload(e.target.checked)}
color="primary"
/>
}
label="Allow Map Download"
sx={{ mt: 2 }}
/>
<div className="flex gap-2 mt-4">
<Button
variant="contained"
color="primary"
onClick={handleGenerateColliders}
>
Generate Colliders
</Button>
<Button
variant="contained"
color="secondary"
onClick={handleConvertFiles}
>
Convert Files
</Button>
<Button
variant="outlined"
color="secondary"
onClick={handleExportMap}
>
Haritayı Kaydet
</Button>
</div>
{/* Map Preview */}
{
/*
<MapPreview tiledService={tiledService} />
*/
}
<SystemMonitor ramUsage={ramUsage} />
</Paper>
</Container>
);
}
export default TiledAI;