radames commited on
Commit
c413f97
1 Parent(s): d16a2c1
Files changed (3) hide show
  1. .gitignore +1 -0
  2. createRooms.py +112 -0
  3. stablediffusion-infinity/app.py +25 -22
.gitignore CHANGED
@@ -17,3 +17,4 @@ flagged/
17
  data
18
  data.db
19
  data.json
 
 
17
  data
18
  data.db
19
  data.json
20
+ rooms.db
createRooms.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from fastapi import Depends, FastAPI
3
+ import sqlite3
4
+ import requests
5
+ import uvicorn
6
+ from pathlib import Path
7
+ import json
8
+
9
+ app = FastAPI()
10
+ LIVEBLOCKS_SECRET = os.environ.get("LIVEBLOCKS_SECRET")
11
+
12
+
13
+ def get_db():
14
+ db = sqlite3.connect(Path("./rooms.db"), check_same_thread=False)
15
+ db.execute("CREATE TABLE IF NOT EXISTS rooms (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, room_id TEXT NOT NULL, users_count INTEGER NOT NULL DEFAULT 0)")
16
+ print("Connected to database")
17
+ db.commit()
18
+ db.row_factory = sqlite3.Row
19
+ try:
20
+ yield db
21
+ except Exception:
22
+ db.rollback()
23
+ finally:
24
+ db.close()
25
+
26
+
27
+ app = FastAPI()
28
+
29
+ rooms = ["sd-multiplayer-room-" + str(i) for i in range(0, 20)]
30
+
31
+
32
+ @app.get("/")
33
+ async def read_root(db: sqlite3.Connection = Depends(get_db)):
34
+ out = db.execute("SELECT * FROM rooms").fetchall()
35
+ print(out)
36
+ return out
37
+
38
+
39
+ @app.get("/create-rooms")
40
+ async def create_room(db: sqlite3.Connection = Depends(get_db)):
41
+ for room_id in rooms:
42
+ print(room_id)
43
+ createRoom(room_id, db)
44
+ all = db.execute("SELECT * FROM rooms").fetchall()
45
+ return all
46
+
47
+
48
+ def createRoom(room_id, db):
49
+ payload = {"id": room_id, "defaultAccesses": ["room:write"]}
50
+
51
+ response = requests.post(f"https://api.liveblocks.io/v2/rooms",
52
+ headers={"Authorization": f"Bearer {LIVEBLOCKS_SECRET}"}, json=payload)
53
+ # if response.status_code == 200:
54
+ data = response.json()
55
+ print(data)
56
+ if "error" in data and data["error"] == "ROOM_ALREADY_EXISTS":
57
+ print("Room already exists")
58
+
59
+ cursor = db.cursor()
60
+ cursor.execute("INSERT INTO rooms (room_id) VALUES (?)", (room_id,))
61
+ db.commit()
62
+ print("Room created")
63
+
64
+ print("Created room", room_id)
65
+ return True
66
+
67
+
68
+ def generateAuthToken():
69
+ response = requests.get(f"https://liveblocks.io/api/authorize",
70
+ headers={"Authorization": f"Bearer {LIVEBLOCKS_SECRET}"})
71
+ if response.status_code == 200:
72
+ data = response.json()
73
+ return data["token"]
74
+ else:
75
+ raise Exception(response.status_code, response.text)
76
+
77
+
78
+ def get_room_count(room_id: str, jwtToken: str = ''):
79
+ print("Getting room count" + room_id)
80
+ response = requests.get(
81
+ f"https://liveblocks.net/api/v1/room/{room_id}/users", headers={"Authorization": f"Bearer {jwtToken}", "Content-Type": "application/json"})
82
+ if response.status_code == 200:
83
+ res = response.json()
84
+ if "data" in res:
85
+ return len(res["data"])
86
+ else:
87
+ return 0
88
+ raise Exception("Error getting room count")
89
+
90
+
91
+ @app.get("/sync-rooms")
92
+ async def sync_rooms(db: sqlite3.Connection = Depends(get_db)):
93
+ try:
94
+ jwtToken = generateAuthToken()
95
+ rooms = db.execute("SELECT * FROM rooms").fetchall()
96
+ for row in rooms:
97
+ room_id = row["room_id"]
98
+ users_count = get_room_count(room_id, jwtToken)
99
+ print("Updating room", room_id, "with", users_count, "users")
100
+ cursor = db.cursor()
101
+ cursor.execute(
102
+ "UPDATE rooms SET users_count = ? WHERE room_id = ?", (users_count, room_id))
103
+ db.commit()
104
+ data = db.execute("SELECT * FROM rooms").fetchall()
105
+ return data
106
+ except Exception as e:
107
+ print(e)
108
+ return {"error": str(e)}
109
+
110
+
111
+ if __name__ == "__main__":
112
+ uvicorn.run("api:app", host="0.0.0.0", log_level="debug", reload=True)
stablediffusion-infinity/app.py CHANGED
@@ -1,6 +1,5 @@
1
  import io
2
  import os
3
- from random import sample
4
 
5
  from pathlib import Path
6
  import uvicorn
@@ -50,10 +49,13 @@ def get_db():
50
  db.row_factory = sqlite3.Row
51
  try:
52
  yield db
 
 
53
  finally:
54
  db.close()
55
 
56
 
 
57
  s3 = boto3.client(service_name='s3',
58
  aws_access_key_id=AWS_ACCESS_KEY_ID,
59
  aws_secret_access_key=AWS_SECRET_KEY)
@@ -248,7 +250,6 @@ def generateAuthToken():
248
 
249
 
250
  def get_room_count(room_id: str, jwtToken: str = ''):
251
- print("Getting room count" + room_id)
252
  response = requests.get(
253
  f"https://liveblocks.net/api/v1/room/{room_id}/users", headers={"Authorization": f"Bearer {jwtToken}", "Content-Type": "application/json"})
254
  if response.status_code == 200:
@@ -260,32 +261,30 @@ def get_room_count(room_id: str, jwtToken: str = ''):
260
  raise Exception("Error getting room count")
261
 
262
 
263
- app = gr.mount_gradio_app(app, blocks, "/gradio",
264
- gradio_api_url="http://0.0.0.0:7860/gradio/")
265
-
266
- app.on_event("startup")
267
-
268
-
269
- @repeat_every(seconds=10)
270
- async def sync_rooms(db: sqlite3.Connection = Depends(get_db)):
271
  try:
272
  jwtToken = generateAuthToken()
273
- rooms = db.execute("SELECT * FROM rooms").fetchall()
274
- print(rooms)
275
- for row in rooms:
276
- room_id = row["room_id"]
277
- users_count = get_room_count(room_id, jwtToken)
278
- print("Updating room", room_id, "with", users_count, "users")
279
- cursor = db.cursor()
280
- cursor.execute(
281
- "UPDATE rooms SET users_count = ? WHERE room_id = ?", (users_count, room_id))
282
- db.commit()
283
- data = db.execute("SELECT * FROM rooms").fetchall()
284
- print("Rooms updated", data)
285
  except Exception as e:
286
  print(e)
287
  print("Rooms update failed")
288
 
 
 
 
 
 
289
 
290
  @app.post('/uploadfile/')
291
  async def create_upload_file(background_tasks: BackgroundTasks, file: UploadFile):
@@ -324,6 +323,10 @@ app.add_middleware(
324
  allow_headers=["*"],
325
  )
326
 
 
 
 
 
327
  if __name__ == "__main__":
328
  uvicorn.run(app, host="0.0.0.0", port=7860,
329
  log_level="debug", reload=False)
 
1
  import io
2
  import os
 
3
 
4
  from pathlib import Path
5
  import uvicorn
 
49
  db.row_factory = sqlite3.Row
50
  try:
51
  yield db
52
+ except Exception:
53
+ db.rollback()
54
  finally:
55
  db.close()
56
 
57
 
58
+
59
  s3 = boto3.client(service_name='s3',
60
  aws_access_key_id=AWS_ACCESS_KEY_ID,
61
  aws_secret_access_key=AWS_SECRET_KEY)
 
250
 
251
 
252
  def get_room_count(room_id: str, jwtToken: str = ''):
 
253
  response = requests.get(
254
  f"https://liveblocks.net/api/v1/room/{room_id}/users", headers={"Authorization": f"Bearer {jwtToken}", "Content-Type": "application/json"})
255
  if response.status_code == 200:
 
261
  raise Exception("Error getting room count")
262
 
263
 
264
+ @app.on_event("startup")
265
+ @repeat_every(seconds=60*5)
266
+ async def sync_rooms():
267
+ print("Syncing rooms")
 
 
 
 
268
  try:
269
  jwtToken = generateAuthToken()
270
+ for db in get_db():
271
+ rooms = db.execute("SELECT * FROM rooms").fetchall()
272
+ for row in rooms:
273
+ room_id = row["room_id"]
274
+ users_count = get_room_count(room_id, jwtToken)
275
+ cursor = db.cursor()
276
+ cursor.execute(
277
+ "UPDATE rooms SET users_count = ? WHERE room_id = ?", (users_count, room_id))
278
+ db.commit()
 
 
 
279
  except Exception as e:
280
  print(e)
281
  print("Rooms update failed")
282
 
283
+ @app.get('/rooms')
284
+ async def get_rooms(db: sqlite3.Connection = Depends(get_db)):
285
+ rooms = db.execute("SELECT * FROM rooms").fetchall()
286
+ return rooms
287
+
288
 
289
  @app.post('/uploadfile/')
290
  async def create_upload_file(background_tasks: BackgroundTasks, file: UploadFile):
 
323
  allow_headers=["*"],
324
  )
325
 
326
+ app = gr.mount_gradio_app(app, blocks, "/gradio",
327
+ gradio_api_url="http://0.0.0.0:7860/gradio/")
328
+
329
+
330
  if __name__ == "__main__":
331
  uvicorn.run(app, host="0.0.0.0", port=7860,
332
  log_level="debug", reload=False)