diff --git a/README.md b/README.md index 1795f2e..482bc7f 100644 --- a/README.md +++ b/README.md @@ -433,4 +433,86 @@ export default TrainPage; 1. [stackoverflow.com - How to execute a function every 1 minute](https://stackoverflow.com/questions/75767160/how-to-execute-a-function-every-1-minute) 2. [advsyscon.com - Python Job Scheduling with Cron](https://www.advsyscon.com/blog/python-job-scheduling/) 3. [discuss.python.org - Help me to initialize or trigger a python file to run every 2 hours](https://discuss.python.org/t/help-me-to-initialize-or-trigger-a-python-file-to-run-in-every-2-hrs/51347) - \ No newline at end of file + + +To set up your Next.js project to run a Python script, save the results locally, and display them on the front end, follow these steps: + +### 1. **Run the Python Script in Next.js:** + - Use Node.js’s `child_process` module to execute the Python script from within an API route in your Next.js project. + - Example code (TypeScript): + + ```typescript + import { exec } from 'child_process'; + import type { NextApiRequest, NextApiResponse } from 'next'; + + export default function handler(req: NextApiRequest, res: NextApiResponse) { + exec('python3 ./../../scripts/train.py', (error, stdout, stderr) => { + if (error) { + res.status(500).json({ error: stderr }); + } else { + // Save stdout to a file or return the output directly + res.status(200).json({ message: 'Script executed successfully', output: stdout }); + } + }); + } + ``` + +### 2. **Save Results Locally:** + - You can save the output of the Python script to a file using Node.js’s `fs` module. + - Example: + + ```typescript + import { exec } from 'child_process'; + import fs from 'fs'; + import type { NextApiRequest, NextApiResponse } from 'next'; + + export default function handler(req: NextApiRequest, res: NextApiResponse) { + exec('python3 ./../../scripts/train.py', (error, stdout, stderr) => { + if (error) { + res.status(500).json({ error: stderr }); + } else { + // Save the output to a file + fs.writeFileSync('./results/output.txt', stdout); + res.status(200).json({ message: 'Script executed and result saved successfully' }); + } + }); + } + ``` + +### 3. **Display the Results on the Front End:** + - Create a React component to fetch and display the saved results. + + ```typescript + import { useEffect, useState } from 'react'; + + function DataDisplay() { + const [textResult, setTextResult] = useState(''); + + useEffect(() => { + fetch('/api/get-results') // This API route should return the saved results + .then((res) => res.text()) + .then((data) => setTextResult(data)); + }, []); + + return ( +
{textResult}
+{textResult}
{imageSrc && }