Factor Studios commited on
Commit
ba864c5
·
verified ·
1 Parent(s): 68afb37

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +114 -87
server.py CHANGED
@@ -7,10 +7,13 @@ import uuid
7
  import time
8
  from typing import Dict, Any, Optional
9
  import numpy as np
10
- from aiohttp import web
11
- import aiohttp
12
  from datetime import datetime
13
 
 
 
 
14
  class VirtualGPUServer:
15
  def __init__(self):
16
  self.base_path = Path(__file__).parent / "storage"
@@ -29,17 +32,12 @@ class VirtualGPUServer:
29
  self.memory_cache: Dict[str, Any] = {}
30
 
31
  # Active connections and sessions
32
- self.active_connections: Dict[str, websockets.WebSocketServerProtocol] = {}
33
  self.active_sessions: Dict[str, Dict[str, Any]] = {}
34
 
35
  # Performance monitoring
36
  self.ops_counter = 0
37
  self.start_time = time.time()
38
-
39
- # HTTP app
40
- self.app = web.Application()
41
- self.app.router.add_get('/', self.handle_index)
42
- self.app.router.add_get('/files', self.handle_files)
43
 
44
  async def handle_vram_operation(self, operation: dict) -> dict:
45
  """Handle VRAM read/write operations"""
@@ -216,92 +214,121 @@ class VirtualGPUServer:
216
  'memory_cache_size': len(self.memory_cache)
217
  }
218
 
219
- async def handle_index(self, request):
220
- """Handle HTTP index request"""
221
- stats = self.get_stats()
222
- html = f"""
223
- <!DOCTYPE html>
224
- <html>
225
- <head>
226
- <title>Virtual GPU Server</title>
227
- <style>
228
- body {{ font-family: Arial, sans-serif; margin: 40px; }}
229
- table {{ border-collapse: collapse; width: 100%; margin-top: 20px; }}
230
- th, td {{ padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }}
231
- th {{ background-color: #f2f2f2; }}
232
- .stats {{ background-color: #f9f9f9; padding: 20px; border-radius: 5px; }}
233
- </style>
234
- </head>
235
- <body>
236
- <h1>Virtual GPU Server Status</h1>
237
- <div class="stats">
238
- <h2>Server Statistics</h2>
239
- <ul>
240
- <li>Uptime: {stats['uptime']:.2f} seconds</li>
241
- <li>Total Operations: {stats['total_operations']}</li>
242
- <li>Operations per Second: {stats['ops_per_second']:.2f}</li>
243
- <li>Active Connections: {stats['active_connections']}</li>
244
- <li>VRAM Cache Size: {stats['vram_cache_size']}</li>
245
- <li>State Cache Size: {stats['state_cache_size']}</li>
246
- <li>Memory Cache Size: {stats['memory_cache_size']}</li>
247
- </ul>
248
- </div>
249
- <h2>Server Files</h2>
250
- <iframe src="/files" style="width: 100%; height: 500px; border: none;"></iframe>
251
- </body>
252
- </html>
253
- """
254
- return web.Response(text=html, content_type='text/html')
255
 
256
- async def handle_files(self, request):
257
- """Handle HTTP files listing request"""
258
- def format_size(size):
259
- for unit in ['B', 'KB', 'MB', 'GB']:
260
- if size < 1024:
261
- return f"{size:.2f} {unit}"
262
- size /= 1024
263
- return f"{size:.2f} TB"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264
 
265
- html = ['<!DOCTYPE html><html><head>',
266
- '<style>',
267
- 'body { font-family: Arial, sans-serif; margin: 20px; }',
268
- 'table { border-collapse: collapse; width: 100%; }',
269
- 'th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }',
270
- 'th { background-color: #f2f2f2; }',
271
- '</style></head><body>',
272
- '<h2>Server Files</h2>',
273
- '<table><tr><th>Path</th><th>Size</th><th>Last Modified</th></tr>']
274
 
275
- for root, _, files in os.walk(self.base_path):
276
- for file in files:
277
- full_path = Path(root) / file
278
- rel_path = full_path.relative_to(self.base_path)
279
- size = format_size(os.path.getsize(full_path))
280
- mtime = datetime.fromtimestamp(os.path.getmtime(full_path))
281
- html.append(f'<tr><td>{rel_path}</td><td>{size}</td><td>{mtime}</td></tr>')
 
 
282
 
283
- html.extend(['</table></body></html>'])
284
- return web.Response(text='\n'.join(html), content_type='text/html')
 
 
 
 
 
285
 
286
- # Create the application instance
287
- server = VirtualGPUServer()
288
- app = server.app
289
 
290
- # WebSocket setup
291
- @app.on_startup.append
292
- async def start_websocket_server(app):
293
- app['websocket_server'] = await websockets.serve(
294
- server.handle_connection,
295
- "0.0.0.0", # Listen on all interfaces
296
- 8765
297
- )
298
- print("WebSocket server started on ws://0.0.0.0:8765")
 
299
 
300
- @app.on_cleanup.append
301
- async def cleanup_websocket_server(app):
302
- app['websocket_server'].close()
303
- await app['websocket_server'].wait_closed()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
 
305
  # For running directly (development)
306
  if __name__ == "__main__":
307
- web.run_app(app, host="0.0.0.0", port=7860)
 
 
7
  import time
8
  from typing import Dict, Any, Optional
9
  import numpy as np
10
+ from fastapi import FastAPI, WebSocket
11
+ from fastapi.responses import HTMLResponse
12
  from datetime import datetime
13
 
14
+ # Create FastAPI instance
15
+ app = FastAPI()
16
+
17
  class VirtualGPUServer:
18
  def __init__(self):
19
  self.base_path = Path(__file__).parent / "storage"
 
32
  self.memory_cache: Dict[str, Any] = {}
33
 
34
  # Active connections and sessions
35
+ self.active_connections: Dict[str, WebSocket] = {}
36
  self.active_sessions: Dict[str, Dict[str, Any]] = {}
37
 
38
  # Performance monitoring
39
  self.ops_counter = 0
40
  self.start_time = time.time()
 
 
 
 
 
41
 
42
  async def handle_vram_operation(self, operation: dict) -> dict:
43
  """Handle VRAM read/write operations"""
 
214
  'memory_cache_size': len(self.memory_cache)
215
  }
216
 
217
+ server = VirtualGPUServer()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
 
219
+ @app.get("/", response_class=HTMLResponse)
220
+ async def handle_index():
221
+ """Handle HTTP index request"""
222
+ stats = server.get_stats()
223
+ html = f"""
224
+ <!DOCTYPE html>
225
+ <html>
226
+ <head>
227
+ <title>Virtual GPU Server</title>
228
+ <style>
229
+ body {{ font-family: Arial, sans-serif; margin: 40px; }}
230
+ table {{ border-collapse: collapse; width: 100%; margin-top: 20px; }}
231
+ th, td {{ padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }}
232
+ th {{ background-color: #f2f2f2; }}
233
+ .stats {{ background-color: #f9f9f9; padding: 20px; border-radius: 5px; }}
234
+ </style>
235
+ </head>
236
+ <body>
237
+ <h1>Virtual GPU Server Status</h1>
238
+ <div class="stats">
239
+ <h2>Server Statistics</h2>
240
+ <ul>
241
+ <li>Uptime: {stats['uptime']:.2f} seconds</li>
242
+ <li>Total Operations: {stats['total_operations']}</li>
243
+ <li>Operations per Second: {stats['ops_per_second']:.2f}</li>
244
+ <li>Active Connections: {stats['active_connections']}</li>
245
+ <li>VRAM Cache Size: {stats['vram_cache_size']}</li>
246
+ <li>State Cache Size: {stats['state_cache_size']}</li>
247
+ <li>Memory Cache Size: {stats['memory_cache_size']}</li>
248
+ </ul>
249
+ </div>
250
+ <h2>Server Files</h2>
251
+ <iframe src="/files" style="width: 100%; height: 500px; border: none;"></iframe>
252
+ </body>
253
+ </html>
254
+ """
255
+ return HTMLResponse(content=html)
256
 
257
+ @app.get("/files", response_class=HTMLResponse)
258
+ async def handle_files():
259
+ """Handle HTTP files listing request"""
260
+ def format_size(size):
261
+ for unit in ['B', 'KB', 'MB', 'GB']:
262
+ if size < 1024:
263
+ return f"{size:.2f} {unit}"
264
+ size /= 1024
265
+ return f"{size:.2f} TB"
266
 
267
+ html = ['<!DOCTYPE html><html><head>',
268
+ '<style>',
269
+ 'body { font-family: Arial, sans-serif; margin: 20px; }',
270
+ 'table { border-collapse: collapse; width: 100%; }',
271
+ 'th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }',
272
+ 'th { background-color: #f2f2f2; }',
273
+ '</style></head><body>',
274
+ '<h2>Server Files</h2>',
275
+ '<table><tr><th>Path</th><th>Size</th><th>Last Modified</th></tr>']
276
 
277
+ for root, _, files in os.walk(server.base_path):
278
+ for file in files:
279
+ full_path = Path(root) / file
280
+ rel_path = full_path.relative_to(server.base_path)
281
+ size = format_size(os.path.getsize(full_path))
282
+ mtime = datetime.fromtimestamp(os.path.getmtime(full_path))
283
+ html.append(f'<tr><td>{rel_path}</td><td>{size}</td><td>{mtime}</td></tr>')
284
 
285
+ html.extend(['</table></body></html>'])
286
+ return HTMLResponse(content='\n'.join(html))
 
287
 
288
+ # WebSocket endpoint
289
+ @app.websocket("/ws")
290
+ async def websocket_endpoint(websocket: WebSocket):
291
+ await websocket.accept()
292
+ session_id = str(uuid.uuid4())
293
+ server.active_connections[session_id] = websocket
294
+ server.active_sessions[session_id] = {
295
+ 'start_time': time.time(),
296
+ 'ops_count': 0
297
+ }
298
 
299
+ try:
300
+ while True:
301
+ message = await websocket.receive_json()
302
+
303
+ # Route operation to appropriate handler
304
+ operation_type = message.get('operation')
305
+ if operation_type == 'vram':
306
+ response = await server.handle_vram_operation(message)
307
+ elif operation_type == 'state':
308
+ response = await server.handle_state_operation(message)
309
+ elif operation_type == 'cache':
310
+ response = await server.handle_cache_operation(message)
311
+ else:
312
+ response = {
313
+ 'status': 'error',
314
+ 'message': 'Unknown operation type'
315
+ }
316
+
317
+ # Update statistics
318
+ server.ops_counter += 1
319
+ server.active_sessions[session_id]['ops_count'] += 1
320
+
321
+ # Send response
322
+ await websocket.send_json(response)
323
+
324
+ except Exception as e:
325
+ print(f"WebSocket error: {e}")
326
+ finally:
327
+ # Cleanup on disconnect
328
+ del server.active_connections[session_id]
329
+ del server.active_sessions[session_id]
330
 
331
  # For running directly (development)
332
  if __name__ == "__main__":
333
+ import uvicorn
334
+ uvicorn.run("server:app", host="0.0.0.0", port=7860, reload=True)