Advertisement
here2share

# tk_localhost_png.py

Dec 27th, 2022
961
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.76 KB | None | 0 0
  1. # tk_localhost_png.py ZZZ
  2.  
  3. import json
  4. import tempfile
  5. import urllib.request
  6. import subprocess
  7. import requests
  8.  
  9. from tkinter import *
  10.  
  11. ww = 1400
  12. hh = 600
  13.  
  14. # Create the root and canvas
  15. root = Tk()
  16. canvas = Canvas(root, width=ww, height=hh)
  17. canvas.pack()
  18.  
  19. # any formula will get converted into being javascript
  20. formula = {
  21.     "ww": ww,
  22.     "hh": hh,
  23.     "Du": 0.16,
  24.     "Dv": 0.08,
  25.     "f": 0.035,
  26.     "k": 0.065,
  27.     "dt": 0.1,
  28.     "u": {},
  29.     "v": {},
  30. }
  31.  
  32. for i in range(ww):
  33.     for j in range(hh):
  34.         formula["u"][i, j] = 1 + 0.1 * (0.5 - random.random())
  35.         formula["v"][i, j] = 0.1 * (0.5 - random.random())
  36.  
  37. # Encode the formula as a JSON string
  38. formula_json = json.dumps(formula).encode("utf-8")
  39.  
  40. # for the convertToJS function to process the 600x1400 image
  41. # this example is to render a Gray-Scott grayscale animation
  42. PyToJS = """
  43. rgb = []
  44. p = 255 / 0.099
  45. while 1:
  46.     for j in range(1, hh-1):
  47.         for i in range(1, ww-1):
  48.             u[i,j] = u[i,j] + dt * (Du * (u[i+1,j] + u[i-1,j] + u[i,j+1] + u[i,j-1] - 4*u[i,j]) - u[i,j]*v[i,j]**2 + f*(1-u[i,j]))
  49.             v[i,j] = v[i,j] + dt * (Dv * (v[i+1,j] + v[i-1,j] + v[i,j+1] + v[i,j-1] - 4*v[i,j]) + u[i,j]*v[i,j]**2 - (f+k)*v[i,j])
  50.             color = int(p * min(1, max(0, v[i,j])))
  51.             rgb.append((color, color, color))
  52. """
  53.  
  54. zoom = 1
  55. def zoom_fn(event):
  56.     global zoom
  57.     if event.keysym == "Up":
  58.         zoom /= 1.01
  59.     elif event.keysym == "Down":
  60.         zoom *= 1.01
  61.  
  62. imagePosX = 0
  63. imagePosY = 0
  64. def on_mouse_move(event):
  65.     global imagePosX
  66.     global imagePosY
  67.     imagePosX += event.x
  68.     imagePosY += event.y
  69.  
  70. root.bind("<B1-Motion>", on_mouse_move)
  71. root.bind("<Up>", zoom_fn)
  72. root.bind("<Down>", zoom_fn)
  73.  
  74. # Send the formula to the JavaScript server using a POST request
  75. req = urllib.request.Request("http://localhost:8000/generate_image")
  76. req.add_header("Content-Type", "application/json")
  77. response = urllib.request.urlopen(req, formula_json)
  78.  
  79. # Read the image data from the response
  80. image_data = response.read()
  81.  
  82. # Save the image data to a temporary file
  83. with tempfile.NamedTemporaryFile(suffix=".png") as f:
  84.     f.write(image_data)
  85.     f.flush()
  86.     # Use Tkinter's "create_image" method to display the image on the canvas
  87.     canvas.create_image(0, 0, anchor=NW, image=f.name)
  88.  
  89. # create javascript localhost that will convert python code into javascript code
  90. js_localhost = """
  91. function convertToJS(pythonCode) {
  92.  // Replace all instances of "as" with "="
  93.  pythonCode = pythonCode.replace(/as ([^\s]+)/g, (match, variable) => {
  94.    return `= ${variable}`;
  95.  });
  96.  
  97.  // Replace all instances of "range" with "for" loop syntax
  98.  pythonCode = pythonCode.replace(/range\(([^)]+)\)/g, (match, args) => {
  99.    return `for (let i = 0; i < ${args}; i++)`;
  100.  });
  101.  
  102.  // Replace all instances of "True" with "true"
  103.  pythonCode = pythonCode.replace(/True/g, "true");
  104.  
  105.  // Replace all instances of "False" with "false"
  106.  pythonCode = pythonCode.replace(/False/g, "false");
  107.  
  108.  // Replace all instances of "None" with "null"
  109.  pythonCode = pythonCode.replace(/None/g, "null");
  110.  
  111.  // Replace all instances of "print" with "console.log"
  112.  pythonCode = pythonCode.replace(/print\(([^)]+)\)/g, (match, args) => {
  113.    return `console.log(${args})`;
  114.  });
  115.  
  116.  // Replace all instances of ":" with "{"
  117.  pythonCode = pythonCode.replace(/:/g, "{");
  118.  
  119.  // Replace all instances of "indent" with a tab character
  120.  pythonCode = pythonCode.replace(/indent/g, "\t");
  121.  
  122.  // Replace all instances of "and" with "&&"
  123.  pythonCode = pythonCode.replace(/ and /g, " && ");
  124.  
  125.  // Replace all instances of "or" with "||"
  126.  pythonCode = pythonCode.replace(/ or /g, " || ");
  127.  
  128.  // Replace all instances of "not" with "!"
  129.  pythonCode = pythonCode.replace(/not /g, "!");
  130.  
  131.  // Return the converted code
  132.  return pythonCode;
  133. }
  134.  
  135. const http = require('http');
  136.  
  137. const hostname = 'localhost';
  138. const port = 8000;
  139.  
  140. const fs = require('fs');
  141. const pngjs = require('pngjs');
  142.  
  143. app.post('/convert_to_png', (req, res) => {
  144.  const rgb = req.body;
  145.  const width = 1400;
  146.  const height = 600;
  147.  
  148.  // Create a new PNG image with the specified width and height
  149.  const png = new pngjs.PNG({ width, height });
  150.  
  151.  // Set the pixel data of the PNG image from the rgb array
  152.  for (let i = 0; i < rgb.length; i++) {
  153.    const pixel = rgb[i];
  154.    png.data[i * 4] = pixel[0];
  155.    png.data[i * 4 + 1] = pixel[1];
  156.    png.data[i * 4 + 2] = pixel[2];
  157.    png.data[i * 4 + 3] = 255;
  158.  }
  159.  
  160.  // Write the PNG image to a file
  161.  png.pack().pipe(fs.createWriteStream('image.png'));
  162.  
  163.  // Alternatively, you can send the PNG image back to the Python script as a response
  164.  // png.pack().pipe(res);
  165. });
  166.  
  167. const server = http.createServer((req, res) => {
  168.  if (req.url === '/generate_image' && req.method === 'POST') {
  169.    let body = '';
  170.    req.on('data', chunk => {
  171.      body += chunk.toString(); // convert Buffer to string
  172.    });
  173.    req.on('end', () => {
  174.      const formula = JSON.parse(body);
  175.      // Convert the formula from Python to JavaScript and generate the image
  176.      // Save the image data to a temporary file
  177.      const imageData = generateImage(formula);
  178.      res.writeHead(200, {'Content-Type': 'image/png'});
  179.      res.end(imageData, 'binary');
  180.    });
  181.  } else {
  182.    res.statusCode = 404;
  183.    res.end();
  184.  }
  185. });
  186.  
  187. server.listen(port, hostname, () => {
  188.  console.log(`Server running at http://${hostname}:${port}/`);
  189. });
  190. """
  191.  
  192. # Create a temporary file
  193. with tempfile.NamedTemporaryFile(suffix=".js", delete=False) as f:
  194.     # Write the js_localhost code to the file
  195.     f.write(js_localhost.encode("utf-8"))
  196.     # Store the file name for later use
  197.     js_file = f.name
  198.  
  199. rgb_json = json.dumps(rgb).encode("utf-8")
  200. response = requests.post("http://localhost:8000/convert_to_png", json=rgb_json)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement