main.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. #!/usr/bin/env python3
  2. import importlib
  3. import inspect
  4. import os
  5. from pathlib import Path
  6. from typing import Awaitable, Callable, Optional
  7. from urllib.parse import parse_qs
  8. from fastapi import Request
  9. from fastapi.responses import FileResponse, RedirectResponse, Response
  10. from starlette.middleware.base import BaseHTTPMiddleware
  11. from starlette.middleware.sessions import SessionMiddleware
  12. from starlette.types import ASGIApp, Receive, Scope, Send
  13. import prometheus
  14. from nicegui import Client, app
  15. from nicegui import globals as nicegui_globals
  16. from nicegui import ui
  17. from website import documentation, example_card, svg
  18. from website.demo import bash_window, browser_window, python_window
  19. from website.documentation_tools import create_anchor_name, element_demo, generate_class_doc
  20. from website.search import Search
  21. from website.star import add_star
  22. from website.style import example_link, features, heading, link_target, section_heading, side_menu, subtitle, title
  23. prometheus.start_monitor(app)
  24. # session middleware is required for demo in documentation and prometheus
  25. app.add_middleware(SessionMiddleware, secret_key=os.environ.get('NICEGUI_SECRET_KEY', ''))
  26. app.add_static_files('/favicon', str(Path(__file__).parent / 'website' / 'favicon'))
  27. app.add_static_files('/fonts', str(Path(__file__).parent / 'website' / 'fonts'))
  28. app.add_static_files('/static', str(Path(__file__).parent / 'website' / 'static'))
  29. if True: # HACK: prevent the page from scrolling when closing a dialog (#1404)
  30. def on_dialog_value_change(sender, value, on_value_change=ui.dialog.on_value_change) -> None:
  31. ui.query('html').classes(**{'add' if value else 'remove': 'has-dialog'})
  32. on_value_change(sender, value)
  33. ui.dialog.on_value_change = on_dialog_value_change
  34. @app.get('/logo.png')
  35. def logo() -> FileResponse:
  36. return FileResponse(svg.PATH / 'logo.png', media_type='image/png')
  37. @app.get('/logo_square.png')
  38. def logo_square() -> FileResponse:
  39. return FileResponse(svg.PATH / 'logo_square.png', media_type='image/png')
  40. @app.post('/dark_mode')
  41. async def dark_mode(request: Request) -> None:
  42. app.storage.browser['dark_mode'] = (await request.json()).get('value')
  43. @app.middleware('http')
  44. async def redirect_reference_to_documentation(request: Request,
  45. call_next: Callable[[Request], Awaitable[Response]]) -> Response:
  46. if request.url.path == '/reference':
  47. return RedirectResponse('/documentation')
  48. return await call_next(request)
  49. # NOTE In our global fly.io deployment we need to make sure that we connect back to the same instance.
  50. fly_instance_id = os.environ.get('FLY_ALLOC_ID', 'local').split('-')[0]
  51. nicegui_globals.socket_io_js_extra_headers['fly-force-instance-id'] = fly_instance_id # for HTTP long polling
  52. nicegui_globals.socket_io_js_query_params['fly_instance_id'] = fly_instance_id # for websocket (FlyReplayMiddleware)
  53. class FlyReplayMiddleware(BaseHTTPMiddleware):
  54. """Replay to correct fly.io instance.
  55. If the wrong instance was picked by the fly.io load balancer, we use the fly-replay header
  56. to repeat the request again on the right instance.
  57. This only works if the correct instance is provided as a query_string parameter.
  58. """
  59. def __init__(self, app: ASGIApp) -> None:
  60. self.app = app
  61. async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
  62. query_string = scope.get('query_string', b'').decode()
  63. query_params = parse_qs(query_string)
  64. target_instance = query_params.get('fly_instance_id', [fly_instance_id])[0]
  65. async def send_wrapper(message):
  66. if target_instance != fly_instance_id:
  67. if message['type'] == 'websocket.close':
  68. # fly.io only seems to look at the fly-replay header if websocket is accepted
  69. message = {'type': 'websocket.accept'}
  70. if 'headers' not in message:
  71. message['headers'] = []
  72. message['headers'].append([b'fly-replay', f'instance={target_instance}'.encode()])
  73. await send(message)
  74. await self.app(scope, receive, send_wrapper)
  75. app.add_middleware(FlyReplayMiddleware)
  76. def add_head_html() -> None:
  77. ui.add_head_html((Path(__file__).parent / 'website' / 'static' / 'header.html').read_text())
  78. ui.add_head_html(f"<style>{(Path(__file__).parent / 'website' / 'static' / 'style.css').read_text()}</style>")
  79. def add_header(menu: Optional[ui.left_drawer] = None) -> None:
  80. menu_items = {
  81. 'Installation': '/#installation',
  82. 'Features': '/#features',
  83. 'Demos': '/#demos',
  84. 'Documentation': '/documentation',
  85. 'Examples': '/#examples',
  86. 'Why?': '/#why',
  87. }
  88. dark_mode = ui.dark_mode(value=app.storage.browser.get('dark_mode'), on_change=lambda e: ui.run_javascript(f'''
  89. fetch('/dark_mode', {{
  90. method: 'POST',
  91. headers: {{'Content-Type': 'application/json'}},
  92. body: JSON.stringify({{value: {e.value}}}),
  93. }});
  94. ''', respond=False))
  95. with ui.header() \
  96. .classes('items-center duration-200 p-0 px-4 no-wrap') \
  97. .style('box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1)'):
  98. if menu:
  99. ui.button(on_click=menu.toggle, icon='menu').props('flat color=white round').classes('lg:hidden')
  100. with ui.link(target=index_page).classes('row gap-4 items-center no-wrap mr-auto'):
  101. svg.face().classes('w-8 stroke-white stroke-2 max-[550px]:hidden')
  102. svg.word().classes('w-24')
  103. with ui.row().classes('max-[1050px]:hidden'):
  104. for title, target in menu_items.items():
  105. ui.link(title, target).classes(replace='text-lg text-white')
  106. search = Search()
  107. search.create_button()
  108. with ui.element().classes('max-[360px]:hidden'):
  109. ui.button(icon='dark_mode', on_click=lambda: dark_mode.set_value(None)) \
  110. .props('flat fab-mini color=white').bind_visibility_from(dark_mode, 'value', value=True)
  111. ui.button(icon='light_mode', on_click=lambda: dark_mode.set_value(True)) \
  112. .props('flat fab-mini color=white').bind_visibility_from(dark_mode, 'value', value=False)
  113. ui.button(icon='brightness_auto', on_click=lambda: dark_mode.set_value(False)) \
  114. .props('flat fab-mini color=white').bind_visibility_from(dark_mode, 'value', lambda mode: mode is None)
  115. with ui.link(target='https://discord.gg/TEpFeAaF4f').classes('max-[455px]:hidden').tooltip('Discord'):
  116. svg.discord().classes('fill-white scale-125 m-1')
  117. with ui.link(target='https://www.reddit.com/r/nicegui/').classes('max-[405px]:hidden').tooltip('Reddit'):
  118. svg.reddit().classes('fill-white scale-125 m-1')
  119. with ui.link(target='https://github.com/zauberzeug/nicegui/').classes('max-[305px]:hidden').tooltip('GitHub'):
  120. svg.github().classes('fill-white scale-125 m-1')
  121. add_star().classes('max-[490px]:hidden')
  122. with ui.row().classes('min-[1051px]:hidden'):
  123. with ui.button(icon='more_vert').props('flat color=white round'):
  124. with ui.menu().classes('bg-primary text-white text-lg'):
  125. for title, target in menu_items.items():
  126. ui.menu_item(title, on_click=lambda target=target: ui.open(target))
  127. @ui.page('/')
  128. async def index_page(client: Client) -> None:
  129. client.content.classes('p-0 gap-0')
  130. add_head_html()
  131. add_header()
  132. with ui.row().classes('w-full h-screen items-center gap-8 pr-4 no-wrap into-section'):
  133. svg.face(half=True).classes('stroke-black dark:stroke-white w-[200px] md:w-[230px] lg:w-[300px]')
  134. with ui.column().classes('gap-4 md:gap-8 pt-32'):
  135. title('Meet the *NiceGUI*.')
  136. subtitle('And let any browser be the frontend of your Python code.') \
  137. .classes('max-w-[20rem] sm:max-w-[24rem] md:max-w-[30rem]')
  138. ui.link(target='#about').classes('scroll-indicator')
  139. with ui.row().classes('''
  140. dark-box min-h-screen no-wrap
  141. justify-center items-center flex-col md:flex-row
  142. py-20 px-8 lg:px-16
  143. gap-8 sm:gap-16 md:gap-8 lg:gap-16
  144. '''):
  145. link_target('about')
  146. with ui.column().classes('text-white max-w-4xl'):
  147. heading('Interact with Python through buttons, dialogs, 3D&nbsp;scenes, plots and much more.')
  148. with ui.column().classes('gap-2 bold-links arrow-links text-lg'):
  149. ui.markdown('''
  150. NiceGUI manages web development details, letting you focus on Python code for diverse applications,
  151. including robotics, IoT solutions, smart home automation, and machine learning.
  152. Designed to work smoothly with connected peripherals like webcams and GPIO pins in IoT setups,
  153. NiceGUI streamlines the management of all your code in one place.
  154. <br><br>
  155. With a gentle learning curve, NiceGUI is user-friendly for beginners
  156. and offers advanced customization for experienced users,
  157. ensuring simplicity for basic tasks and feasibility for complex projects.
  158. <br><br><br>
  159. Available as
  160. [PyPI package](https://pypi.org/project/nicegui/),
  161. [Docker image](https://hub.docker.com/r/zauberzeug/nicegui) and on
  162. [GitHub](https://github.com/zauberzeug/nicegui).
  163. ''')
  164. example_card.create()
  165. with ui.column().classes('w-full text-lg p-8 lg:p-16 max-w-[1600px] mx-auto'):
  166. link_target('installation', '-50px')
  167. section_heading('Installation', 'Get *started*')
  168. with ui.row().classes('w-full text-lg leading-tight grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-8'):
  169. with ui.column().classes('w-full max-w-md gap-2'):
  170. ui.html('<em>1.</em>').classes('text-3xl font-bold')
  171. ui.markdown('Create __main.py__').classes('text-lg')
  172. with python_window(classes='w-full h-52'):
  173. ui.markdown('''
  174. ```python\n
  175. from nicegui import ui
  176. ui.label('Hello NiceGUI!')
  177. ui.run()
  178. ```
  179. ''')
  180. with ui.column().classes('w-full max-w-md gap-2'):
  181. ui.html('<em>2.</em>').classes('text-3xl font-bold')
  182. ui.markdown('Install and launch').classes('text-lg')
  183. with bash_window(classes='w-full h-52'):
  184. ui.markdown('''
  185. ```bash
  186. pip3 install nicegui
  187. python3 main.py
  188. ```
  189. ''')
  190. with ui.column().classes('w-full max-w-md gap-2'):
  191. ui.html('<em>3.</em>').classes('text-3xl font-bold')
  192. ui.markdown('Enjoy!').classes('text-lg')
  193. with browser_window(classes='w-full h-52'):
  194. ui.label('Hello NiceGUI!')
  195. with ui.expansion('...or use Docker to run your main.py').classes('w-full gap-2 bold-links arrow-links'):
  196. with ui.row().classes('mt-8 w-full justify-center items-center gap-8'):
  197. ui.markdown('''
  198. With our [multi-arch Docker image](https://hub.docker.com/repository/docker/zauberzeug/nicegui)
  199. you can start the server without installing any packages.
  200. The command searches for `main.py` in in your current directory and makes the app available at http://localhost:8888.
  201. ''').classes('max-w-xl')
  202. with bash_window(classes='max-w-lg w-full h-52'):
  203. ui.markdown('''
  204. ```bash
  205. docker run -it --rm -p 8888:8080 \\
  206. -v "$PWD":/app zauberzeug/nicegui
  207. ```
  208. ''')
  209. with ui.column().classes('w-full p-8 lg:p-16 bold-links arrow-links max-w-[1600px] mx-auto'):
  210. link_target('features', '-50px')
  211. section_heading('Features', 'Code *nicely*')
  212. with ui.row().classes('w-full text-lg leading-tight grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-8'):
  213. features('swap_horiz', 'Interaction', [
  214. 'buttons, switches, sliders, inputs, ...',
  215. 'notifications, dialogs and menus',
  216. 'interactive images with SVG overlays',
  217. 'web pages and native window apps',
  218. ])
  219. features('space_dashboard', 'Layout', [
  220. 'navigation bars, tabs, panels, ...',
  221. 'grouping with rows, columns, grids and cards',
  222. 'HTML and Markdown elements',
  223. 'flex layout by default',
  224. ])
  225. features('insights', 'Visualization', [
  226. 'charts, diagrams and tables',
  227. '3D scenes',
  228. 'straight-forward data binding',
  229. 'built-in timer for data refresh',
  230. ])
  231. features('brush', 'Styling', [
  232. 'customizable color themes',
  233. 'custom CSS and classes',
  234. 'modern look with material design',
  235. '[Tailwind CSS](https://tailwindcss.com/) auto-completion',
  236. ])
  237. features('source', 'Coding', [
  238. 'routing for multiple pages',
  239. 'auto-reload on code change',
  240. 'persistent user sessions',
  241. 'Jupyter notebook compatibility',
  242. ])
  243. features('anchor', 'Foundation', [
  244. 'generic [Vue](https://vuejs.org/) to Python bridge',
  245. 'dynamic GUI through [Quasar](https://quasar.dev/)',
  246. 'content is served with [FastAPI](http://fastapi.tiangolo.com/)',
  247. 'Python 3.8+',
  248. ])
  249. with ui.column().classes('w-full p-8 lg:p-16 max-w-[1600px] mx-auto'):
  250. link_target('demos', '-50px')
  251. section_heading('Demos', 'Try *this*')
  252. with ui.column().classes('w-full'):
  253. documentation.create_intro()
  254. with ui.column().classes('dark-box p-8 lg:p-16 my-16'):
  255. with ui.column().classes('mx-auto items-center gap-y-8 gap-x-32 lg:flex-row'):
  256. with ui.column().classes('gap-1 max-lg:items-center max-lg:text-center'):
  257. ui.markdown('Browse through plenty of live demos.') \
  258. .classes('text-white text-2xl md:text-3xl font-medium')
  259. ui.html('Fun-Fact: This whole website is also coded with NiceGUI.') \
  260. .classes('text-white text-lg md:text-xl')
  261. ui.link('Documentation', '/documentation').style('color: black !important') \
  262. .classes('rounded-full mx-auto px-12 py-2 bg-white font-medium text-lg md:text-xl')
  263. with ui.column().classes('w-full p-8 lg:p-16 max-w-[1600px] mx-auto'):
  264. link_target('examples', '-50px')
  265. section_heading('In-depth examples', 'Pick your *solution*')
  266. with ui.row().classes('w-full text-lg leading-tight grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4'):
  267. example_link('Slideshow', 'implements a keyboard-controlled image slideshow')
  268. example_link('Authentication', 'shows how to use sessions to build a login screen')
  269. example_link('Modularization',
  270. 'provides an example of how to modularize your application into multiple files and reuse code')
  271. example_link('FastAPI', 'illustrates the integration of NiceGUI with an existing FastAPI application')
  272. example_link('Map',
  273. 'demonstrates wrapping the JavaScript library [leaflet](https://leafletjs.com/) '
  274. 'to display a map at specific locations')
  275. example_link('AI Interface',
  276. 'utilizes the [replicate](https://replicate.com) library to perform voice-to-text '
  277. 'transcription and generate images from prompts with Stable Diffusion')
  278. example_link('3D Scene', 'creates a webGL view and loads an STL mesh illuminated with a spotlight')
  279. example_link('Custom Vue Component', 'shows how to write and integrate a custom Vue component')
  280. example_link('Image Mask Overlay', 'shows how to overlay an image with a mask')
  281. example_link('Infinite Scroll', 'presents an infinitely scrolling image gallery')
  282. example_link('OpenCV Webcam', 'uses OpenCV to capture images from a webcam')
  283. example_link('SVG Clock', 'displays an analog clock by updating an SVG with `ui.timer`')
  284. example_link('Progress', 'demonstrates a progress bar for heavy computations')
  285. example_link('NGINX Subpath', 'shows the setup to serve an app behind a reverse proxy subpath')
  286. example_link('Script Executor', 'executes scripts on selection and displays the output')
  287. example_link('Local File Picker', 'demonstrates a dialog for selecting files locally on the server')
  288. example_link('Search as you type', 'using public API of thecocktaildb.com to search for cocktails')
  289. example_link('Menu and Tabs', 'uses Quasar to create foldable menu and tabs inside a header bar')
  290. example_link('Todo list', 'shows a simple todo list with checkboxes and text input')
  291. example_link('Trello Cards', 'shows Trello-like cards that can be dragged and dropped into columns')
  292. example_link('Slots', 'shows how to use scoped slots to customize Quasar elements')
  293. example_link('Table and slots', 'shows how to use component slots in a table')
  294. example_link('Single Page App', 'navigate without reloading the page')
  295. example_link('Chat App', 'a simple chat app')
  296. example_link('Chat with AI', 'a simple chat app with AI')
  297. example_link('SQLite Database', 'CRUD operations on a SQLite database with async-support through Tortoise ORM')
  298. example_link('Pandas DataFrame', 'displays an editable [pandas](https://pandas.pydata.org) DataFrame')
  299. example_link('Lightbox', 'A thumbnail gallery where each image can be clicked to enlarge')
  300. example_link('ROS2', 'Using NiceGUI as web interface for a ROS2 robot')
  301. example_link('Docker Image',
  302. 'Demonstrate using the official '
  303. '[zauberzeug/nicegui](https://hub.docker.com/r/zauberzeug/nicegui) docker image')
  304. example_link('Download Text as File', 'providing in-memory data like strings as file download')
  305. example_link('Generate PDF', 'create SVG preview and PDF download from input form elements')
  306. with ui.row().classes('dark-box min-h-screen mt-16'):
  307. link_target('why')
  308. with ui.column().classes('''
  309. max-w-[1600px] m-auto
  310. py-20 px-8 lg:px-16
  311. items-center justify-center no-wrap flex-col md:flex-row gap-16
  312. '''):
  313. with ui.column().classes('gap-8'):
  314. heading('Why?')
  315. with ui.column().classes('gap-2 text-xl text-white bold-links arrow-links'):
  316. ui.markdown(
  317. 'We at '
  318. '[Zauberzeug](https://zauberzeug.com) '
  319. 'like '
  320. '[Streamlit](https://streamlit.io/) '
  321. 'but find it does '
  322. '[too much magic](https://github.com/zauberzeug/nicegui/issues/1#issuecomment-847413651) '
  323. 'when it comes to state handling. '
  324. 'In search for an alternative nice library to write simple graphical user interfaces in Python we discovered '
  325. '[JustPy](https://justpy.io/). '
  326. 'Although we liked the approach, it is too "low-level HTML" for our daily usage. '
  327. 'But it inspired us to use '
  328. '[Vue](https://vuejs.org/) '
  329. 'and '
  330. '[Quasar](https://quasar.dev/) '
  331. 'for the frontend.')
  332. ui.markdown(
  333. 'We have built on top of '
  334. '[FastAPI](https://fastapi.tiangolo.com/), '
  335. 'which itself is based on the ASGI framework '
  336. '[Starlette](https://www.starlette.io/) '
  337. 'and the ASGI webserver '
  338. '[Uvicorn](https://www.uvicorn.org/) '
  339. 'because of their great performance and ease of use.'
  340. )
  341. svg.face().classes('stroke-white shrink-0 w-[200px] md:w-[300px] lg:w-[450px]')
  342. @ui.page('/documentation')
  343. def documentation_page() -> None:
  344. add_head_html()
  345. menu = side_menu()
  346. add_header(menu)
  347. ui.add_head_html('<style>html {scroll-behavior: auto;}</style>')
  348. with ui.column().classes('w-full p-8 lg:p-16 max-w-[1250px] mx-auto'):
  349. section_heading('Reference, Demos and more', '*NiceGUI* Documentation')
  350. documentation.create_full()
  351. @ui.page('/documentation/{name}')
  352. async def documentation_page_more(name: str, client: Client) -> None:
  353. if name in {'ag_grid', 'e_chart'}:
  354. name = name.replace('_', '') # NOTE: "AG Grid" leads to anchor name "ag_grid", but class is `ui.aggrid`
  355. module = importlib.import_module(f'website.more_documentation.{name}_documentation')
  356. more = getattr(module, 'more', None)
  357. if hasattr(ui, name):
  358. api = getattr(ui, name)
  359. back_link_target = str(api.__doc__ or api.__init__.__doc__).splitlines()[0].strip()
  360. else:
  361. api = name
  362. back_link_target = name
  363. add_head_html()
  364. add_header()
  365. with side_menu() as menu:
  366. ui.markdown(f'[← back](/documentation#{create_anchor_name(back_link_target)})').classes('bold-links')
  367. with ui.column().classes('w-full p-8 lg:p-16 max-w-[1250px] mx-auto'):
  368. section_heading('Documentation', f'ui.*{name}*' if hasattr(ui, name) else f'*{name.replace("_", " ").title()}*')
  369. with menu:
  370. ui.markdown('**Demos**' if more else '**Demo**').classes('mt-4')
  371. element_demo(api)(getattr(module, 'main_demo'))
  372. if more:
  373. more()
  374. if inspect.isclass(api):
  375. with menu:
  376. ui.markdown('**Reference**').classes('mt-4')
  377. ui.markdown('## Reference').classes('mt-16')
  378. generate_class_doc(api)
  379. await client.connected()
  380. await ui.run_javascript(f'document.title = "{name} • NiceGUI";', respond=False)
  381. ui.run(uvicorn_reload_includes='*.py, *.css, *.html')