Skip to content

Commit a6a7d07

Browse files
committed
rm pointless asyncs
1 parent 2cf5b2b commit a6a7d07

File tree

10 files changed

+69
-81
lines changed

10 files changed

+69
-81
lines changed

00_game_of_life/readme.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def Grid():
6464
return Div(*cells, id='grid')
6565

6666
@rt('/update')
67-
async def put(x: int, y: int):
67+
def put(x: int, y: int):
6868
game_state['grid'][y][x] = 1 if game_state['grid'][y][x] == 0 else 0
6969
await update_players()
7070
```
@@ -77,7 +77,7 @@ FastHTML handles WebSocket connections with ease:
7777

7878
```python
7979
@app.ws('/gol', conn=on_connect, disconn=on_disconnect)
80-
async def ws(msg:str, send): pass
80+
def ws(msg:str, send): pass
8181

8282
player_queue = []
8383
async def on_connect(send): player_queue.append(send)

03_pictionary/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,4 @@ The obvious next step was to turn this into a game of Pictionary! Here's what th
6868

6969
![In Action](in_action.gif)
7070

71-
You can view the running app at [moodle-game.com](https://moodle-game.com/). The code for this version is in the 'moodle_demo' folder.
71+
You can view the running app at [moodle-game.com](https://moodle-game.com/). The code for this version is in the 'moodle_demo' folder.

03_pictionary/main.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@
1111
@app.get("/")
1212
def home():
1313
return Title('Drawing Demo'), Main(
14-
H1("Haiku Canvas Demo"),
14+
H1("Haiku Canvas Demo"),
1515
Canvas(id="drawingCanvas", width="500", height="500",
16-
style="border: 1px solid black; background-color: #f0f0f0;"),
16+
style="border: 1px solid black; background-color: #f0f0f0;"),
1717
Div("Draw something", id="caption"), cls='container')
1818

1919

@@ -38,5 +38,5 @@ async def process_canvas(image: str):
3838
caption = message.content[0].text.replace("\n", "<br>")
3939
return JSONResponse({"caption": caption})
4040

41-
if __name__ == '__main__':
42-
uvicorn.run("main:app", host='0.0.0.0', port=8000, reload=True)
41+
serve()
42+

03_pictionary/moodle_demo/main.py

+53-60
Original file line numberDiff line numberDiff line change
@@ -13,28 +13,28 @@
1313
domain = "https://moodle-game.com"
1414

1515
# Wordlist
16-
words = ['lips', 'caterpillar', 'ants', 'jellyfish', 'cupcake', 'seashell', 'grass', 'island', 'coat', 'bee',
17-
'eye', 'lion', 'car', 'bus', 'boy', 'knee', 'bathroom', 'ball', 'jacket', 'flag', 'snowflake', 'football',
18-
'grapes', 'bumblebee', 'music', 'book', 'lemon', 'dragon', 'dream', 'eyes', 'balloon', 'triangle', 'sunglasses', 'zebra',
19-
'feet', 'ant', 'bed', 'rocket', 'river', 'candle', 'float', 'smile', 'alligator', 'bunny', 'plant', 'snake', 'bird', 'duck',
20-
'kitten', 'earth', 'starfish', 'ear', 'monkey', 'lollipop', 'sun', 'branch', 'blanket', 'orange', 'carrot', 'cube', 'dinosaur',
21-
'hippo', 'candy', 'jail', 'cow', 'drum', 'hamburger', 'hat', 'light', 'inchworm', 'snail', 'cat', 'shirt', 'nose', 'alive',
22-
'person', 'jar', 'tail', 'motorcycle', 'whale', 'zigzag', 'suitcase', 'backpack', 'feather', 'line', 'mitten', 'woman', 'robot',
23-
'cheese', 'chimney', 'comb', 'egg', 'worm', 'zoo', 'pizza', 'fly', 'pen', 'coin', 'apple', 'baseball', 'oval', 'skateboard', 'frog',
24-
'spoon', 'horse', 'beach', 'slide', 'ladybug', 'window', 'rabbit', 'helicopter', 'desk', 'head', 'leg', 'crayon', 'clock', 'boat',
25-
'diamond', 'bug', 'ears', 'box', 'face', 'night', 'square', 'pie', 'bear', 'finger', 'banana', 'mouth', 'nail', 'cherry', 'bike',
26-
'broom', 'fire', 'sea', 'beak', 'baby', 'bowl', 'popsicle', 'lamp', 'blocks', 'bark', 'elephant', 'spider', 'rock', 'purse', 'leaf',
27-
'ship', 'shoe', 'kite', 'mountains', 'moon', 'table', 'rain', 'sheep', 'curl', 'daisy', 'snowman', 'train', 'legs', 'swing', 'mountain',
28-
'cup', 'truck', 'flower', 'glasses', 'crab', 'owl', 'ring', 'love', 'lizard', 'door', 'heart', 'button', 'giraffe', 'chicken',
29-
'chair', 'bridge', 'key', 'neck', 'ghost', 'computer', 'bow', 'bread', 'corn', 'water', 'angel', 'fork', 'bone', 'candy', 'roof',
30-
'underwear', 'drum', 'spider', 'shoe', 'smile', 'cup', 'hat', 'bird', 'kite', 'snowman', 'doll', 'skateboard', 'sleep', 'sad',
31-
'butterfly', 'elephant', 'ocean', 'book', 'egg', 'house', 'dog', 'ball', 'star', 'shirt', 'cookie', 'fish', 'bed', 'phone', 'airplane', 'nose',
32-
'apple', 'sun', 'sandwich', 'cherry', 'bubble', 'moon', 'snow', 'rocket', 'cliff', 'stingray', 'horse', 'sack', 'paper', 'drumstick', 'teapot',
33-
'plug', 'button', 'cave', 'crumb', 'children', 'bib', 'panda', 'unite', 'eel', 'cocoon', 'cook', 'city', 'stove', 'apologize', 'maze',
34-
'sunset', 'step', 'organ', 'jump', 'ribbon', 'pizza', 'pop', 'tape', 'pot', 'table', 'calendar',
35-
'squirrel', 'letter', 'coconut', 'napkin', 'hero', 'newborn', 'doghouse', 'baby', 'turkey', 'cheetah', 'sidekick',
16+
words = ['lips', 'caterpillar', 'ants', 'jellyfish', 'cupcake', 'seashell', 'grass', 'island', 'coat', 'bee',
17+
'eye', 'lion', 'car', 'bus', 'boy', 'knee', 'bathroom', 'ball', 'jacket', 'flag', 'snowflake', 'football',
18+
'grapes', 'bumblebee', 'music', 'book', 'lemon', 'dragon', 'dream', 'eyes', 'balloon', 'triangle', 'sunglasses', 'zebra',
19+
'feet', 'ant', 'bed', 'rocket', 'river', 'candle', 'float', 'smile', 'alligator', 'bunny', 'plant', 'snake', 'bird', 'duck',
20+
'kitten', 'earth', 'starfish', 'ear', 'monkey', 'lollipop', 'sun', 'branch', 'blanket', 'orange', 'carrot', 'cube', 'dinosaur',
21+
'hippo', 'candy', 'jail', 'cow', 'drum', 'hamburger', 'hat', 'light', 'inchworm', 'snail', 'cat', 'shirt', 'nose', 'alive',
22+
'person', 'jar', 'tail', 'motorcycle', 'whale', 'zigzag', 'suitcase', 'backpack', 'feather', 'line', 'mitten', 'woman', 'robot',
23+
'cheese', 'chimney', 'comb', 'egg', 'worm', 'zoo', 'pizza', 'fly', 'pen', 'coin', 'apple', 'baseball', 'oval', 'skateboard', 'frog',
24+
'spoon', 'horse', 'beach', 'slide', 'ladybug', 'window', 'rabbit', 'helicopter', 'desk', 'head', 'leg', 'crayon', 'clock', 'boat',
25+
'diamond', 'bug', 'ears', 'box', 'face', 'night', 'square', 'pie', 'bear', 'finger', 'banana', 'mouth', 'nail', 'cherry', 'bike',
26+
'broom', 'fire', 'sea', 'beak', 'baby', 'bowl', 'popsicle', 'lamp', 'blocks', 'bark', 'elephant', 'spider', 'rock', 'purse', 'leaf',
27+
'ship', 'shoe', 'kite', 'mountains', 'moon', 'table', 'rain', 'sheep', 'curl', 'daisy', 'snowman', 'train', 'legs', 'swing', 'mountain',
28+
'cup', 'truck', 'flower', 'glasses', 'crab', 'owl', 'ring', 'love', 'lizard', 'door', 'heart', 'button', 'giraffe', 'chicken',
29+
'chair', 'bridge', 'key', 'neck', 'ghost', 'computer', 'bow', 'bread', 'corn', 'water', 'angel', 'fork', 'bone', 'candy', 'roof',
30+
'underwear', 'drum', 'spider', 'shoe', 'smile', 'cup', 'hat', 'bird', 'kite', 'snowman', 'doll', 'skateboard', 'sleep', 'sad',
31+
'butterfly', 'elephant', 'ocean', 'book', 'egg', 'house', 'dog', 'ball', 'star', 'shirt', 'cookie', 'fish', 'bed', 'phone', 'airplane', 'nose',
32+
'apple', 'sun', 'sandwich', 'cherry', 'bubble', 'moon', 'snow', 'rocket', 'cliff', 'stingray', 'horse', 'sack', 'paper', 'drumstick', 'teapot',
33+
'plug', 'button', 'cave', 'crumb', 'children', 'bib', 'panda', 'unite', 'eel', 'cocoon', 'cook', 'city', 'stove', 'apologize', 'maze',
34+
'sunset', 'step', 'organ', 'jump', 'ribbon', 'pizza', 'pop', 'tape', 'pot', 'table', 'calendar',
35+
'squirrel', 'letter', 'coconut', 'napkin', 'hero', 'newborn', 'doghouse', 'baby', 'turkey', 'cheetah', 'sidekick',
3636
'cucumber', 'crust', 'sunglasses', 'computer', 'scar', 'stick', 'grill', 'rat', 'teacher', 'farm', 'tusk',
37-
'lung', 'lock', 'refrigerator', 'ambulance', 'ship', 'harmonica', 'soda', 'eagle', 'rainstorm', 'hoof', 'fern',
37+
'lung', 'lock', 'refrigerator', 'ambulance', 'ship', 'harmonica', 'soda', 'eagle', 'rainstorm', 'hoof', 'fern',
3838
'platypus', 'pitchfork', 'pinecone', 'pencil', 'parent','trombone', 'midnight', 'sap', 'pharaoh','panda']
3939

4040
# App
@@ -77,7 +77,7 @@ def Navbar(page="home"):
7777
document.querySelector('.navbar-toggle').addEventListener('click', function() {
7878
const navbarLinks = document.querySelector('.navbar-links');
7979
navbarLinks.classList.toggle('active');
80-
80+
8181
// Toggle aria-expanded attribute
8282
const expanded = this.getAttribute('aria-expanded') === 'true' || false;
8383
this.setAttribute('aria-expanded', !expanded);
@@ -139,20 +139,20 @@ def active_area(session, last_game_id:int=None):
139139
Canvas(id="drawingCanvas", width="512", height="512", cls='actitem canvas'), # TODO style this
140140
Div(Div(B("Recent guesses:"), cls="guess", style="margin-bottom: 0.5rem;"),
141141
Div(id="guess-area",
142-
hx_trigger="every 0.3s", hx_get="/guesses",
142+
hx_trigger="every 0.3s", hx_get="/guesses",
143143
hx_target="#guess-area", hx_swap="afterbegin"),
144144
style="border: 10px solid #FF4136; height: 512px; width: 350px; overflow-y: auto; text-align: left;",
145145
cls="actitem guessarea",
146146
),
147-
cls="actcontainer",
147+
cls="actcontainer",
148148
),
149149
id="active-area")
150150

151151
# If they're in the queue, show the queue status (will poll every second for updates)
152152
if session['sid'] in player_queue:
153153

154154
# Update last request time so they don't get pruned
155-
player_queue[session['sid']]['last_request'] = time.time()
155+
player_queue[session['sid']]['last_request'] = time.time()
156156

157157
# Estimate time remaining until the player will play:
158158
remaining_times = [game_max_duration - (time.time() - game.start_time) for game in active_games]
@@ -161,7 +161,7 @@ def active_area(session, last_game_id:int=None):
161161
estimate = int(sorted(remaining_times)[position_in_queue - 1])
162162
else:
163163
estimate = game_max_duration * len(player_queue) / max_concurrent_games
164-
164+
165165
# Show the queue status # <<< TODO restyle
166166
status = Div(
167167
P("Game(s) full. You have been added to the queue."),
@@ -188,7 +188,7 @@ def active_area(session, last_game_id:int=None):
188188
style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%;"
189189
),
190190
id="active-area")
191-
191+
192192
# If they're not in an active game or the queue, show the start game button
193193
intro = P("Welcome to Moodle!",
194194
"Put your drawing skills to the test while a team of AI models try to guess your word.",
@@ -222,7 +222,7 @@ def get_recent_guesses(session):
222222
game_ended = True
223223
if game_ended:
224224
# Could make this a script that uses htmx.ajax in a Timeout instead of using a hidden div
225-
gs.append(Hidden("endgame", hx_get=f"/active_area?last_game_id={game.id}", hx_target="#active-area",
225+
gs.append(Hidden("endgame", hx_get=f"/active_area?last_game_id={game.id}", hx_target="#active-area",
226226
hx_trigger="load delay:3s",hx_swap="outerHTML", id="endgame", hx_swap_oob="outerHTML"))
227227
end_game(game)
228228
return *gs, ""
@@ -256,7 +256,7 @@ def end(session):
256256
# End the game
257257
game = [game for game in active_games if game.player == session['sid']][0]
258258
end_game(game)
259-
259+
260260
# Replace active area
261261
return active_area(session, last_game_id=game.id)
262262

@@ -309,7 +309,7 @@ def end_game(game):
309309
with db_lock:
310310
game.game_gif = gif_path
311311
games.update(game)
312-
312+
313313
if True:
314314
final_draw = drawings[game.last_drawing]
315315
# Reject if no drawings
@@ -338,7 +338,7 @@ def process_canvas(image: str, session):
338338
game.last_drawing = drawing.id
339339
games.update(game)
340340
return {'active_game': 'yes', 'latest_image': fn}
341-
341+
342342
# They clicked "Play A Game!" to start a game - updates active area
343343
@app.post("/join")
344344
def join(session):
@@ -429,7 +429,7 @@ def game_summary_page(game_id: int, session):
429429
href=twitter_url,
430430
target="_blank",
431431
cls="btn btn-primary twitter-s`hare-button"),
432-
P(""),)
432+
P(""),)
433433
content = [
434434
H3(f"Game {game_id} Summary"),
435435
P(f"Word: {game.word}"),
@@ -441,7 +441,7 @@ def game_summary_page(game_id: int, session):
441441
twitter_share,
442442
gif
443443
]
444-
444+
445445
# Twitter meta tags
446446
metas = [
447447
Meta(name="twitter:card", content="summary_large_image"),
@@ -503,19 +503,19 @@ def stats():
503503
)
504504

505505
about_md = """## About
506-
506+
507507
Moodle was born from a demo that got a little out of control. I wanted to see if any of these multi-modal
508508
LLMs could play pictionary. It turns out they can! And it's rather fun...
509509
510510
### Technical Details
511-
512-
This app is built with a new framework we're working on - [FastHTML](https://fastht.ml). It's a Python framework
511+
512+
This app is built with a new framework we're working on - [FastHTML](https://fastht.ml). It's a Python framework
513513
that makes it easy to build web apps with Python and HTML. It's still in development, but it's already pretty powerful!
514-
514+
515515
The canvas (HTML/JS) sends images to the backend, which ships them off to a few different models that try to guess the word.
516-
516+
517517
### Future Plans
518-
518+
519519
I think this will be a fun, quirky eval for models. I'm saving all the drawings (I hope you don't draw anything bad) and the progressions
520520
will make a good classification problem. Can a model guess from the final image? from the sequence? etc..."""
521521

@@ -546,7 +546,7 @@ def static(fname: str, ext: str):
546546

547547

548548
# Threaded guess loop #
549-
# For each game, for each model, we have a thread going that
549+
# For each game, for each model, we have a thread going that
550550
# sends the image to the model and gets the guess back
551551

552552
## API clients ##
@@ -660,11 +660,11 @@ def __init__(self, task_name, stop_event, func, game_idx=None, interval=3):
660660
self.interval = interval
661661
def run(self):
662662
# Debug info
663-
if self.game_idx is None:
663+
if self.game_idx is None:
664664
if thread_debug: print(f"Task {self.task_name} is starting with func {self.func}")
665-
else:
665+
else:
666666
if thread_debug: print(f"Task {self.task_name} is starting for game {self.game_idx} with guesser {self.func}")
667-
667+
668668
# Run in loop
669669
while not self.stop_event.is_set():
670670
start_time = time.time()
@@ -701,7 +701,7 @@ def run(self):
701701
if thread_debug: print(f"Game idx {self.game_idx} guess by {guesser_name}: {guess_text} (correct: {is_correct})")
702702
except Exception as e:
703703
print(f"Error: {e}")
704-
704+
705705
# Sleep for the remaining time with a bit of randomness added
706706
time.sleep(max(0, self.interval - (time.time() - start_time)) + random.random() * 0.5)
707707

@@ -713,38 +713,31 @@ def run(self):
713713

714714
def start_background_tasks():
715715
global tasks
716-
if len(tasks) > 0:
717-
print("Tasks already running")
718-
return
716+
if len(tasks) > 0: return print("Tasks already running")
719717
for i in range(max_concurrent_games):
720718
for guesser in guessers:
721719
task = BackgroundTask(f'game_{i}_guesser_{guesser}', stop_event, guessers[guesser], i)
722720
tasks.append(task)
723721
tasks.append(BackgroundTask('queue_pruner', stop_event, queue_pruner, interval=1))
724722
tasks.append(BackgroundTask('game_ender', stop_event, game_ender, interval=1))
725-
for task in tasks:
726-
task.start()
723+
for task in tasks: task.start()
727724

728725
def stop_background_tasks():
729726
print("Stopping all tasks...")
730727
stop_event.set()
731-
for task in tasks:
732-
task.join()
728+
for task in tasks: task.join()
733729
print("All tasks stopped")
734730

735731
@app.on_event("startup")
736-
async def startup_event():
737-
start_background_tasks()
732+
async def startup_event(): start_background_tasks()
738733

739734
@app.on_event("shutdown")
740-
async def shutdown_event():
741-
stop_background_tasks()
735+
async def shutdown_event(): stop_background_tasks()
742736

743737
if __name__ == "__main__":
744-
try:
745-
serve()
746-
except KeyboardInterrupt:
747-
pass
738+
try: serve()
739+
except KeyboardInterrupt: pass
748740
finally:
749741
stop_background_tasks()
750-
sys.exit(0)
742+
sys.exit(0)
743+

04_sse/sse_chatbot.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ async def get_message():
9696

9797

9898
@app.post("/send-message")
99-
async def send_message(msg: str):
99+
def send_message(msg: str):
100100
messages.append({"role": "user", "content": msg})
101101
user_msg = Div(ChatMessage(len(messages) - 1))
102102
messages.append({"role": "assistant", "content": ""})

04_sse/sse_clock_plus.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ async def time_generator():
2727
# Maybe we can patch EventSourceResponse to run to_xml automatically if FT
2828
# components are detected in the data key, so we don't have to do it here
2929
# Note: For data, converts carriage returns to extra `data:` lines in the response
30-
data=to_xml(P(datetime.now().strftime('%H:%M:%S'))),
30+
data=to_xml(P(datetime.now().strftime('%H:%M:%S'))),
3131
event="TimeUpdateEvent")
3232
await asyncio.sleep(1)
3333

04_sse/sse_clock_scroll.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from fasthtml.common import *
44

55
hdrs=(Script(src="https://unpkg.com/[email protected]/sse.js"),)
6-
app,rt = fast_app(hdrs=hdrs)
6+
app,rt = fast_app(hdrs=hdrs)
77

88
@rt
99
def index():
@@ -19,12 +19,12 @@ async def time_generator():
1919
while not shutdown_event.is_set():
2020
data = Article(datetime.now().strftime('%H:%M:%S'))
2121
yield sse_message(data)
22-
await sleep(1)
22+
await sleep(1)
2323

2424
@rt("/time-sender")
2525
async def get():
2626
"Send time to all connected clients every second"
2727
return EventStream(time_generator())
2828

2929

30-
serve()
30+
serve()

04_sse/sse_starlette_demo.py

+1-6
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,16 @@
55
from starlette.routing import Route
66
from sse_starlette.sse import EventSourceResponse
77

8-
98
async def numbers(minimum, maximum):
109
for i in range(minimum, maximum + 1):
1110
await asyncio.sleep(0.9)
1211
yield dict(data=f'{i}\n\n{i}', id=f'data-{i}', event='update_number')
1312

14-
1513
async def sse(request):
1614
generator = numbers(1, 5)
1715
return EventSourceResponse(generator)
1816

19-
2017
routes = [Route("/", endpoint=sse)]
21-
2218
app = Starlette(debug=True, routes=routes)
2319

24-
if __name__ == "__main__":
25-
uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")
20+
if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")

code_editor/code_editor.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ async def post(request: Request):
5151
code = data['code']
5252
row = data['row']
5353
column = data['column']
54-
54+
5555
try:
5656
response = client.completion.create(
5757
model=model_name,
@@ -66,4 +66,4 @@ async def post(request: Request):
6666

6767
return JSONResponse({"completion": completion})
6868

69-
serve()
69+
serve()

htmx/storage.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def index():
1111
Div(id='foo'))
1212

1313
@rt
14-
async def more(sid:str): return f'{sid}: {datetime.now()}'
14+
def more(sid:str): return f'{sid}: {datetime.now()}'
1515

1616
serve()
1717

0 commit comments

Comments
 (0)