tinyweb for Python
tinyweb’s Python implementation is a library of its own: a Python program can use it to draw on a web page, add buttons, labels and sliders to it, play sounds and answer the reader, with no Pyking anywhere. It is the file Pyking copies beside a program compiled for python14, renamed tinyweb.py.
Download tinyweb-python.zip: tinyweb.py, the example below, and the samples in tinyweb_assets/.
Running a program
The program serves its own page: web_init starts the server and prints its address, and once the program’s own code has finished it goes on serving the page and calling the functions it handed over until it is stopped (Ctrl-C). Open the address in a browser.
python3 example.pyThe page asks for a sample beside where the program runs first, then in tinyweb_assets/ there.
An example
# A canvas, two circles, two samples and buttons that play them, written# in Python against tinyweb.py. Run it with `python3 example.py` and open# the address it prints.
import tinyweb as tw
tw.web_init(0)
kick = tw.load_sample("kick1.wav")snare = tw.load_sample("snare1.wav")
canvas = tw.canvas(400, 200)tw.draw_circle(canvas, 100, 50, 30, "#ff0000")tw.draw_circle(canvas, 100, 50, 20, "#000000")
presses = 0
def play_kick(): tw.play_sample(kick, 0.0, 1.0, 1.0)
def play_snare(): global presses presses += 1 print(f"snare, press {presses}") tw.play_sample(snare, 0.0, 0.5, 1.0)
tw.make_button("Play kick", play_kick)tw.make_button("Play snare", play_snare)tw.make_button("Does nothing", lambda: None)
print("built the page")Functions
Every function but web_init needs web_init to have been called first, or PYKING_TINYWEB_LOG to be set (below); otherwise it says so and the program ends with status 1.
web_init
def web_init(port: int) -> NoneServes the program’s page on port and prints its address, tinyweb: http://127.0.0.1:N/; port 0 picks any free port. Call it before anything else. With PYKING_TINYWEB_LOG set it does nothing.
canvas
def canvas(width: int, height: int) -> intA new canvas, width by height pixels, placed below what the page already shows. Answers the number that names it.
fill_canvas
def fill_canvas(c: int, color: str) -> NoneFills the whole canvas c with color, a CSS color such as "#ff0000" or "red".
draw_circle
def draw_circle(c: int, x: int, y: int, radius: int, color: str) -> NoneA filled circle on the canvas c, centred at (x, y).
draw_rect
def draw_rect(c: int, x: int, y: int, width: int, height: int, color: str) -> NoneA filled rectangle on the canvas c, with its top left corner at (x, y).
draw_line
def draw_line(c: int, x1: int, y1: int, x2: int, y2: int, color: str, width: int) -> NoneA straight line on the canvas c, from (x1, y1) to (x2, y2), width pixels wide.
draw_text
def draw_text(c: int, x: int, y: int, words: str, color: str, size: int) -> Nonewords written on the canvas c, with the top left corner of the text at (x, y), size pixels high.
make_button
def make_button(title: str, on_click: Callable[[], None]) -> intA button showing title, placed below what the page already shows, which calls on_click each time it is pressed. Answers the number that names it.
label
def label(text: str) -> intA line of text, placed below what the page already shows. Answers the number that names it to set_label.
set_label
def set_label(id: int, text: str) -> NoneReplaces the text of the label id with text.
make_slider
def make_slider(low: int, high: int, value: int, on_change: Callable[[int], None]) -> intA slider from low to high, starting at value, placed below what the page already shows, which calls on_change with each new value it is moved to. Answers the number that names it.
apply_style
def apply_style(id: int, kind: str, property: str, value: str) -> NoneChanges the page’s look. With kind “theme”, value names a theme: “light” (the default), “dark”, “plain”, “paper” or “retro”. With kind “page”, “button”, “label”, “slider” or “canvas”, property of every element of that kind becomes value; with kind “element”, only the element id’s. property is one of background, color, border, radius, font, size, padding, gap, accent and width, and value is CSS, such as “#336699” or “12px”. id is 0 except for an element.
load_sample
def load_sample(name: str) -> intStarts loading the sound file name and answers a number naming it to play_sample. The name is looked up beside where the program runs first, and then among the samples tinyweb ships in tinyweb_assets/: kick1.wav, snare1.wav, hihat1.wav and piano_c1.wav.
play_sample
def play_sample(sample: int, at: float, volume: float, rate: float) -> NonePlays the sample sample: at the time at on the page’s clock, or now if that has passed; volume times as loud, and rate times as fast, which raises its pitch as much.
time
def time() -> floatThe page’s clock, in seconds, as the page last reported it: inside an on_frame callback, the time the frame is for. It is the audio clock once sound has started, so a time read here is a time play_sample can be given.
on_frame
def on_frame(draw: Callable[[float], None]) -> NoneCalls draw before each frame the page shows, with the time the frame is for.
on_mouse
def on_mouse(c: int, click: Callable[[int, int], None]) -> NoneCalls click with the position, in pixels from the top left corner, of every click on the canvas c.
on_key
def on_key(pressed: Callable[[str], None]) -> NoneCalls pressed with the name of every key pressed while the page has the focus: a letter or digit as itself, and otherwise the browser’s name for it, such as “ArrowLeft”, “Enter” or ” ”.
Without a page
Two environment variables, each a file path, run a program with no page at all, which is how it is tested: with PYKING_TINYWEB_LOG set, every command the program would send its page is appended to that file as one line, and once the program’s own code has finished the events PYKING_TINYWEB_EVENTS lists — click ID, slide ID VALUE, frame T, mouse ID X Y, key NAME, one per line — are delivered as if a reader had caused them.
PYKING_TINYWEB_LOG=page.log PYKING_TINYWEB_EVENTS=clicks.txt python3 example.pyWhat Pyking generates
Pyking’s own tinyweb tests, compiled for python14. Each comes with the libraries it needs as Pyking writes them — tinyweb’s implementation under its own name, and the module Pyking compiles from tinyweb’s Pyking half — and is built and run with:
python3 program.pylib_tinyweb_frames
# Animation kept in time with sound: each frame is drawn for the time# the page gives it, and each beat is scheduled half a second ahead on# the same clock, so it sounds where the picture says it is. The# .events file delivers four frames.
import tinyweb as tw
tw.web_init(0)
c = tw.canvas(200, 100)kick = tw.load_sample("kick1.wav")beat = 0.5var next_beat = 0.0
def draw(t: Float): tw.clear(c, "#111111") tw.circle(c, int(t * 100.0), 50, 10, "#ffcc00") if t >= next_beat: print("beat scheduled at " ++ string(next_beat + beat) ++ ", drawn at " ++ string(t)) tw.play(kick, at = next_beat + beat) next_beat := next_beat + beat
tw.on_frame(draw)print(tw.time())program.py, as Pyking generates it
# --- prelude begins ---
def __pyk_fdiv(a, b): if b == 0.0: # Python raises where IEEE answers. Pyking follows IEEE. if a != a or a == 0.0: return float('nan') below = (a < 0.0) != (repr(b)[0] == '-') return float('-inf') if below else float('inf') return a / b
def __pyk_float(x): if x != x: return 'nan' if x == float('inf'): return 'inf' if x == float('-inf'): return '-inf' if x == 0.0: # The two zeros compare equal; repr tells them apart. return '-0.0' if repr(x)[0] == '-' else '0.0' sign = '-' if x < 0.0 else '' a = abs(x) p = 0 while p < 16: s = '%.*e' % (p, a) if float(s) == a: break p = p + 1 else: s = '%.*e' % (16, a) at = s.index('e') digits = s[:at].replace('.', '') decpt = int(s[at + 1:]) + 1 digits = digits.rstrip('0') or '0' n = len(digits) if decpt <= -4 or decpt > 16: mantissa = digits if n == 1 else digits[0] + '.' + digits[1:] return sign + mantissa + 'e' + str(decpt - 1) if decpt <= 0: return sign + '0.' + '0' * (-decpt) + digits if decpt >= n: return sign + digits + '0' * (decpt - n) + '.0' return sign + digits[:decpt] + '.' + digits[decpt:]
def __pyk_trunc(x): if x != x or x in (float('inf'), float('-inf')): return 0 n = int(x) return n if -2147483648 <= n <= 2147483647 else 0
# --- prelude ends; the compiled program follows ---
import tinyweb as twimport tinyweb_external as tw_externaltw_external.web_init(0)c = tw_external.canvas(200, 100)kick = tw_external.load_sample('kick1.wav')beat = 0.5next_beat = 0.0
def draw(t): global next_beat tw.clear(c, '#111111') tw.circle(c, __pyk_trunc(t * 100.0), 50, 10, '#ffcc00') if t >= next_beat: print('beat scheduled at ' + str(__pyk_float(next_beat + beat)) + ', drawn at ' + str(__pyk_float(t))) tw.play(kick, next_beat + beat, tw.play__default__volume(), tw.play__default__rate()) next_beat = next_beat + beat return ()
tw_external.on_frame(draw)print(__pyk_float(tw_external.time()))lib_tinyweb_input
# The mouse, the keyboard and a slider, each reported on a label, and# the other drawing functions. The .events file clicks the canvas,# presses two keys -- the second Enter -- and moves the slider.
import tinyweb as tw
tw.web_init(0)
c = tw.canvas(300, 200)tw.rect(c, 0, 0, 300, 200, "#eeeeee")tw.line(c, 0, 0, 300, 200)tw.line(c, 0, 200, 300, 0, "red", width = 3)tw.text(c, 10, 10, "click \"me\"", size = 20)status = tw.label("nothing yet")
def clicked(x: Int, y: Int): tw.set_label(status, "clicked at " ++ string(x) ++ ", " ++ string(y)) tw.circle(c, x, y, 5, "blue")
def pressed(key: String): print("key [" ++ key ++ "]") if key == "Enter": tw.play_file("snare1.wav")
def moved(value: Int): tw.set_label(status, "slider at " ++ string(value))
tw.on_mouse(c, clicked)tw.on_key(pressed)tw.slider(0, 10, 5, on_change = moved)tw.slider(1, 3, 2)program.py, as Pyking generates it
import tinyweb as twimport tinyweb_external as tw_externaltw_external.web_init(0)c = tw_external.canvas(300, 200)tw.rect(c, 0, 0, 300, 200, '#eeeeee')tw.line(c, 0, 0, 300, 200, tw.line__default__color(), tw.line__default__width())tw.line(c, 0, 200, 300, 0, 'red', 3)tw.text(c, 10, 10, 'click "me"', tw.text__default__color(), 20)status = tw_external.label('nothing yet')
def clicked(x, y): tw_external.set_label(status, 'clicked at ' + str(x) + ', ' + str(y)) return tw.circle(c, x, y, 5, 'blue')
def pressed(key): print('key [' + key + ']') if key == 'Enter': tw.play_file('snare1.wav') return ()
def moved(value): return tw_external.set_label(status, 'slider at ' + str(value))
tw_external.on_mouse(c, clicked)tw_external.on_key(pressed)tw.slider(0, 10, 5, moved)tw.slider(1, 3, 2, tw.slider__default__on_change())lib_tinyweb_sound_graphics1
# A canvas, two circles, two samples and buttons that play them: the# first tinyweb program.
import tinyweb as tw
tw.web_init(0)
kick = tw.load_sample("kick1.wav")snare = tw.load_sample("snare1.wav")
canvas = tw.canvas(400, 200)
tw.circle(canvas, 100, 50, 30, "#ff0000") # canvas, x, y, radius, colortw.circle(canvas, 100, 50, 20) # the color defaults to "#000000"
var presses = 0
def play_kick(): tw.play(kick)
def play_sound(): presses := presses + 1 print("snare, press " ++ string(presses)) tw.play(snare, volume = 0.5)
tw.button("Play kick", on_click = play_kick)tw.button("Play snare", on_click = play_sound)tw.button("Does nothing") # on_click is optional
print("built the page")lib_tinyweb_sound_graphics1.zip
program.py, as Pyking generates it
# --- prelude begins ---
def __pyk_fdiv(a, b): if b == 0.0: # Python raises where IEEE answers. Pyking follows IEEE. if a != a or a == 0.0: return float('nan') below = (a < 0.0) != (repr(b)[0] == '-') return float('-inf') if below else float('inf') return a / b
def __pyk_float(x): if x != x: return 'nan' if x == float('inf'): return 'inf' if x == float('-inf'): return '-inf' if x == 0.0: # The two zeros compare equal; repr tells them apart. return '-0.0' if repr(x)[0] == '-' else '0.0' sign = '-' if x < 0.0 else '' a = abs(x) p = 0 while p < 16: s = '%.*e' % (p, a) if float(s) == a: break p = p + 1 else: s = '%.*e' % (16, a) at = s.index('e') digits = s[:at].replace('.', '') decpt = int(s[at + 1:]) + 1 digits = digits.rstrip('0') or '0' n = len(digits) if decpt <= -4 or decpt > 16: mantissa = digits if n == 1 else digits[0] + '.' + digits[1:] return sign + mantissa + 'e' + str(decpt - 1) if decpt <= 0: return sign + '0.' + '0' * (-decpt) + digits if decpt >= n: return sign + digits + '0' * (decpt - n) + '.0' return sign + digits[:decpt] + '.' + digits[decpt:]
# --- prelude ends; the compiled program follows ---
import tinyweb as twimport tinyweb_external as tw_externaltw_external.web_init(0)kick = tw_external.load_sample('kick1.wav')snare = tw_external.load_sample('snare1.wav')canvas = tw_external.canvas(400, 200)tw.circle(canvas, 100, 50, 30, '#ff0000')tw.circle(canvas, 100, 50, 20, tw.circle__default__color())presses = 0
def play_kick(): return tw.play(kick, tw.play__default__at(), tw.play__default__volume(), tw.play__default__rate())
def play_sound(): global presses presses = presses + 1 print('snare, press ' + str(presses)) return tw.play(snare, tw.play__default__at(), 0.5, tw.play__default__rate())
tw.button('Play kick', play_kick)tw.button('Play snare', play_sound)tw.button('Does nothing', tw.button__default__on_click())print('built the page')lib_tinyweb_style
# The page's look: a theme, the style of every element of a kind, and# the style of one element. The .events file presses the button, which# changes the theme and one label while the page is showing.
import tinyweb as tw
tw.web_init(0)
tw.theme("paper")tw.theme("no such theme")tw.page_style(background = "#fdf6e3", color = "#586e75", font = "serif", size = 18, padding = 12, gap = 16)tw.button_style(background = "#268bd2", color = "white", border = "none", radius = 14, font = "monospace", size = 16, padding = 8)tw.label_style(background = "lightyellow", color = "#333333", border = "1px solid gold", radius = 4, font = "sans-serif", size = 14, padding = 6)tw.slider_style(accent = "crimson", width = 240, color = "crimson", font = "monospace", size = 20)tw.canvas_style(border = "3px solid teal", radius = 10)
title = tw.label("Styled")tw.set_style(title, background = "navy", color = "white", border = "2px dashed orange", radius = 0, font = "Georgia", size = 28, padding = 10, width = 300)level = tw.slider(0, 10, 4)tw.set_colors(level, color = "seagreen")c = tw.canvas(120, 60)tw.set_style(c, border = "1px solid black")
def pressed(): tw.theme("retro") tw.set_colors(title, background = "black") print("now retro")
ok = tw.button("Retro", on_click = pressed)tw.set_colors(ok, color = "black", background = "gold")program.py, as Pyking generates it
import tinyweb as twimport tinyweb_external as tw_externaltw_external.web_init(0)tw.theme('paper')tw.theme('no such theme')tw.page_style('#fdf6e3', '#586e75', 'serif', 18, 12, 16)tw.button_style('#268bd2', 'white', 'none', 14, 'monospace', 16, 8)tw.label_style('lightyellow', '#333333', '1px solid gold', 4, 'sans-serif', 14, 6)tw.slider_style('crimson', 240, 'crimson', 'monospace', 20)tw.canvas_style('3px solid teal', 10)title = tw_external.label('Styled')tw.set_style(title, 'navy', 'white', '2px dashed orange', 0, 'Georgia', 28, 10, tw.set_style__default__accent(), 300)level = tw.slider(0, 10, 4, tw.slider__default__on_change())tw.set_colors(level, 'seagreen', tw.set_colors__default__background())c = tw_external.canvas(120, 60)tw.set_style(c, tw.set_style__default__background(), tw.set_style__default__color(), '1px solid black', tw.set_style__default__radius(), tw.set_style__default__font(), tw.set_style__default__size(), tw.set_style__default__padding(), tw.set_style__default__accent(), tw.set_style__default__width())
def pressed(): tw.theme('retro') tw.set_colors(title, tw.set_colors__default__color(), 'black') print('now retro') return ()
ok = tw.button('Retro', pressed)tw.set_colors(ok, 'black', 'gold')