Gemini Pro Text: Flawless Formatting with markdown2

Introduction

Gemini Pro is a powerful generative AI model that can generate human-like text based on a given prompt. However, when rendering the generated text in an HTML template, you may encounter formatting issues due to the presence of formatting symbols (such as asterisks for bold) in the output. In this article, we’ll explore how to use the markdown2 library to convert the generated text and display it correctly in your web application.

Problem Statement

The issue we’re facing is that the generated text from Gemini Pro contains formatting symbols (e.g., asterisks for bold) that are not being rendered correctly in the HTML output. We want to remove these formatting symbols while preserving the content.

This code is for a Django web application that uses Google's Generative AI API (specifically the "gemini-pro" model) to generate content based on a user query and then renders the generated content in an HTML template.

view.py: This is a Django view file where you define functions that handle HTTP requests and return HTTP responses.

from django.shortcuts import render
import google.generativeai as genai
# Create your views here.

GEMINI_API_KEY="AIzaSyB_-S6qNqxTWx0k5rUvb215qaInAF7YSeg"
genai.configure(api_key=GEMINI_API_KEY)


def new(request):
    model = genai.GenerativeModel('gemini-pro')
    response = model.generate_content("What is the meaning of life?")
    text = response.text
    return render(request,"new.html",{'texts': text})

new.html: This is an HTML template file that will be rendered by the render function in the view.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="markdown-content">{{texts}}</div>
</body>
</html>

Output

**Philosophical Perspectives** * **Existentialism:** Meaning is created by individuals through their choices and actions. * **Nihilism:** Life has no inherent meaning or purpose. * **Absurdism:** Life is inherently meaningless, but humans create meaning through the pursuit of purpose and goals. * **Teleology:** Life has a predetermined purpose or goal. * **Hedonism:** Meaning is found in maximizing pleasure and minimizing pain. **Religious and Spiritual Perspectives** * **Theism:** Meaning is derived from a relationship with a divine being. * **Humanism:** Meaning is found in the human experience and values such as empathy, compassion, and justice. * **Buddhism:** Meaning is achieved through the pursuit of enlightenment and the end of suffering. * **Hinduism:** Meaning is found in the fulfillment of one's dharma (duty) and the ultimate liberation from the cycle of rebirth. **Psychological Perspectives** * **Maslow's Hierarchy of Needs:** Meaning is found in satisfying basic needs and then pursuing higher-order needs such as self-actualization. * **Purpose-Driven Life:** Meaning is derived from having a clear sense of purpose and working towards it. * **Flow Theory:** Meaning is experienced when individuals engage in activities that challenge them, provide feedback, and allow for optimal performance. **Personal Experiences** * **Relationships:** Meaning can be found in connecting with others, forming close relationships, and building a sense of belonging. * **Accomplishments:** Meaning can be derived from achieving goals, making a difference in the world, and leaving a legacy. * **Values:** Meaning can be aligned with one's core values and living a life that reflects them. * **Growth and Learning:** Meaning can be found in the pursuit of knowledge, personal development, and expanding one's horizons. **Ultimately, the meaning of life is a deeply personal and subjective matter.** There is no one "correct" answer, and different individuals find meaning in different aspects of their lives. It is an ongoing process of exploration, reflection, and the creation of one's own unique path.

This image and the pasted output are different because, in every rerun, the response from generative AI is different.

Solution. Using markdown2

The markdown2 library is a Python package that converts Markdown text to HTML. By using markdown2, we can easily convert the generated text to HTML, ensuring that formatting symbols are correctly interpreted.

Installation

First, install the markdown2 package using pip:

pip install markdown2

Implementation

Now let’s modify your existing code to use markdown2 for cleaning up the generated text:

from django.shortcuts import render
import google.generativeai as genai
import markdown2
# Create your views here.

GEMINI_API_KEY="AIzaSyB_**********0k5rUvb215qaInAF7YSeg" #Enter your Key as it will not work
genai.configure(api_key=GEMINI_API_KEY)

def new(request):
    model = genai.GenerativeModel('gemini-pro')
    response = model.generate_content("What is the meaning of life?")
    text = markdown2.markdown(response.text)
    return render(request,"new.html",{'texts': text})

Markdown2 is a Python library that converts Markdown-formatted text to HTML. Markdown is a lightweight markup language with plain-text formatting syntax. It allows you to write using an easy-to-read, easy-to-write plain text format, then convert it to structurally valid HTML.

In the provided code, markdown2.markdown(response.text) converts the generated content (presumably in Markdown format) into HTML format before rendering it in the template. This conversion ensures that any Markdown formatting in the generated content is properly displayed in the HTML rendered by the template.

Code Explanation

  • from django.shortcuts import render: This line imports the render function from django.shortcuts module, which is used to render HTML templates with context data.
  • import google.generativeai as genai: This imports the GenerativeAI module from Google's library. The library is referred to as genai in the code.
  • import markdown2: This imports the markdown2 module, which is a Python implementation of the Markdown markup language. Markdown2 is a library that converts Markdown text to HTML.
  • GEMINI_API_KEY="AzaSyB_-S6**********rUvb215qaInAF7YSeg": This line defines a constant GEMINI_API_KEY, which holds the API key required to authenticate with Google's GenerativeAI service.
  • genai.configure(api_key=GEMINI_API_KEY): This line configures the GenerativeAI module with the API key defined earlier.
  • def new(request): This defines a view function named new, which takes a Django HttpRequest object as input.
  • model = genai.GenerativeModel('gemini-pro'): This line creates an instance of a GenerativeModel object using the model named 'gemini-pro'. This model is presumably trained to generate content based on input prompts.
  • response = model.generate_content("What is the meaning of life?"): This line calls the generate_content method of the GenerativeModel object to generate content based on the input prompt "What is the meaning of life?".
  • text = markdown2.markdown(response.text): This line converts the generated content (presumably in Markdown format) to HTML using the markdown2 library. The response.text attribute is assumed to contain Markdown-formatted text.
  • return render(request, "new.html", {'texts': text}): This line renders the 'new.html' template with the generated HTML content (text) passed to it as context data under the key 'texts'.

This code is an HTML template with a section for dynamic content rendering using a template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>{{texts|safe}}</div>
</body>
</html>
  • <div>{{texts|safe}}</div>: This is the dynamic part of the HTML, where content is injected. {{texts|safe}} is a placeholder for dynamic content, likely coming from a backend server through a template engine.
  • {{texts}}: This is a placeholder variable that will be replaced with actual content. It could be a string, HTML markup, or other data.
  • |safe: This Django template filter is used to mark the content as safe HTML. By default, Django's template engine escapes HTML to prevent Cross-Site Scripting (XSS) attacks. However, sometimes you may want to render HTML content that you trust to be safe. In such cases, you can use the safe filter to bypass the automatic HTML escaping and render the content as HTML.

  • Using the safe filter is necessary in this context because the generated content is HTML code that was converted from Markdown. Without the safe filter, the HTML tags in the generated content would be escaped, and the content would be displayed as plain text rather than rendered HTML.

Output

The meaning of life is subjective and varies greatly from person to person. There is no one definitive answer that will apply to everyone. However, some common themes that emerge in discussions about the meaning of life include:

  • To find purpose and fulfillment. Many people believe that the meaning of life is to find a sense of purpose and fulfillment. This can be achieved through work, relationships, hobbies, or other activities that bring meaning and joy to life.
  • To make a positive impact on the world. Others believe that the meaning of life is to make a positive impact on the world. This can be done through acts of kindness, volunteering, or other activities that help to make the world a better place.
  • To connect with others. Some people believe that the meaning of life is to connect with others. This can be done through relationships, friendships, or other social interactions that create a sense of belonging and community.
  • To experience all that life has to offer. Others believe that the meaning of life is simply to experience all that life has to offer. This can include traveling, trying new things, and exploring different cultures.

Ultimately, the meaning of life is something that each person must discover for themselves. There is no right or wrong answer, and the meaning of life can change over time. However, by exploring these different perspectives, we can gain a better understanding of what makes life meaningful and fulfilling.

This image and the pasted output are different because, in every rerun, the response from generative AI is different.

Conclusion

Utilizing the markdown2 library has provided a practical solution to the formatting challenges encountered when integrating Gemini Pro's generated content into HTML templates. By converting the generated text from Markdown to HTML, we ensure proper rendering while preserving the semantic structure of the content. This approach enhances the user experience and facilitates the seamless integration of AI-generated content into web applications. Ultimately, this article has demonstrated how leveraging tools like markdown2 can streamline the process of working with generative AI models, empowering developers to create engaging and visually appealing web experiences.


Recommended Free Ebook
Similar Articles