MySafeCode commited on
Commit
3b4d4ac
·
verified ·
1 Parent(s): a6d1e63

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +177 -65
app.py CHANGED
@@ -5,73 +5,144 @@ import os
5
  from flask import Flask, Response, render_template_string
6
  from io import BytesIO
7
  from PIL import Image
 
8
 
9
  os.environ['SDL_VIDEODRIVER'] = 'dummy'
10
  pygame.init()
11
- print(" PyGame initialized")
12
 
13
  WIDTH, HEIGHT = 400, 300
 
 
14
  shared = {
15
- "frame_count": 0,
16
- "streaming": True,
17
- "last_frame_data": None # Store raw bytes instead of filename
 
18
  }
19
 
20
- def debug_loop():
21
- """Debug version that prints everything"""
22
- # Test if surfaces work at all
23
- print("🎬 Creating test surface...")
24
- screen = pygame.Surface((WIDTH, HEIGHT))
25
-
26
- # Test drawing
27
- screen.fill((255, 0, 0)) # RED
28
- pixel_color = screen.get_at((50, 50))
29
- print(f"🔴 Test draw - Pixel at (50,50): {pixel_color}")
30
-
31
- # Now test with circle
32
- x, y = 100, 100
33
- for i in range(5):
34
- screen.fill((25, 25, 45)) # Clear
35
- pygame.draw.circle(screen, (255, 80, 80), (x + i*20, y), 20)
36
-
37
- # Get pixel where circle should be
38
- pixel = screen.get_at((x + i*20, y))
39
- print(f"🔄 Frame {i}: Circle at ({x + i*20},{y}) - Pixel: {pixel}")
40
 
41
- # Convert to JPEG
42
- frame_str = pygame.image.tostring(screen, 'RGB')
43
- img = Image.frombytes('RGB', (WIDTH, HEIGHT), frame_str)
44
- buf = BytesIO()
45
- img.save(buf, format='JPEG')
46
- shared["last_frame_data"] = buf.getvalue()
47
 
48
- time.sleep(0.5)
49
-
50
- print("✅ Debug test complete")
51
- shared["streaming"] = False
52
 
53
  app = Flask(__name__)
54
 
55
  HTML = '''<html>
56
- <body style="background:#0f172a; color:white; text-align:center; padding:20px;">
57
- <h1>🔍 Debug Test</h1>
58
- <div id="status">Testing PyGame drawing...</div>
59
- <img id="streamImg" width="400" height="300" style="border:3px solid #60a5fa;">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  <script>
62
- function updateImage() {
63
- const img = document.getElementById('streamImg');
64
- if (img.src) {
65
- // Force reload
66
- img.src = img.src.split('?')[0] + '?t=' + Date.now();
67
- } else {
68
- img.src = '/frame';
69
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  }
71
 
72
- // Update every 2 seconds
73
- setInterval(updateImage, 2000);
74
- updateImage();
 
 
75
  </script>
76
  </body>
77
  </html>'''
@@ -80,27 +151,68 @@ HTML = '''<html>
80
  def index():
81
  return render_template_string(HTML)
82
 
83
- @app.route('/frame')
84
- def frame():
85
- if shared["last_frame_data"]:
86
- return Response(
87
- shared["last_frame_data"],
88
- mimetype='image/jpeg',
89
- headers={'Cache-Control': 'no-cache'}
90
- )
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- # Create a simple color test image
93
- img = Image.new('RGB', (WIDTH, HEIGHT), color=(0, 255, 0)) # GREEN
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  buf = BytesIO()
95
- img.save(buf, format='JPEG')
96
- return Response(buf.getvalue(), mimetype='image/jpeg')
 
 
 
 
 
 
 
 
 
97
 
98
  if __name__ == "__main__":
99
- print("🚀 Starting debug test...")
 
 
100
 
101
- # Run debug loop in thread
102
- thread = threading.Thread(target=debug_loop, daemon=True)
103
  thread.start()
104
 
105
  # Start server
106
- app.run(host='0.0.0.0', port=7860, debug=False, threaded=True)
 
 
 
 
 
 
5
  from flask import Flask, Response, render_template_string
6
  from io import BytesIO
7
  from PIL import Image
8
+ import random
9
 
10
  os.environ['SDL_VIDEODRIVER'] = 'dummy'
11
  pygame.init()
12
+ print("🔥 DEBUG START")
13
 
14
  WIDTH, HEIGHT = 400, 300
15
+
16
+ # SIMPLE shared state - just a counter and color
17
  shared = {
18
+ "counter": 0,
19
+ "color_index": 0,
20
+ "last_update": time.time(),
21
+ "streaming": True
22
  }
23
 
24
+ # Different colors to clearly see changes
25
+ COLORS = [
26
+ (255, 50, 50), # Red
27
+ (50, 255, 50), # Green
28
+ (50, 50, 255), # Blue
29
+ (255, 255, 50), # Yellow
30
+ (255, 50, 255), # Purple
31
+ (50, 255, 255), # Cyan
32
+ ]
33
+
34
+ def simple_loop():
35
+ """Super simple - just changes color and counter"""
36
+ while shared["streaming"]:
37
+ time.sleep(0.5) # Change every 500ms
 
 
 
 
 
 
38
 
39
+ # Update state
40
+ shared["counter"] += 1
41
+ shared["color_index"] = (shared["color_index"] + 1) % len(COLORS)
42
+ shared["last_update"] = time.time()
 
 
43
 
44
+ # Log to prove it's running
45
+ print(f"🔄 UPDATE #{shared['counter']}: Color {shared['color_index']} at {time.strftime('%H:%M:%S')}")
 
 
46
 
47
  app = Flask(__name__)
48
 
49
  HTML = '''<html>
50
+ <head>
51
+ <style>
52
+ body { background:#0f172a; color:white; text-align:center; padding:20px; font-family: monospace; }
53
+ #frame { border:3px solid white; width:400px; height:300px; margin:20px auto; }
54
+ .color-box { width:50px; height:50px; display:inline-block; margin:10px; border:2px solid white; }
55
+ .stats { background:#1e293b; padding:15px; border-radius:10px; display:inline-block; }
56
+ </style>
57
+ </head>
58
+ <body>
59
+ <h1>🧪 DEBUG TEST</h1>
60
+ <div class="stats">
61
+ <div>Counter: <span id="counter">0</span></div>
62
+ <div>Color: <span id="color">Red</span></div>
63
+ <div>Last Update: <span id="time">Never</span></div>
64
+ <div>Frame: <span id="framenum">0</span></div>
65
+ </div>
66
+
67
+ <div id="frame"></div>
68
+
69
+ <div>
70
+ <div class="color-box" style="background:rgb(255,50,50)" title="Red"></div>
71
+ <div class="color-box" style="background:rgb(50,255,50)" title="Green"></div>
72
+ <div class="color-box" style="background:rgb(50,50,255)" title="Blue"></div>
73
+ <div class="color-box" style="background:rgb(255,255,50)" title="Yellow"></div>
74
+ <div class="color-box" style="background:rgb(255,50,255)" title="Purple"></div>
75
+ <div class="color-box" style="background:rgb(50,255,255)" title="Cyan"></div>
76
+ </div>
77
+
78
+ <div style="margin-top:20px;">
79
+ <button onclick="manualRefresh()">🔄 Manual Refresh</button>
80
+ <button onclick="forceNew()">⚡ Force New Image</button>
81
+ </div>
82
 
83
  <script>
84
+ let lastCounter = 0;
85
+ let frameNum = 0;
86
+
87
+ function updateDisplay() {
88
+ frameNum++;
89
+ document.getElementById('framenum').textContent = frameNum;
90
+
91
+ fetch('/data?_=' + Date.now())
92
+ .then(r => r.json())
93
+ .then(data => {
94
+ // Update text
95
+ document.getElementById('counter').textContent = data.counter;
96
+ document.getElementById('color').textContent = ['Red','Green','Blue','Yellow','Purple','Cyan'][data.color_index];
97
+ document.getElementById('time').textContent = new Date(data.last_update * 1000).toLocaleTimeString();
98
+
99
+ // Update visual frame
100
+ const color = `rgb(${data.color[0]},${data.color[1]},${data.color[2]})`;
101
+ document.getElementById('frame').style.background = color;
102
+ document.getElementById('frame').innerHTML = `
103
+ <div style="padding-top:120px; font-size:24px;">
104
+ #${data.counter}<br>
105
+ ${data.color_name}
106
+ </div>
107
+ `;
108
+
109
+ // Log if changed
110
+ if (data.counter !== lastCounter) {
111
+ console.log(`New update: #${data.counter} (${data.color_name})`);
112
+ lastCounter = data.counter;
113
+ }
114
+ })
115
+ .catch(err => {
116
+ console.error('Fetch error:', err);
117
+ document.getElementById('time').textContent = 'ERROR';
118
+ });
119
+ }
120
+
121
+ function manualRefresh() {
122
+ console.log('Manual refresh triggered');
123
+ updateDisplay();
124
+ }
125
+
126
+ function forceNew() {
127
+ console.log('Forcing new image...');
128
+ fetch('/image?_=' + Date.now())
129
+ .then(r => r.blob())
130
+ .then(blob => {
131
+ const url = URL.createObjectURL(blob);
132
+ const img = new Image();
133
+ img.onload = () => {
134
+ document.getElementById('frame').style.background = `url(${url})`;
135
+ console.log('New image loaded');
136
+ };
137
+ img.src = url;
138
+ });
139
  }
140
 
141
+ // Update every 500ms
142
+ setInterval(updateDisplay, 500);
143
+ updateDisplay();
144
+
145
+ console.log('Debug client started');
146
  </script>
147
  </body>
148
  </html>'''
 
151
  def index():
152
  return render_template_string(HTML)
153
 
154
+ @app.route('/data')
155
+ def get_data():
156
+ """Return current state as JSON"""
157
+ color = COLORS[shared["color_index"]]
158
+ color_names = ["Red", "Green", "Blue", "Yellow", "Purple", "Cyan"]
159
+
160
+ return {
161
+ 'counter': shared["counter"],
162
+ 'color_index': shared["color_index"],
163
+ 'color': color,
164
+ 'color_name': color_names[shared["color_index"]],
165
+ 'last_update': shared["last_update"],
166
+ 'timestamp': time.time()
167
+ }
168
+
169
+ @app.route('/image')
170
+ def get_image():
171
+ """Generate a unique image with counter and color"""
172
+ color = COLORS[shared["color_index"]]
173
 
174
+ # Create image with counter
175
+ img = Image.new('RGB', (WIDTH, HEIGHT), color=color)
176
+
177
+ # Add counter text (simple version)
178
+ from PIL import ImageDraw, ImageFont
179
+ draw = ImageDraw.Draw(img)
180
+
181
+ # Draw counter in center
182
+ text = f"#{shared['counter']}"
183
+ # Simple text drawing
184
+ for i in range(len(text)):
185
+ x = 180 + i * 20
186
+ y = 140
187
+ draw.rectangle([x, y, x+15, y+20], fill=(255, 255, 255))
188
+
189
+ # Convert to bytes
190
  buf = BytesIO()
191
+ img.save(buf, format='PNG') # PNG for transparency
192
+
193
+ return Response(
194
+ buf.getvalue(),
195
+ mimetype='image/png',
196
+ headers={
197
+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
198
+ 'Pragma': 'no-cache',
199
+ 'Expires': '0'
200
+ }
201
+ )
202
 
203
  if __name__ == "__main__":
204
+ print("🚀 Starting debug server...")
205
+ print("Expecting updates every 0.5 seconds")
206
+ print("Check browser console for logs")
207
 
208
+ # Start background thread
209
+ thread = threading.Thread(target=simple_loop, daemon=True)
210
  thread.start()
211
 
212
  # Start server
213
+ app.run(
214
+ host='0.0.0.0',
215
+ port=int(os.environ.get('PORT', 7860)),
216
+ debug=False,
217
+ threaded=True
218
+ )