-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_memory_efficient.py
More file actions
232 lines (194 loc) · 8.6 KB
/
Copy pathmain_memory_efficient.py
File metadata and controls
232 lines (194 loc) · 8.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#!/usr/bin/env python3
"""
Memory-Efficient TimeCapsuleTV - Main Application
Loads only the current decade to reduce memory usage
"""
import time
import os
import signal
import threading
from http.server import HTTPServer, SimpleHTTPRequestHandler
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from src.data.loader import lazy_loader
from src.core.generator import HTMLGenerator
from src.core.server import TVServer
class MemoryEfficientVideoPlayer:
"""Memory-efficient TV application controller"""
def __init__(self):
self.current_decade = '80s' # Start with 80s
self.driver = None
self.exit_server = TVServer()
self.http_server = None
self.http_port = 8888
self.running = True
# Load only current decade
print(f"🔄 Loading {self.current_decade} decade...")
self.current_decade_data = lazy_loader.load_decade_data(self.current_decade)
self.html_generator = HTMLGenerator({self.current_decade: self.current_decade_data})
# Setup signal handlers for graceful shutdown
signal.signal(signal.SIGTERM, self._signal_handler)
signal.signal(signal.SIGINT, self._signal_handler)
def switch_decade(self, decade):
"""Switch to a different decade (memory efficient)"""
if decade == self.current_decade:
return
print(f"🔄 Switching to {decade} decade...")
self.current_decade = decade
# Load new decade data
self.current_decade_data = lazy_loader.load_decade_data(decade)
self.html_generator = HTMLGenerator({decade: self.current_decade_data})
# Regenerate HTML with new data
self.create_html_file()
# Reload the page
if self.driver:
self.driver.refresh()
print(f"✅ Switched to {decade} decade ({len(self.current_decade_data)} videos)")
def setup_driver(self):
"""Configure Chrome driver for kiosk mode"""
chrome_options = Options()
chrome_options.add_argument("--kiosk")
chrome_options.add_argument("--disable-web-security")
chrome_options.add_argument("--allow-running-insecure-content")
chrome_options.add_argument("--autoplay-policy=no-user-gesture-required")
chrome_options.add_argument("--disable-features=VizDisplayCompositor")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-plugins")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
# Setup Chrome driver
service = Service(ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=service, options=chrome_options)
# Set up window close handler
self.driver.execute_script("""
window.addEventListener('beforeunload', function() {
// Send exit command to Python backend
fetch('http://localhost:8080/exit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({command: 'exit'})
}).catch(() => {
// Ignore errors on window close
});
});
""")
def create_html_file(self):
"""Generate and save the HTML file"""
html_content = self.html_generator.generate_html()
with open('temp_tv.html', 'w', encoding='utf-8') as f:
f.write(html_content)
def start_http_server(self):
"""Start HTTP server to serve the HTML file"""
class CustomHandler(SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=os.getcwd(), **kwargs)
def log_message(self, format, *args):
# Suppress HTTP server logs
pass
try:
self.http_server = HTTPServer(('localhost', self.http_port), CustomHandler)
# Start server in background thread
server_thread = threading.Thread(target=self.http_server.serve_forever, daemon=True)
server_thread.start()
print(f"✅ HTTP server started on http://localhost:{self.http_port}")
except OSError as e:
print(f"Warning: Could not start TV server: {e}")
print(f"Error: {e}")
import traceback
print("Full traceback:")
traceback.print_exc()
def start(self):
"""Start the TV application"""
try:
# Setup components
self.setup_driver()
self.exit_server.start()
self.create_html_file()
self.start_http_server()
# Load via HTTP instead of file://
url = f'http://localhost:{self.http_port}/temp_tv.html'
print(f"🌐 Loading via HTTP: {url}")
self.driver.get(url)
print("Memory-Efficient TimeCapsuleTV started!")
print(f"📺 Currently loaded: {self.current_decade} decade ({len(self.current_decade_data)} videos)")
print("Controls:")
print(" ↑/↓ Arrow Keys: Cycle through categories")
print(" ←/→ Arrow Keys: Cycle through videos within current category")
print(" R: Toggle random mode (random from all videos)")
print(" S: Skip current video (useful for blocked videos)")
print(" n/N: Cycle noise mode")
print(" C: Categorize current video")
print(" H: Jump to next hidden video (sequential)")
print(" X: Add current video to favorites ❤️")
print(" F: Switch to favorites mode")
print(" 5: Switch to 50s")
print(" 6: Switch to 60s")
print(" 7: Switch to 70s")
print(" 8: Switch to 80s")
print(" 9: Switch to 90s")
print(" 0: Switch to 00s")
print(" ESC: Exit")
print(f"Categories available: {', '.join(self.html_generator.category_names)}")
# Keep the application running
while self.running:
time.sleep(1)
except KeyboardInterrupt:
print("\nShutting down...")
except Exception as e:
import traceback
print(f"Error: {e}")
print("Full traceback:")
traceback.print_exc()
finally:
self.cleanup()
def _signal_handler(self, signum, frame):
"""Handle shutdown signals"""
print(f"\n🛑 Received signal {signum}, shutting down gracefully...")
self.running = False
self.cleanup()
def cleanup(self):
"""Clean up resources"""
print("🧹 Cleaning up resources...")
# Stop the running flag
self.running = False
# Clear data cache to free memory
lazy_loader.clear_cache()
# Close browser driver
if self.driver:
try:
print("🌐 Closing browser...")
self.driver.quit()
except Exception as e:
print(f"Warning: Error closing browser: {e}")
# Stop exit server
if self.exit_server:
try:
print("🛑 Stopping exit server...")
self.exit_server.stop()
except Exception as e:
print(f"Warning: Error stopping exit server: {e}")
# Shutdown HTTP server
if self.http_server:
try:
print("🌐 Shutting down HTTP server...")
self.http_server.shutdown()
except Exception as e:
print(f"Warning: Error shutting down HTTP server: {e}")
# Clean up temporary file
try:
if os.path.exists('temp_tv.html'):
os.remove('temp_tv.html')
print("🗑️ Removed temporary HTML file")
except Exception as e:
print(f"Warning: Error removing temporary file: {e}")
print("✅ Cleanup complete")
if __name__ == "__main__":
# Show total video count without loading all data
print("🎬 TimeCapsuleTV - Memory Efficient Version")
lazy_loader.get_total_video_count()
player = MemoryEfficientVideoPlayer()
player.start()