main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. #!/usr/bin/env python3
  2. import importlib
  3. import inspect
  4. if True:
  5. # increasing max decode packets to be able to transfer images
  6. # see https://github.com/miguelgrinberg/python-engineio/issues/142
  7. from engineio.payload import Payload
  8. Payload.max_decode_packets = 500
  9. import os
  10. from pathlib import Path
  11. from fastapi import Request
  12. from fastapi.responses import FileResponse, RedirectResponse
  13. from starlette.middleware.sessions import SessionMiddleware
  14. import prometheus
  15. from nicegui import Client, app
  16. from nicegui import globals as nicegui_globals
  17. from nicegui import ui
  18. from website import documentation, example_card, svg
  19. from website.demo import bash_window, browser_window, python_window
  20. from website.documentation_tools import create_anchor_name, element_demo, generate_class_doc
  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='NiceGUI is awesome!')
  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.get('/logo.png')
  29. def logo():
  30. return FileResponse(svg.PATH / 'logo.png', media_type='image/png')
  31. @app.get('/logo_square.png')
  32. def logo():
  33. return FileResponse(svg.PATH / 'logo_square.png', media_type='image/png')
  34. @app.middleware('http')
  35. async def redirect_reference_to_documentation(request: Request, call_next):
  36. if request.url.path == '/reference':
  37. return RedirectResponse('/documentation')
  38. return await call_next(request)
  39. # NOTE in our global fly.io deployment we need to make sure that the websocket connects back to the same instance
  40. fly_instance_id = os.environ.get('FLY_ALLOC_ID', '').split('-')[0]
  41. if fly_instance_id:
  42. nicegui_globals.socket_io_js_extra_headers['fly-force-instance-id'] = fly_instance_id
  43. def add_head_html() -> None:
  44. ui.add_head_html((Path(__file__).parent / 'website' / 'static' / 'header.html').read_text())
  45. ui.add_head_html(f"<style>{(Path(__file__).parent / 'website' / 'static' / 'style.css').read_text()}</style>")
  46. def add_header() -> None:
  47. menu_items = {
  48. 'Features': '/#features',
  49. 'Installation': '/#installation',
  50. 'Demos': '/#demos',
  51. 'Documentation': '/documentation',
  52. 'Examples': '/#examples',
  53. 'Why?': '/#why',
  54. }
  55. with ui.header() \
  56. .classes('items-center duration-200 p-0 px-4 no-wrap') \
  57. .style('box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1)'):
  58. with ui.link(target=index_page).classes('row gap-4 items-center no-wrap mr-auto'):
  59. svg.face().classes('w-8 stroke-white stroke-2')
  60. svg.word().classes('w-24')
  61. with ui.row().classes('lg:hidden'):
  62. with ui.menu().classes('bg-primary text-white text-lg') as menu:
  63. for title, target in menu_items.items():
  64. ui.menu_item(title, on_click=lambda _, target=target: ui.open(target))
  65. ui.button(on_click=menu.open).props('flat color=white icon=menu')
  66. with ui.row().classes('max-lg:hidden'):
  67. for title, target in menu_items.items():
  68. ui.link(title, target).classes(replace='text-lg text-white')
  69. with ui.link(target='https://discord.gg/TEpFeAaF4f'):
  70. svg.discord().classes('fill-white scale-125 m-1')
  71. with ui.link(target='https://github.com/zauberzeug/nicegui/'):
  72. svg.github().classes('fill-white scale-125 m-1')
  73. add_star()
  74. @ui.page('/')
  75. async def index_page(client: Client):
  76. client.content.classes('p-0 gap-0')
  77. add_head_html()
  78. add_header()
  79. with ui.row().classes('w-full h-screen items-center gap-8 pr-4 no-wrap into-section'):
  80. svg.face(half=True).classes('stroke-black w-[200px] md:w-[230px] lg:w-[300px]')
  81. with ui.column().classes('gap-4 md:gap-8 pt-32'):
  82. title('Meet the *NiceGUI*.')
  83. subtitle('And let any browser be the frontend of your Python code.') \
  84. .classes('max-w-[20rem] sm:max-w-[24rem] md:max-w-[30rem]')
  85. ui.link(target='#about').classes('scroll-indicator')
  86. with ui.row().classes('''
  87. dark-box min-h-screen no-wrap
  88. justify-center items-center flex-col md:flex-row
  89. py-20 px-8 lg:px-16
  90. gap-8 sm:gap-16 md:gap-8 lg:gap-16
  91. '''):
  92. link_target('about')
  93. with ui.column().classes('text-white max-w-4xl'):
  94. heading('Interact with Python through buttons, dialogs, 3D&nbsp;scenes, plots and much more.')
  95. with ui.column().classes('gap-2 bold-links arrow-links text-lg'):
  96. ui.markdown(
  97. 'NiceGUI handles all the web development details for you. '
  98. 'So you can focus on writing Python code. '
  99. 'Anything from short scripts and dashboards to full robotics projects, IoT solutions, '
  100. 'smart home automations and machine learning projects can benefit from having all code in one place.'
  101. )
  102. ui.markdown(
  103. 'Available as '
  104. '[PyPI package](https://pypi.org/project/nicegui/), '
  105. '[Docker image](https://hub.docker.com/r/zauberzeug/nicegui) and on '
  106. '[GitHub](https://github.com/zauberzeug/nicegui).')
  107. example_card.create()
  108. with ui.column().classes('w-full p-8 lg:p-16 bold-links arrow-links max-w-[1600px] mx-auto'):
  109. link_target('features', '-50px')
  110. section_heading('Features', 'Code *nicely*')
  111. with ui.row().classes('w-full text-lg leading-tight grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-8'):
  112. features('swap_horiz', 'Interaction', [
  113. 'buttons, switches, sliders, inputs, ...',
  114. 'notifications, dialogs and menus',
  115. 'keyboard input',
  116. 'on-screen joystick',
  117. ])
  118. features('space_dashboard', 'Layout', [
  119. 'navigation bars, tabs, panels, ...',
  120. 'grouping with rows, columns and cards',
  121. 'HTML and Markdown elements',
  122. 'flex layout by default',
  123. ])
  124. features('insights', 'Visualization', [
  125. 'charts, diagrams and tables',
  126. '3D scenes',
  127. 'progress bars',
  128. 'built-in timer for data refresh',
  129. ])
  130. features('brush', 'Styling', [
  131. 'customizable color themes',
  132. 'custom CSS and classes',
  133. 'modern look with material design',
  134. '[Tailwind CSS](https://tailwindcss.com/) auto-completion',
  135. ])
  136. features('source', 'Coding', [
  137. 'live-cycle events',
  138. 'implicit reload on code change',
  139. 'straight-forward data binding',
  140. 'execute javascript from Python',
  141. ])
  142. features('anchor', 'Foundation', [
  143. 'generic [Vue](https://vuejs.org/) to Python bridge',
  144. 'dynamic GUI through [Quasar](https://quasar.dev/)',
  145. 'content is served with [FastAPI](http://fastapi.tiangolo.com/)',
  146. 'Python 3.7+',
  147. ])
  148. with ui.column().classes('w-full text-lg p-8 lg:p-16 max-w-[1600px] mx-auto'):
  149. link_target('installation', '-50px')
  150. section_heading('Installation', 'Get *started*')
  151. with ui.row().classes('w-full text-lg leading-tight grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-8'):
  152. with ui.column().classes('w-full max-w-md gap-2'):
  153. ui.html('<em>1.</em>').classes('text-3xl font-bold')
  154. ui.markdown('Create __main.py__').classes('text-lg')
  155. with python_window(classes='w-full h-52'):
  156. ui.markdown('''```python\n
  157. from nicegui import ui
  158. ui.label('Hello NiceGUI!')
  159. ui.run()
  160. ```''')
  161. with ui.column().classes('w-full max-w-md gap-2'):
  162. ui.html('<em>2.</em>').classes('text-3xl font-bold')
  163. ui.markdown('Install and launch').classes('text-lg')
  164. with bash_window(classes='w-full h-52'):
  165. ui.markdown('```bash\npip3 install nicegui\npython3 main.py\n```')
  166. with ui.column().classes('w-full max-w-md gap-2'):
  167. ui.html('<em>3.</em>').classes('text-3xl font-bold')
  168. ui.markdown('Enjoy!').classes('text-lg')
  169. with browser_window(classes='w-full h-52'):
  170. ui.label('Hello NiceGUI!')
  171. with ui.expansion('...or use Docker to run your main.py').classes('w-full gap-2 bold-links arrow-links'):
  172. with ui.row().classes('mt-8 w-full justify-center items-center gap-8'):
  173. ui.markdown('''
  174. With our [multi-arch Docker image](https://hub.docker.com/repository/docker/zauberzeug/nicegui)
  175. you can start the server without installing any packages.
  176. The command searches for `main.py` in in your current directory and makes the app available at http://localhost:8888.
  177. ''').classes('max-w-xl')
  178. with bash_window(classes='max-w-lg w-full h-52'):
  179. ui.markdown('```bash\n'
  180. 'docker run -it --rm -p 8888:8080 \\\n -v "$PWD":/app zauberzeug/nicegui\n'
  181. '```')
  182. with ui.column().classes('w-full p-8 lg:p-16 max-w-[1600px] mx-auto'):
  183. link_target('demos', '-50px')
  184. section_heading('Demos', 'Try *this*')
  185. with ui.column().classes('w-full'):
  186. documentation.create_intro()
  187. with ui.column().classes('dark-box p-8 lg:p-16 my-16'):
  188. with ui.column().classes('mx-auto items-center gap-y-8 gap-x-32 lg:flex-row'):
  189. with ui.column().classes('gap-1 max-lg:items-center max-lg:text-center'):
  190. ui.markdown('Browse through plenty of live demos.') \
  191. .classes('text-white text-2xl md:text-3xl font-medium')
  192. ui.html('Fun-Fact: This whole website is also coded with NiceGUI.') \
  193. .classes('text-white text-lg md:text-xl')
  194. ui.link('Documentation', '/documentation') \
  195. .classes('rounded-full mx-auto px-12 py-2 text-white bg-white font-medium text-lg md:text-xl')
  196. with ui.column().classes('w-full p-8 lg:p-16 max-w-[1600px] mx-auto'):
  197. link_target('examples', '-50px')
  198. section_heading('In-depth examples', 'Pick your *solution*')
  199. with ui.row().classes('w-full text-lg leading-tight grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4'):
  200. example_link('Slideshow', 'implements a keyboard-controlled image slideshow')
  201. example_link('Authentication', 'shows how to use sessions to build a login screen')
  202. example_link(
  203. 'Modularization',
  204. 'provides an example of how to modularize your application into multiple files and reuse code')
  205. example_link(
  206. 'FastAPI',
  207. 'illustrates the integration of NiceGUI with an existing FastAPI application')
  208. example_link(
  209. 'Map',
  210. 'demonstrates wrapping the JavaScript library [leaflet](https://leafletjs.com/) to display a map at specific locations')
  211. example_link(
  212. 'AI Interface',
  213. 'utilizes the [replicate](https://replicate.com) library to perform voice-to-text transcription and generate images from prompts with Stable Diffusion')
  214. example_link('3D Scene', 'creates a webGL view and loads an STL mesh illuminated with a spotlight')
  215. example_link('Custom Vue Component', 'shows how to write and integrate a custom Vue component')
  216. example_link('Image Mask Overlay', 'shows how to overlay an image with a mask')
  217. example_link('Infinite Scroll', 'presents an infinitely scrolling image gallery')
  218. example_link('OpenCV Webcam', 'uses OpenCV to capture images from a webcam')
  219. example_link('SVG Clock', 'displays an analog clock by updating an SVG with `ui.timer`')
  220. example_link('Progress', 'demonstrates a progress bar for heavy computations')
  221. example_link('NGINX Subpath', 'shows the setup to serve an app behind a reverse proxy subpath')
  222. example_link('Script Executor', 'executes scripts on selection and displays the output')
  223. example_link('Local File Picker', 'demonstrates a dialog for selecting files locally on the server')
  224. example_link('Search as you type', 'using public API of thecocktaildb.com to search for cocktails')
  225. example_link('Menu and Tabs', 'uses Quasar to create foldable menu and tabs inside a header bar')
  226. example_link('Trello Cards', 'shows Trello-like cards that can be dragged and dropped into columns')
  227. example_link('Slots', 'shows how to use scoped slots to customize Quasar elements')
  228. example_link('Table and slots', 'shows how to use component slots in a table')
  229. example_link('Single Page App', 'navigate without reloading the page')
  230. example_link('Chat App', 'a simple chat app')
  231. with ui.row().classes('bg-primary w-full min-h-screen mt-16'):
  232. link_target('why')
  233. with ui.column().classes('''
  234. max-w-[1600px] m-auto
  235. py-20 px-8 lg:px-16
  236. items-center justify-center no-wrap flex-col md:flex-row gap-16
  237. '''):
  238. with ui.column().classes('gap-8'):
  239. heading('Why?')
  240. with ui.column().classes('gap-2 text-xl text-white bold-links arrow-links'):
  241. ui.markdown(
  242. 'We at '
  243. '[Zauberzeug](https://zauberzeug.com) '
  244. 'like '
  245. '[Streamlit](https://streamlit.io/) '
  246. 'but find it does '
  247. '[too much magic](https://github.com/zauberzeug/nicegui/issues/1#issuecomment-847413651) '
  248. 'when it comes to state handling. '
  249. 'In search for an alternative nice library to write simple graphical user interfaces in Python we discovered '
  250. '[JustPy](https://justpy.io/). '
  251. 'Although we liked the approach, it is too "low-level HTML" for our daily usage. '
  252. 'But it inspired us to use '
  253. '[Vue](https://vuejs.org/) '
  254. 'and '
  255. '[Quasar](https://quasar.dev/) '
  256. 'for the frontend.')
  257. ui.markdown(
  258. 'We have built on top of '
  259. '[FastAPI](https://fastapi.tiangolo.com/), '
  260. 'which itself is based on the ASGI framework '
  261. '[Starlette](https://www.starlette.io/) '
  262. 'and the ASGI webserver '
  263. '[Uvicorn](https://www.uvicorn.org/) '
  264. 'because of their great performance and ease of use.'
  265. )
  266. svg.face().classes('stroke-white shrink-0 w-[200px] md:w-[300px] lg:w-[450px]')
  267. @ui.page('/documentation')
  268. def documentation_page():
  269. add_head_html()
  270. add_header()
  271. side_menu()
  272. ui.add_head_html('<style>html {scroll-behavior: auto;}</style>')
  273. with ui.column().classes('w-full p-8 lg:p-16 max-w-[1250px] mx-auto'):
  274. section_heading('Reference, Demos and more', '*NiceGUI* Documentation')
  275. ui.markdown(
  276. 'This is the documentation for NiceGUI >= 1.0. '
  277. 'Documentation for older versions can be found at [https://0.9.nicegui.io/](https://0.9.nicegui.io/reference).'
  278. ).classes('bold-links arrow-links')
  279. documentation.create_full()
  280. @ui.page('/documentation/{name}')
  281. def documentation_page_more(name: str):
  282. add_head_html()
  283. add_header()
  284. with side_menu() as menu:
  285. ui.markdown(f'[← back](/documentation#{create_anchor_name(name)})').classes('bold-links')
  286. with ui.column().classes('w-full p-8 lg:p-16 max-w-[1250px] mx-auto'):
  287. if not hasattr(ui, name):
  288. name = name.replace('_', '') # NOTE: "AG Grid" leads to anchor name "ag_grid", but class is `ui.aggrid`
  289. section_heading('Documentation', f'ui.*{name}*')
  290. module = importlib.import_module(f'website.more_documentation.{name}_documentation')
  291. element_class = getattr(ui, name)
  292. more = getattr(module, 'more', None)
  293. with menu:
  294. ui.markdown('**Demos**' if more else '**Demo**').classes('mt-4')
  295. element_demo(element_class)(getattr(module, 'main_demo'))
  296. if more:
  297. more()
  298. if inspect.isclass(element_class):
  299. with menu:
  300. ui.markdown('**Reference**').classes('mt-4')
  301. ui.markdown('## Reference').classes('mt-16')
  302. generate_class_doc(element_class)
  303. ui.run(uvicorn_reload_includes='*.py, *.css, *.html')