Mesop Framework Of Python From Google

Introduction

For Python developers, building user interfaces (UIs) for web applications often involves venturing outside their comfort zone. Frameworks like Django and Flask require knowledge of JavaScript, HTML, and CSS. This can add complexity and slow down development, especially for those who are primarily focused on back-end development.

Google's latest open-source tool for designing web interfaces with Python. Mesop like Streamlit or Gradio, allows you to create responsive and appealing user interfaces quickly.

Mesop

What is Mesop?

Mesop is a Python-based UI framework developed by Google. If you're a Python enthusiast or a developer interested in building user interfaces, Mesop is a tool you should explore. This offers a collection of ready-to-use components for common UI elements like buttons, text boxes, and tables. This jumpstarts your development process, allowing you to focus on the unique functionalities of your application.

Why use Mesop?

  1. Open Source: Mesop is open source, meaning you can contribute to its development or customize it to fit your needs.
  2. Simplicity: You won't need to learn a new programming language or complex syntax to start building UIs.
  3. Efficiency: Mesop streamlines the development process, allowing you to focus on creating your application rather than worrying about the intricacies of the underlying code.

Getting started with Mesop
 

Installation

pip install mesop

Example

Save the following code into a file as a sample.py

import mesop as me
@me.page()
def main():
  me.text("This is my first text!")

Run

mesop sample.py

MesopFrameworkCodeOutput

Open the browser using the URL printed in the console (for example, http://localhost:32123) as shown in the above image. If you modify the code (for example, from "This is my first text!" to "Hi"), the Mesop app should be automatically hot-reloaded.

Output

Output

Explanation

In the above code first, it imports the Mesop library as me, defines a page using the @me.page() decorator, and within this page, it includes a single text element that says, "This is my first text!" The main() function, which is decorated by @me.page(), is the entry point for generating the content of the page. The me. text() function call within main() adds the specified text to the web page when it is rendered.

Components in Mesop

Mesop applications are made up of components. This is a tree of components. Let's see different types of components.

  1. Native Components: Native components are the components implemented using Angular/Javascript. Many of these components wrap around Angular Material components.
  2. User-defined Components: The components that you create on your own are called user-defined Components. These are essentially Python functions like the main in the above example.

Mesop provides two major groups of components for building your UIs.

1. High-level Components

These are pre-built components that are designed to perform specific functions, allowing for speedier development. Here are a few examples:

  • Chat: This component enables you to design chat interfaces for real-time communication.
  • Text to Text: This component works with text-based AI models to enable capabilities such as chatbots and text summarization.
  • Text to picture: This component interacts with picture production AI models, allowing users to create images using text prompts.

2. Layout Components

These components provide the foundation for structuring your application's layout. Examples include:

  • Box: This is a versatile container component that can house other components and provide layout attributes such as size and position.
  • Sidenav: This component creates a side navigation menu, often utilized by users.

For more details, check this: Mesop components

Architecture of Mesop

Unlike traditional frameworks that require knowledge of HTML, CSS, and Javascript, Mesop allows developers to write UI entirely in Python. Mesop has a two-part architecture:

  1. Python Server: This server runs on top of Flask, a popular Python web framework. It handles the backend logic of your application, including data processing and communication with databases.
  2. Web Client: This is where things get interesting. While Mesop lets you write Python for the UI, it uses the Angular framework on the client side. Mesop essentially wraps pre-built Angular components, particularly those from Angular Material, to render the UI you define in Python. This gives you the ease of Python development with the rendering power of Angular.

A Simple Chat Bot using Mesop

This code creates a simple Chatbot using the Mesop framework integrating Gemini API.

Code

import google.generativeai as genai

genai.configure(api_key="Your_API_key")
generation_config ={
    "temperature":1,
    "top_p":0.95,
    "top_k":64,
    "max_output_tokens":8192,
    "response_mime_type":"text/plain"
}

model= genai.GenerativeModel(
    model_name="gemini-1.5-flash", 
    generation_config=generation_config,
    system_instruction="You are helpful AI Assistant."
)

import mesop as me
import mesop.labs as mel

@me.page(
  security_policy=me.SecurityPolicy(
    allowed_iframe_parents=["https://google.github.io"]
  ),
  path="/chat",
  title="Chat Bot",
)

def page():
  mel.chat(transform, title="Mesop Demo Chat", bot_user="Mesop Bot")


def transform(input: str, history: list[mel.ChatMessage]):
    response = model.generate_content(input, stream=True)
    for chunk in response:
        yield chunk.text

Output

Mesop Demo

Explanation

Here is a breakdown of the above code for better understanding.

  1. AI Model Setup
    • It imports libraries to interact with Google's AI model.
    • It configures the model's behavior, including how random or likely the responses will be and the maximum length.
    • Finally, it creates an instance of the AI model, specifying the "Gemini-1.5-flash" model (faster for chat) and introducing it as a helpful AI assistant.
  2. Chat Interface with Mesop
    • It imports libraries to build the chat interface using Mesop.
    • The @me.page decorator defines a Mesop page accessible at http://localhost:****/chat. It also sets security restrictions and the page title.
    • The page function uses the mel. chat component from Mesop Labs to create the chat interface. It defines functions for processing user input (transform) and sets the chat title and bot name.
  3. Chat Conversation
    • The transform function is called whenever the user types a message
    • It sends the user's message to the AI model and instructs it to generate a response in chunks (for faster display).
    • The function loops through each chunk of text generated by the AI model and yields it back to the chat interface, displaying the response piece by piece.

Learn More about Mesop

Here are some resources to delve deeper.

Conclusion

As you can see, Mesop makes it simple to develop user interfaces with less code. Its simplicity and flexibility make it an excellent choice for Python developers trying to create beautiful and useful user interfaces.

FAQs
 

1. What is Mesop?

A. Mesop is a Python framework that allows you to develop web applications entirely in Python. Mesop, unlike typical frameworks that need knowledge of HTML, CSS, and Javascript, simplifies things by using Python for both backend logic and user interface (UI).

2. What are some limitations of Mesop?

A. Mesop is still under development. So it has some limitations:

  • Limited Features: Mesop's capabilities and functions may be smaller than those of established frameworks.
  • Limited Community: Because the community around Mesop is still expanding, getting assistance or resources may be more difficult.

3. Do I need to know HTML, CSS, or JS to use Mesop?

A. For basic usage of Mesop and building simple web apps, you don't necessarily need to know HTML, CSS, or JS as it offers a set of UI components.

4. What kind of applications can I build with Mesop?

A. You can build various web or simple chat applications using the Mesop framework. However, it may not currently provide all the vast features and functions as it is still under development.


Similar Articles