-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathllms_ctx.txt
1785 lines (1460 loc) · 63.1 KB
/
llms_ctx.txt
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<document>
<title>FastHTML Gallery Examples</title>
<description>FastHTML Gallery bring minimal examples of FastHTML apps to allow you to get started with FastHTML more easily</description>
<category name="Applications">
<example name="Annotate Text">
from fasthtml.common import *
import json
import httpx
# Set up the app, including daisyui and tailwind for the chat component
tlink = Script(src="https://cdn.tailwindcss.com?plugins=typography"),
dlink = Link(rel="stylesheet", href="https://cdn.jsdelivr.net/npm/[email protected]/dist/full.min.css")
def Arrow(arrow, hx_get, id):
# Grey out button if you're at the end
if arrow == "←": ptr_evnts = "pointer-events-none opacity-50" if id == 1 else ""
elif arrow == "→": ptr_evnts = " pointer-events-none opacity-50" if id == total_items_length - 1 else ""
# CSS Styling for both arrow buttons
common_classes = "relative inline-flex items-center bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
return A(Span(arrow, cls="sr-only"),
Span(arrow, cls="h-5 w-5", aria_hidden="true"),
hx_get=hx_get, hx_swap="outerHTML",
cls=f" {'' if arrow=='←' else '-ml-px'} rounded-{'l' if arrow=='←' else 'r'}-md {common_classes} {ptr_evnts}")
def AnnotateButton(value, feedback):
# Different button styling if it's already marked as correct/incorrect
classes = '' if feedback=='correct' else 'btn-outline'
# Green for correct red for incorrect
classes += f" btn-{'success' if value=='correct' else 'error'}"
classes += ' mr-2' if value=='correct' else ''
return Button(value.capitalize(), name='feedback', value=value, cls='btn hover:text-white '+classes)
def render(Item):
messages = json.loads(Item.messages)
card_header = Div(cls="border-b border-gray-200 bg-white p-4")(
Div(cls="flex justify-between items-center mb-4")(
H3(f"Sample {Item.id} out of {total_items_length}" if total_items_length else "No samples in DB", cls="text-base font-semibold leading-6 text-gray-9000"),
Div(cls="flex-shrink-0")(
Arrow("←", f"{Item.id - 2}" if Item.id > 0 else "#", Item.id),
Arrow("→", f"{Item.id}" if Item.id < total_items_length - 1 else "#", Item.id))),
Div(cls="-ml-4 -mt-4 flex flex-wrap items-center justify-between sm:flex-nowrap")(
Div(cls="ml-4 mt-4")(
P(messages[0]['content'], cls="mt-1 text-sm text-gray-500 max-h-16 overflow-y-auto whitespace-pre-wrap"))))
card_buttons_form = Div(cls="mt-4")(
Form(cls="flex items-center", method="post", hx_post=f"{Item.id}", target_id=f"item_{Item.id}", hx_swap="outerHTML", hx_encoding="multipart/form-data")(
Input(type="text", name="notes", value=Item.notes, placeholder="Additional notes?", cls="flex-grow p-2 my-4 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 bg-transparent"),
Div(cls="flex-shrink-0 ml-4")(
AnnotateButton('correct', Item.feedback),
AnnotateButton('incorrect', Item.feedback))))
# Card component
card = Div(cls=" flex flex-col h-full flex-grow overflow-auto", id=f"item_{Item.id}",
style="min-height: calc(100vh - 6rem); max-height: calc(100vh - 16rem);")(
card_header,
Div(cls="bg-white shadow rounded-b-lg p-4 pt-0 pb-10 flex-grow overflow-scroll")(
Div(messages[1]['content'], id="main_text", cls="mt-2 w-full rounded-t-lg text-sm whitespace-pre-wrap h-auto marked")),
card_buttons_form)
return card
hdrs=(tlink, dlink, picolink, MarkdownJS(), HighlightJS())
app, rt, texts_db, Item = fast_app('texts.db',hdrs=hdrs, render=render, bodykw={"data-theme":"light"},
id=int, messages=list, feedback=bool, notes=str, pk='id')
# Get Dummy Data
data_url = 'https://raw.githubusercontent.com/AnswerDotAI/fasthtml-example/main/annotate_text/data/dummy_data.jsonl'
response = httpx.get(data_url)
# Insert Dummy Data into Db
for line in response.text.splitlines():
item = json.loads(line)
texts_db.insert(messages=json.dumps(item), feedback=None, notes='')
# Set total_items_length after inserting dummy data
total_items_length = len(texts_db())
print(f"Inserted {total_items_length} items from dummy data")
@rt("/{idx}")
def post(idx: int, feedback: str = None, notes: str = None):
print(f"Posting feedback: {feedback} and notes: {notes} for item {idx}")
items = texts_db()
item = texts_db.get(idx)
item.feedback, item.notes = feedback, notes
texts_db.update(item)
next_item = next((i for i in items if i.id > item.id), items[0])
print(f"Updated item {item.id} with feedback: {feedback} and notes: {notes} moving to {next_item.id}")
return next_item
@rt("/")
@rt("/{idx}")
def get(idx:int = 0):
items = texts_db()
index = idx
if index >= len(items): index = len(items) - 1 if items else 0
# Container for card and buttons
content = Div(cls="w-full max-w-2xl mx-auto flex flex-col max-h-full")(
H1('LLM generated text annotation tool with FastHTML (and Tailwind)',cls="text-xl font-bold text-center text-gray-800 mb-8"),
items[index])
return Main(content,
cls="container mx-auto min-h-screen bg-gray-100 p-8 flex flex-col",
hx_target="this")
</example>
<example name="Cellular Automata">
from fasthtml.common import *
from starlette.responses import Response
from uuid import uuid4
generator = {}
bindict = {
(1,1,1):0,
(1,1,0):1,
(1,0,1):2,
(1,0,0):3,
(0,1,1):4,
(0,1,0):5,
(0,0,1):6,
(0,0,0):7}
initial_row = [0]*50 + [1] + [0]*50
color_map = {0:"white", 1:"black"}
####################
### HTML Widgets ###
####################
explanation = Div(
H1("Cellular Automata"),
H4("Input explanations:"),
Ul(Li(Strong("Rule: "),"Determines the next state of a cell based on the current state of the cell and its neighbors."),
Li(Strong("Generations: "),"Determines how many generations to run the automaton."),
Li(Strong("Width: "),"Determines the width of the grid."),))
def progress_bar(percent_complete: float):
return Div(hx_swap_oob="innerHTML:#progress_bar")(
Progress(value=percent_complete))
def mk_box(color,size=5):
return Div(cls="box", style=f"background-color:{color_map[color]};height:{size}px;width:{size}px;margin:0;display:inline-block;")
def mk_row(colors,font_size=0,size=5):
return Div(*[mk_box(color,size) for color in colors], cls="row",style=f"font-size:{font_size}px;")
def mk_button(show):
return Button("Hide Rule" if show else "Show Rule",
hx_get="show_rule?show=" + ("False" if show else "True"),
hx_target="#rule", id="sh_rule", hx_swap_oob="outerHTML",
hx_include="[name='rule_number']")
########################
### FastHTML Section ###
########################
app, rt = fast_app()
@rt
def index(sess):
if 'id' not in sess: sess['id'] = str(uuid4())
return Title("Cellular Automata"),Main(Div(
Div(P(explanation,id="explanations")),
Form(Group(
Div(hx_target='this', hx_swap='outerHTML')(Label(_for="rule_number", cls="form-label")("Rule"),
Input(type='number', name="rule_number", id='rule_set', value="30",hx_post='validate/rule_number')),
Div(hx_target='this', hx_swap='outerHTML')(Label("Generations", cls="form-label"),
Input(type='number',name="generations", id='generations_set', value="50",hx_post='validate/generations', hx_indicator='#generationsind')),
Div(hx_target='this', hx_swap='outerHTML')(Label("Width", cls="form-label"),
Input(type='number',name="width", id='width_set', value="100", hx_post='validate/width', hx_indicator='#widthind')),
Button(cls="btn btn-active btn-primary", type="submit", hx_get="run",
hx_target="#grid", hx_include="[name='rule_number'],[name='generations'],[name='width']", hx_swap="outerHTML")("Run"))),
Group(
Div(style="margin-left:50px")(
Div(id="progress_bar"),
Div(id="grid")),
Div(style="margin-right:50px; max-width:200px")(
mk_button(False),
Div(id="rule"),
))))
@rt('/show_rule')
def get(rule_number: int, show: bool):
rule = [int(x) for x in f'{rule_number:08b}']
return Div(
Div(mk_button(show)),
Div(*[Group(
Div(mk_row(list(k),font_size=10,size=20),style="max-width:100px"),
Div(P(" -> "),style="max-width:100px"),
Div(mk_box(rule[v],size=20),style="max-width:100px")) for k,v in bindict.items()] if show else '')
)
@rt('/run')
def get(rule_number: int, generations: int, width: int, sess):
errors = {'rule_number': validate_rule_number(rule_number),
'generations': validate_generations(generations),
'width': validate_width(width)}
# Removes the None values from the errors dictionary (No errors)
errors = {k: v for k, v in errors.items() if v is not None}
# Return Button with error message if they exist
if errors:
return Div(Div(id="grid"),
Div(id="progress_bar",hx_swap_oob="outerHTML:#progress_bar"),
Div(id='submit-btn-container',hx_swap_oob="outerHTML:#submit-btn-container")(
Button(cls="btn btn-active btn-primary", type="submit",
hx_get="run", hx_target="#grid",
hx_include="[name='rule_number'],[name='generations'],[name='width']", hx_swap="outerHTML")("Run"),
*[Div(error, style='color: red;') for error in errors.values()]))
start = [0]*(width//2) + [1] + [0]*(width//2)
global generator
generator[sess['id']] = run(rule=rule_number,generations=generations,start=start)
return Div(
Div(style=f"width: {(width+1)*5}px",id="progress_bar",hx_swap_oob="outerHTML:#progress_bar"),
Div(id="next",hx_trigger="every .1s", hx_get="next", hx_target="#grid",hx_swap="beforeend"),id="grid")
@rt('/next')
def get(sess):
global generator
g,val = next(generator[sess['id']],(False,False))
if val: return Div(
progress_bar(g),
mk_row(val))
else:
del generator[sess['id']]
return Response(status_code=286)
@rt('/validate/rule_number')
def post(rule_number: int): return inputTemplate('Rule Number', 'rule_number',rule_number, validate_rule_number(rule_number))
@rt('/validate/generations')
def post(generations: int): return inputTemplate('Generations', 'generations', generations, validate_generations(generations))
@rt('/validate/width')
def post(width: int): return inputTemplate('Width', 'width', width, validate_width(width))
#########################
### Application Logic ###
#########################
def run(rule=30, start = initial_row, generations = 100):
rule = [int(x) for x in f'{rule:08b}']
yield 0, start
old_row = [0] + start + [0]
new_row = []
for g in range(1,generations):
for i in range(1,len(old_row)-1):
key=tuple(old_row[i-1:i+2])
new_row.append(rule[bindict[key]])
yield (g+1)/generations,new_row
old_row = [0] + new_row + [0]
new_row = []
########################
### Validation Logic ###
########################
def validate_rule_number(rule_number: int):
if (rule_number < 0) or (rule_number > 255 ): return "Enter an integer between 0 and 255 (inclusive)"
def validate_generations(generations: int):
if generations < 0: return "Enter a positive integer"
if generations > 200: return "Enter a number less than 200"
def validate_width(width: int):
if width < 0: return "Enter a positive integer"
if width > 200: return "Enter a number less than 200"
def inputTemplate(label, name, val, errorMsg=None, input_type='number'):
# Generic template for replacing the input field and showing the validation message
return Div(hx_target='this', hx_swap='outerHTML', cls=f"{errorMsg if errorMsg else 'Valid'}")(
Label(label), # Creates label for the input field
Input(name=name,type=input_type,value=f'{val}',style="width: 340px;",hx_post=f'validate/{name.lower()}'), # Creates input field
Div(f'{errorMsg}', style='color: red;') if errorMsg else None) # Creates red error message below if there is an error
</example>
<example name="Csv Editor">
from fasthtml.common import *
from uuid import uuid4
db = database('sqlite.db')
hdrs = (Style('''
button,input { margin: 0 1rem; }
[role="group"] { border: 1px solid #ccc; }
.edited { outline: 2px solid orange; }
'''), )
app, rt = fast_app(hdrs=hdrs)
@rt
async def get_test_file():
import httpx
url = "https://raw.githubusercontent.com/AnswerDotAI/FastHTML-Gallery/main/applications/start_simple/csv_editor/ex_data.csv"
response = await httpx.AsyncClient().get(url)
return Response(response.text, media_type="text/csv",
headers={'Content-Disposition': 'attachment; filename="ex_data.csv"'})
@rt
def index(sess):
if 'id' not in sess: sess['id'] = str(uuid4())
return Titled("CSV Uploader",
A('Download Example CSV', href="get_test_file", download="ex_data.csv"),
Group(Input(type="file", name="csv_file", accept=".csv"),
Button("Upload", hx_post="upload", hx_target="#results",
hx_encoding="multipart/form-data", hx_include='previous input'),
A('Download', href='download', type="button")),
Div(id="results"))
def render_row(row):
vals = [Td(Input(value=v, name=k, oninput="this.classList.add('edited')")) for k,v in row.items()]
vals.append(Td(Group(Button('delete', hx_delete=remove.rt(id=row['id']).lstrip('/')),
Button('update', hx_post='update', hx_include="closest tr"))))
return Tr(*vals, hx_target='closest tr', hx_swap='outerHTML')
@rt
def download(sess):
tbl = db[sess['id']]
csv_data = [",".join(map(str, tbl.columns_dict))]
csv_data += [",".join(map(str, row.values())) for row in tbl()]
headers = {'Content-Disposition': 'attachment; filename="data.csv"'}
return Response("\n".join(csv_data), media_type="text/csv", headers=headers)
@rt('/update')
def post(d:dict, sess): return render_row(db[sess['id']].update(d))
@app.delete('/remove')
def remove(id:int, sess): db[sess['id']].delete(id)
@rt("/upload")
def post(csv_file: UploadFile, sess):
db[sess['id']].drop(ignore=True)
if not csv_file.filename.endswith('.csv'): return "Please upload a CSV file"
content = b''
for i, line in enumerate(csv_file.file):
if i >= 51: break
content += line
tbl = db.import_file(sess['id'], content, pk='id')
header = Tr(*map(Th, tbl.columns_dict))
vals = [render_row(row) for row in tbl()]
return (Span('First 50 rows only', style="color: red;") if i>=51 else '', Table(Thead(header), Tbody(*vals)))
serve()
</example>
<example name="Tic Tac Toe">
from fasthtml.common import *
style = Style("""body{
min-height: 100vh;
margin:0;
background-color: #1A1A1E;
display:grid;
}""") # custom style to be applied globally.
hdrs = (Script(src="https://cdn.tailwindcss.com") ,
Link(rel="stylesheet", href="/files/examples/applications/tic_tac_toe/output.css"))
app, rt = fast_app(hdrs=(hdrs, style), pico=False)
current_state_index = -1 #Used to navigate the current snapshot of the board
button_states = [[None for _ in range(9)] for _ in range(9)] #2D array to store snapshots of board
win_states = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
] #possible win streaks/states for Xs and Os
winner_found_game_ended = False
def check_win(player) -> bool:
global button_states, current_state_index, winner_found_game_ended
"""Checks if there's a win streak present in the board. Uses the win states list to check
If text at all text indices are equal and its not the placeholder text ("."), change the global variable "winner_found_game_ended" to True"""
for cell_1, cell_2, cell_3 in win_states:
if (
button_states[current_state_index][cell_1] != None
and button_states[current_state_index][cell_1]
== button_states[current_state_index][cell_2]
and button_states[current_state_index][cell_2]
== button_states[current_state_index][cell_3]):
winner_found_game_ended = True
return f"Player {player} wins the game!"
if all(value is not None for value in button_states[current_state_index]):
#if the current snapshot of the board doesn't have any placeholder text and there is no winning streak
winner_found_game_ended = True
return "No Winner :("
#will keep returning this value [because its called after every button click], until a winner or none is found
return f'''Player {'X' if player == 'O' else 'O'}'s turn!'''
def handle_click(index: int):
"""This function handles what text gets sent to the button's face depending on whose turn it is uses a weird algorithm"""
global button_states, current_state_index
next_index = current_state_index + 1
button_states[next_index] = button_states[current_state_index][:] #make a copy of the current snapshot to add to the next snapshot
if button_states[current_state_index][index] is None:
if "X" not in button_states[current_state_index] or button_states[
current_state_index
].count("X") <= button_states[current_state_index].count("O"):
button_states[next_index][index] = "X"
else:
button_states[next_index][index] = "O"
current_state_index += 1
return button_states[next_index][index]
@app.get("/on_click") # On click, call helper function to alternate between X and O
def render_button(index:int):
global button_states, current_state_index
player = handle_click(index)
winner = check_win(player) # function that checks if there's a winner
buttons = [Button(
f'''{text if text is not None else '.' }''',
cls="tic-button-disabled" if (text is not None) or winner_found_game_ended else "tic-button",
disabled=True if (text is not None) or winner_found_game_ended else False,
hx_get=f"on_click?index={idx}",
hx_target=".buttons-div", hx_swap='outerHTML')
for idx, text in enumerate(button_states[current_state_index])
]
"""rerenders buttons based on the next snapshot.
I initially made this to render only the button that gets clicked.
But to be able to check the winner and stop the game, I have to use the next snapshot instead
if you wanna see the previous implementation, it should be in one of the commits."""
board = Div(
Div(winner, cls="justify-self-center"),
Div(*buttons, cls="grid grid-cols-3 grid-rows-3"),
cls="buttons-div font-bevan text-white font-light grid justify-center")
return board
# Rerenders the board if the restart button is clicked.
# Also responsible for initial rendering of board when webpage is reloaded
@app.get("/restart")
def render_board():
global button_states, current_state_index, winner_found_game_ended
current_state_index = -1
button_states = [[None for _ in range(9)] for _ in range(9)]
winner_found_game_ended = False
# button component
buttons = [
Button(
".",
cls="tic-button",
hx_get=f"on_click?index={i}",
hx_swap="outerHTML", hx_target=".buttons-div")
for i, _ in enumerate(button_states[current_state_index])
]
return Div(Div("Player X starts the game",cls="font-bevan text-white justify-self-center"),
Div(*buttons, cls="grid grid-cols-3 grid-rows-3"),
cls="buttons-div grid")
@app.get("/")
def homepage():
global button_states
return Div(
Div(
H1("Tic Tac Toe!", cls="font-bevan text-5xl text-white"),
P("A FastHTML app by Adedara Adeloro", cls="font-bevan text-custom-blue font-light"),
cls="m-14"),
Div(
render_board.__wrapped__(), # render buttons.
Div(
Button(
"Restart!",
disabled=False,
cls="restart-button",
hx_get="restart", hx_target=".buttons-div", hx_swap="outerHTML"),
cls="flex flex-col items-center justify-center m-10"),
cls="flex flex-col items-center justify-center"),
cls="justify-center items-center min-h-screen bg-custom-background")
</example>
</category>
<category name="Dynamic User Interface (Htmx)">
<example name="Animations">
import random
from fasthtml.common import *
app, rt = fast_app(hdrs=(Style("""
/* CSS to center content of the app */
body { max-width: 800px; padding: 20px; width: 90%; margin: 0 auto; }
* { text-align: center; }
/* CSS to fade in to full opacity in 1 second */
#fade-me-in.htmx-added {
opacity: 0;
}
#fade-me-in {
opacity: 1;
transition: opacity 1s ease-out;
}
/* CSS to fade out to 0 opacity in 1 second */
.fade-me-out {
opacity: 1;
}
.fade-me-out.htmx-swapping {
opacity: 0;
transition: opacity 1s ease-out;
}
"""),))
@rt
def color_throb_demo():
# Each time this route is called it chooses a random color
random_color = random.choice(['red', 'blue', 'green', 'yellow', 'orange', 'purple', 'pink'])
return P("Groovy baby, yeah!", id="color-demo",
# Make text random color and do a smooth transition
style=f"color: {random_color}; transition: all 1s ease-in;",
# Call this route and replace the text every 1 second
get=color_throb_demo, hx_swap="outerHTML", hx_trigger="every 1s")
# 2. Settling Transitions
@rt
def fade_in_demo():
return Button( "Fade Me In", id="fade-me-in", class_="btn primary",
# hx_trigger defaults to click so we do not have to specify it
# When the button is clicked, create a new button with a 1 second settling transition
post=fade_in_demo, hx_swap="outerHTML settle:1s")
def in_flight_animation_demo():
" Create a form that changes its look on click. In this case it displays a 'Submitted!' response. "
return Form(
Input(name="name", style="width: 300px;", placeholder="Content field"),
Button("Submit", class_="btn primary"),
# When the button is clicked, swap it with the button specified in form_completion_message
post=form_completion_message, hx_swap="outerHTML")
@rt
def form_completion_message():
# A button with green background and white text
return Button("Submitted!", class_="btn primary",
style="background-color: green; color: white;")
# Helper function to create a section for an example
def section(title, desc, content): return Card(H2(title), P(desc), Br(), content, Br())
@rt
def index():
return Div(
H1("Text Animations"), Br(),
section("Color Throb",
"Change text color every second in a smooth transition.",
color_throb_demo()),
section("Settling Transitions",
"Make a button disappear on click and gradually fade in.",
fade_in_demo()),
section("Request In Flight Animation",
"Let a form change its look on click. In this case it displays a 'Submitted!' response.",
in_flight_animation_demo()))
serve()
</example>
<example name="Cascading Dropdowns">
from fasthtml.common import *
app, rt = fast_app()
chapters = ['ch1', 'ch2', 'ch3']
lessons = {
'ch1': ['lesson1', 'lesson2', 'lesson3'],
'ch2': ['lesson4', 'lesson5', 'lesson6'],
'ch3': ['lesson7', 'lesson8', 'lesson9']}
def mk_opts(nm, cs):
return (
Option(f'-- select {nm} --', disabled='', selected='', value=''),
*map(Option, cs))
@rt
def get_lessons(chapter: str):
return Select(*mk_opts('lesson', lessons[chapter]), name='lesson')
@rt
def index():
chapter_dropdown = Select(
*mk_opts('chapter', chapters),
name='chapter',
get='get_lessons', hx_target='#lessons')
return Div(
Div(Label("Chapter:", for_="chapter"),
chapter_dropdown),
Div(Label("Lesson:", for_="lesson"),
Div(Div(id='lessons')),))
</example>
<example name="Click To Edit">
from fasthtml.common import *
app, rt = fast_app()
flds = dict(firstName='First Name', lastName='Last Name', email='Email')
@dataclass
class Contact:
firstName:str; lastName:str; email:str; edit:bool=False
def __ft__(self):
def item(k, v):
val = getattr(self,v)
return Div(Label(Strong(k), val), Hidden(val, id=v))
return Form(
*(item(v,k) for k,v in flds.items()),
Button('Click To Edit'),
post='form', hx_swap='outerHTML')
contacts = [Contact('Joe', 'Blow', '[email protected]')]
@rt
def index(): return contacts[0]
@rt
def form(c:Contact):
def item(k,v): return Div(Label(k), Input(name=v, value=getattr(c,v)))
return Form(
*(item(v,k) for k,v in flds.items()),
Button('Submit', name='btn', value='submit'),
Button('Cancel', name='btn', value='cancel'),
post="contact", hx_swap='outerHTML'
)
@rt
def contact(c:Contact, btn:str):
if btn=='submit': contacts[0] = c
return contacts[0]
</example>
<example name="Click To Load">
from uuid import uuid4
from fasthtml.common import *
app, rt = fast_app()
agent_num = 0
@rt
def add_row():
global agent_num
agent_num += 1
return Tr(map(Td, (
f"Agent Smith {agent_num}",
f"smith{agent_num}@matrix.com",
uuid4())))
@rt
def index():
first_row = add_row()
return Div(
H1("Click to Load"),
P("Dynamically add rows to a table using HTMX."),
Table(Tr(map(Th, ("Name", "Email", "ID"))), first_row, id='tbl'),
Button("Load More...", get=add_row, hx_target="#tbl", hx_swap="beforeend"),
style="text-align: center;")
serve()
</example>
<example name="Configurable Select">
from fasthtml.common import *
from monsterui.all import *
app, rt = fast_app(hdrs=Theme.blue.headers())
@rt
def index(): return Container(H1('Configurable Select'), mk_form())
@rt
def mk_form(add_option:str=None, options:str='isaac,hamel,curtis'):
opts = options.split(',')
if add_option: opts.append(add_option)
return Form(
# fh-frankenui helper that adds both a form label and input
# and does proper linking with for, id, and name automatically
LabelInput("Add an Option", id="add_option"),
Button("Add"),
# fh-frankenui select allows for search boxes
UkSelect(map(Option, opts), searchable=True),
# When the "Add" button is pressed, make a new form
get=mk_form,
# Store options state in DOM
hx_vals={"options": ','.join(opts)},
# Replace the whole form
hx_swap="outerHTML")
serve()
</example>
<example name="Custom Keybindings">
from fasthtml.common import *
app, rt = fast_app()
@rt
def index():return Titled(
"Custom Keybindings with HTMX",
render_button("DO IT (Press `Shift + u`)"))
@rt
def doit(): return render_button("😀 DID IT! ")
def render_button(text):
return Button(text,
# Auto-focus on load
autofocus=True,
# Activate with click or U key as long as focus is in body
hx_trigger="click, keyup[key=='U'] from:body",
get=doit)
serve()
</example>
<example name="Infinite Scroll">
from fasthtml.common import *
import uuid
column_names = ('name', 'email', 'id')
def generate_contact(id: int) -> Dict[str, str]:
return {'name': 'Agent Smith',
'email': f'void{str(id)}@matrix.com',
'id': str(uuid.uuid4())
}
def generate_table_row(row_num: int) -> Tr:
contact = generate_contact(row_num)
return Tr(*[Td(contact[key]) for key in column_names])
def generate_table_part(part_num: int = 1, size: int = 20) -> Tuple[Tr]:
paginated = [generate_table_row((part_num - 1) * size + i) for i in range(size)]
paginated[-1].attrs.update({
'get': f'page?idx={part_num + 1}',
'hx-trigger': 'revealed',
'hx-swap': 'afterend'})
return tuple(paginated)
app, rt = fast_app()
@rt
def index():
return Titled('Infinite Scroll',
Div(Table(
Thead(Tr(*[Th(key) for key in column_names])),
Tbody(generate_table_part(1)))))
@rt
def page(idx:int|None = 0):
return generate_table_part(idx)
</example>
<example name="Inline Validation">
from fasthtml.common import *
import re
################
### FastHTML ###
################
app, rt = fast_app()
@rt
def index():
return Form(post='submit', hx_target='#submit-btn-container', hx_swap='outerHTML')(
# Calls /email route to validate email
Div(hx_target='this', hx_swap='outerHTML')(
Label(_for='email')('Email Address'),
Input(type='text', name='email', id='email', post='email')),
# Calls /cool route to validate cool
Div(hx_target='this', hx_swap='outerHTML')(
Label(_for='cool')('Is this cool?'),
Input(type='text', name='cool', id='cool', post='cool')),
# Calls /coolscale route to validate coolscale
Div(hx_target='this', hx_swap='outerHTML')(
Label(_for='CoolScale')('How cool (scale of 1 - 10)?'),
Input(type='number', name='CoolScale', id='CoolScale', post='coolscale')),
# Submits the form which calls /submit route to validate whole form
Div(id='submit-btn-container')(
Button(type='submit', id='submit-btn',)('Submit')))
### Field Validation Routing ###
# Validates the field and generates FastHTML with appropriate validation and template function
@rt
def email(email: str): return inputTemplate('Email Address', 'email', email, validate_email(email))
@rt
def cool(cool: str): return inputTemplate('Is this cool?', 'cool', cool, validate_cool(cool))
@rt
def coolscale(CoolScale: int): return inputTemplate('How cool (scale of 1 - 10)?', 'CoolScale', CoolScale, validate_coolscale(CoolScale), input_type='number')
@rt
def submit(email: str, cool: str, CoolScale: int):
# Validates all fields in the form
errors = {'email': validate_email(email),
'cool': validate_cool(cool),
'coolscale': validate_coolscale(CoolScale) }
# Removes the None values from the errors dictionary (No errors)
errors = {k: v for k, v in errors.items() if v is not None}
# Return Button with error message if they exist
return Div(id='submit-btn-container')(
Button(type='submit', id='submit-btn', post='submit', hx_target='#submit-btn-container', hx_swap='outerHTML')('Submit'),
*[Div(error, style='color: red;') for error in errors.values()])
########################
### Validation Logic ###
########################
def validate_email(email: str):
# Check if email address is a valid one
email_regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
if not re.match(email_regex, email): return "Please enter a valid email address"
# Check if email address is already taken (in this case only [email protected] will pass)
elif email != "[email protected]": return "That email is already taken. Please enter another email (only [email protected] will pass)."
# If no errors, return None (default of python)
def validate_cool(cool: str):
if cool.lower() not in ["yes", "definitely"]: return "Yes or definitely are the only correct answers"
def validate_coolscale(CoolScale: int):
if CoolScale < 1 or CoolScale > 10: return "Please enter a number between 1 and 10"
######################
### HTML Templates ###
######################
def inputTemplate(label, name, val, errorMsg=None, input_type='text'):
# Generic template for replacing the input field and showing the validation message
return Div(hx_target='this', hx_swap='outerHTML', cls=f"{errorMsg if errorMsg else 'Valid'}")(
Label(label), # Creates label for the input field
Input(name=name,type=input_type,value=f'{val}',post=f'{name.lower()}'), # Creates input field
Div(f'{errorMsg}', style='color: red;') if errorMsg else None) # Creates red error message below if there is an error
</example>
<example name="Loading Indicator">
from fasthtml.common import *
from monsterui.all import *
import asyncio
app, rt = fast_app(hdrs=Theme.blue.headers())
@rt
def index():
return Titled("Loading Demo",
# Button to trigger an HTMX request
Button("Load", id='load',
# Trigger HTMX request to add content to #content
get=load, hx_target='#content', hx_swap='beforeend',
# While request in flight, show loading indicator
hx_indicator='#loading'),
# A place to put content from request
Div(id='content'),
# Loading indicator ready for htmx use
# For more options see https://monsterui.answer.ai/api_ref/docs_loading
Loading(id='loading', htmx_indicator=True))
@rt
async def load():
# Sleep for a second to simulate a long request
await asyncio.sleep(1)
return P("Loading Demo")
serve()
</example>
<example name="Multi Image Upload">
from base64 import b64encode
from fasthtml.common import *
app, rt = fast_app()
@rt
def index():
inp = Card(
H3("Drag and drop images here", style="text-align: center;"),
# HTMX for uploading multiple images
Input(type="file",name="images", multiple=True, required=True,
# Call the upload route on change
post=upload, hx_target="#image-list", hx_swap="afterbegin", hx_trigger="change",
# encoding for multipart
hx_encoding="multipart/form-data",accept="image/*"),
# Make a nice border to show the drop zone
style="border: 2px solid #ccc; border-radius: 8px;",)
return Titled("Multi Image Upload",
inp,
H3("👇 Uploaded images 👇", style="text-align: center;"),
Div(id="image-list"))
async def ImageCard(image):
contents = await image.read()
# Create a base64 string
img_data = f"data:{image.content_type};base64,{b64encode(contents).decode()}"
# Create a card with the image
return Card(H4(image.filename), Img(src=img_data, alt=image.filename))
@rt
async def upload(images: list[UploadFile]):
# Create a grid filled with 1 image card per image
return Grid(*[await ImageCard(image) for image in images])
serve()
</example>
<example name="Progress Bar">
from fasthtml.common import *
import random
app, rt = fast_app()
def get_progress(percent_complete: int):
"Simulate progress check"
return percent_complete + random.random()/3
@rt
def index():
return (Div(H3("Start the job to see progress!"),id='progress_bar'),
Button("Start Job",post=update_status, hx_target="#progress_bar"))
@rt
def update_status():
"Start job and progress bar"
return progress_bar(percent_complete=0)
@rt
def update_progress(percent_complete: float):
# Check if done
if percent_complete >= 1: return H3("Job Complete!", id="progress_bar")
# get progress
percent_complete = get_progress(percent_complete)
# Update progress bar
return progress_bar(percent_complete)
def progress_bar(percent_complete: float):
return Progress(id="progress_bar",value=percent_complete,
get=update_progress,hx_target="#progress_bar",hx_trigger="every 500ms",
hx_vals=f"js:'percent_complete': '{percent_complete}'")
serve()
</example>
<example name="Show Hide">
from fasthtml.common import *
app, rt = fast_app()
content = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sit amet volutpat tellus, in tincidunt magna. Vivamus congue posuere ligula a cursus. Sed efficitur tortor quis nisi mollis, eu aliquet nunc malesuada. Nulla semper lacus lacus, non sollicitudin velit mollis nec. Phasellus pharetra lobortis nisi ac eleifend. Suspendisse commodo dolor vitae efficitur lobortis. Nulla a venenatis libero, a congue nibh. Fusce ac pretium orci, in vehicula lorem. Aenean lacus ipsum, molestie quis magna id, lacinia finibus neque. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Interdum et malesuada fames ac ante ipsum primis in faucibus. Maecenas ac ex luctus, dictum erat ut, bibendum enim. Curabitur et est quis sapien consequat fringilla a sit amet purus."""
def mk_button(show):
return Button("Hide" if show else "Show",
hx_get="toggle?show=" + ("False" if show else "True"),
hx_target="#content", id="toggle", hx_swap_oob="outerHTML")
@rt
def index():
return Div(mk_button(False), Div(id="content"))
@rt
def toggle(show: bool):
return Div(
Div(mk_button(show)),
Div(content if show else ''))
</example>
<example name="Two Column Grid">
from fasthtml.common import *
app, rt = fast_app()
@rt
def index():
return Titled('Try editing fields:',
Grid(Div(
Form(post="submit", hx_target="#result", hx_trigger="input delay:200ms")(
Select(Option("One"), Option("Two"), id="select"),