main.py 14 KB

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