MySafeCode commited on
Commit
113839d
·
verified ·
1 Parent(s): 823b1d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -92
app.py CHANGED
@@ -1,119 +1,106 @@
1
  #!/usr/bin/env python3
2
- # fast_noise.py - Optimized for speed
 
3
  import numpy as np
4
  import time
 
5
  from flask import Flask, Response
6
 
 
 
 
 
7
  app = Flask(__name__)
8
 
9
- WIDTH, HEIGHT = 400, 300
10
- CHUNK_SIZE = 50 # Process in chunks for better performance
 
11
 
12
  @app.route('/')
13
  def index():
14
- return '''<!DOCTYPE html>
15
- <html>
16
- <head>
17
- <title>Fast Noise</title>
18
- <style>
19
- body { margin: 0; padding: 20px; background: #111; color: white; font-family: monospace; text-align: center; }
20
- canvas { border: 3px solid #0af; background: black; display: block; margin: 20px auto; }
21
- .stats { background: #222; padding: 15px; border-radius: 8px; display: inline-block; margin: 10px; }
22
- </style>
23
- </head>
24
- <body>
25
- <h1 style="color: #0af;">⚡ FAST NOISE</h1>
26
  <canvas id="canvas" width="400" height="300"></canvas>
27
- <div class="stats">
28
- <div>FPS: <span id="fps">0</span></div>
29
- <div>Latency: <span id="latency">0</span>ms</div>
30
- </div>
31
-
32
  <script>
33
  const canvas = document.getElementById('canvas');
34
  const ctx = canvas.getContext('2d');
35
- let frameCount = 0;
36
- let lastTime = performance.now();
37
-
38
- // Pre-allocate buffers (FASTER)
39
- const imageData = new ImageData(400, 300);
40
- const rgba = imageData.data;
41
- const rgbBuffer = new ArrayBuffer(400*300*3);
42
- const rgbView = new Uint8Array(rgbBuffer);
43
 
44
  function loadFrame() {
45
- const startTime = performance.now();
46
-
47
- fetch('/fast_noise')
48
- .then(r => {
49
- const reader = r.body.getReader();
50
- return reader.read();
51
- })
52
- .then(({value, done}) => {
53
- if (value) {
54
- // Direct memory copy (FASTEST)
55
- rgbView.set(new Uint8Array(value));
56
-
57
- // Convert RGB to RGBA
58
- for (let i = 0, j = 0; i < rgba.length; i += 4, j += 3) {
59
- rgba[i] = rgbView[j];
60
- rgba[i + 1] = rgbView[j + 1];
61
- rgba[i + 2] = rgbView[j + 2];
62
- rgba[i + 3] = 255;
63
- }
64
-
65
- ctx.putImageData(imageData, 0, 0);
66
-
67
- // Update stats
68
- frameCount++;
69
- const now = performance.now();
70
- if (now - lastTime >= 1000) {
71
- document.getElementById('fps').textContent = frameCount;
72
- frameCount = 0;
73
- lastTime = now;
74
- }
75
-
76
- const latency = now - startTime;
77
- document.getElementById('latency').textContent = Math.round(latency);
78
  }
 
 
79
  });
80
  }
81
 
82
- // Start at 10 FPS (more realistic for network)
83
  setInterval(loadFrame, 100);
84
- loadFrame();
85
  </script>
86
- </body>
87
- </html>'''
 
 
 
 
 
 
 
 
 
88
 
89
- @app.route('/fast_noise')
90
- def fast_noise():
91
- """Optimized noise generation"""
92
- # Pre-allocate array (FASTER than creating new each time)
93
- noise = np.empty((HEIGHT, WIDTH, 3), dtype=np.uint8)
94
 
95
- # Fill with random values (vectorized - FAST)
96
- np.random.randint(0, 256, (HEIGHT, WIDTH, 3), dtype=np.uint8, out=noise)
 
 
 
 
 
97
 
98
- # Add occasional vertical/horizontal lines for TV effect
99
- if np.random.random() < 0.1:
100
- if np.random.random() < 0.5:
101
- # Vertical line
102
- x = np.random.randint(0, WIDTH)
103
- width = np.random.randint(1, 5)
104
- noise[:, x:x+width, :] = 255
105
- else:
106
- # Horizontal line
107
- y = np.random.randint(0, HEIGHT)
108
- height = np.random.randint(1, 5)
109
- noise[y:y+height, :, :] = 255
110
 
111
- return Response(
112
- noise.tobytes(),
113
- mimetype='application/octet-stream',
114
- headers={'Cache-Control': 'no-cache'}
115
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
- if __name__ == "__main__":
118
- print(" Fast noise server starting...")
119
- app.run(host='0.0.0.0', port=7860, threaded=True)
 
1
  #!/usr/bin/env python3
2
+ # pygame_to_flask.py - PyGame renders, Flask serves
3
+ import pygame
4
  import numpy as np
5
  import time
6
+ import threading
7
  from flask import Flask, Response
8
 
9
+ # Setup
10
+ os.environ['SDL_VIDEODRIVER'] = 'dummy'
11
+ WIDTH, HEIGHT = 400, 300
12
+
13
  app = Flask(__name__)
14
 
15
+ # Simple shared state
16
+ current_frame = None
17
+ frame_lock = threading.Lock()
18
 
19
  @app.route('/')
20
  def index():
21
+ return '''<html><body>
 
 
 
 
 
 
 
 
 
 
 
22
  <canvas id="canvas" width="400" height="300"></canvas>
 
 
 
 
 
23
  <script>
24
  const canvas = document.getElementById('canvas');
25
  const ctx = canvas.getContext('2d');
 
 
 
 
 
 
 
 
26
 
27
  function loadFrame() {
28
+ fetch('/pygame_frame')
29
+ .then(r => r.arrayBuffer())
30
+ .then(buffer => {
31
+ const imageData = new ImageData(400, 300);
32
+ const rgba = imageData.data;
33
+ const rgb = new Uint8Array(buffer);
34
+
35
+ for (let i = 0, j = 0; i < rgba.length; i += 4, j += 3) {
36
+ rgba[i] = rgb[j];
37
+ rgba[i + 1] = rgb[j + 1];
38
+ rgba[i + 2] = rgb[j + 2];
39
+ rgba[i + 3] = 255;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  }
41
+
42
+ ctx.putImageData(imageData, 0, 0);
43
  });
44
  }
45
 
 
46
  setInterval(loadFrame, 100);
 
47
  </script>
48
+ </body></html>'''
49
+
50
+ @app.route('/pygame_frame')
51
+ def pygame_frame():
52
+ with frame_lock:
53
+ if current_frame:
54
+ return Response(current_frame, mimetype='application/octet-stream')
55
+
56
+ # Fallback: black frame
57
+ black = np.zeros((HEIGHT, WIDTH, 3), dtype=np.uint8).tobytes()
58
+ return Response(black, mimetype='application/octet-stream')
59
 
60
+ def pygame_render():
61
+ """PyGame rendering thread"""
62
+ print("🎬 Starting PyGame...")
 
 
63
 
64
+ try:
65
+ pygame.init()
66
+ surface = pygame.Surface((WIDTH, HEIGHT))
67
+ print("✅ PyGame initialized")
68
+ except Exception as e:
69
+ print(f"❌ PyGame failed: {e}")
70
+ return
71
 
72
+ # Simple animation
73
+ x, y = 200, 150
74
+ dx, dy = 3, 2
 
 
 
 
 
 
 
 
 
75
 
76
+ while True:
77
+ # Clear
78
+ surface.fill((20, 20, 40))
79
+
80
+ # Update
81
+ x += dx
82
+ y += dy
83
+
84
+ if x < 20 or x > 380:
85
+ dx = -dx
86
+ if y < 20 or y > 280:
87
+ dy = -dy
88
+
89
+ # Draw
90
+ pygame.draw.circle(surface, (255, 100, 100), (int(x), int(y)), 20)
91
+
92
+ # Convert to bytes
93
+ pixels = pygame.surfarray.pixels3d(surface)
94
+
95
+ with frame_lock:
96
+ global current_frame
97
+ current_frame = pixels.tobytes()
98
+
99
+ time.sleep(1/30)
100
+
101
+ # Start PyGame thread
102
+ threading.Thread(target=pygame_render, daemon=True).start()
103
 
104
+ # Start Flask
105
+ print("🌐 Starting Flask...")
106
+ app.run(host='0.0.0.0', port=7860, threaded=True)