google / mesop

Build delightful web apps quickly in Python
https://google.github.io/mesop/
Apache License 2.0
4.05k stars 184 forks source link

Support JupyterLab #354

Open wwwillchen opened 3 weeks ago

wwwillchen commented 3 weeks ago

Source: https://www.reddit.com/r/LocalLLaMA/comments/1d8g5j1/comment/l76huu2/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button

rezpe commented 1 week ago

This would be great if it worked on jupyter. After reviewing the colab folder, it seems we need to implement 2 functions: jupyter_run and jupyter_show. That could be a direction for it:

import threading

from absl import flags  # Keep this for flag handling if needed
from mesop.runtime import enable_debug_mode 
from mesop.server.constants import EDITOR_PACKAGE_PATH, PROD_PACKAGE_PATH
from mesop.server.logging import log_startup
from mesop.server.server import configure_flask_app
from mesop.server.static_file_serving import configure_static_file_serving

def jupyter_run(port: int = 32123, prod_mode: bool = False):
  """Starts the Mesop web server. 
  """

  # Flag handling (adapt as needed for your application)
  if not flags.FLAGS.is_parsed():
    flags.FLAGS.mark_as_parsed() 

  flask_app = configure_flask_app(prod_mode=prod_mode)
  if not prod_mode:
    enable_debug_mode()

  configure_static_file_serving(
      flask_app,
      static_file_runfiles_base=PROD_PACKAGE_PATH 
      if prod_mode
      else EDITOR_PACKAGE_PATH,
  )

  log_startup(port=port)

  def run_flask():
      print(f" * Running Mesop app on http://localhost:{port}/") # Print URL
      flask_app.run(host="::", port=port, use_reloader=False)

import threading
import time
from IPython.display import IFrame, display 

# ... (Your existing Flask app setup code) ...

def jupyter_show(port: int = 32123, path: str = "/", width: str = "100%", height: str = "400"):
    """Displays the Mesop app in a JupyterLab cell output as an IFrame."""

    def show_iframe():
        """Displays the IFrame after a short delay to ensure the server is running."""
        time.sleep(2)  # Adjust delay if needed 
        display(IFrame(src=f"http://localhost:{port}{path}", width=width, height=height))

    # Run the iframe display function in a separate thread
    threading.Thread(target=show_iframe).start()

@wwwillchen , what do you think ?

wwwillchen commented 6 days ago

Thanks, I'll take a look and try your suggestion out.