Skip to content

Code Doumentation Here

Shoun C edited this page Sep 23, 2023 · 1 revision

Code Documentation for generate_presentation Function

This documentation explains the code within the generate_presentation function from the Slide Saver project's feature.py file. The function is responsible for generating PowerPoint presentations based on user input and customizations.

This documentation explains the code within the `generate_presentation` function from the Slide Saver project's `feature.py` file. The function is responsible for generating PowerPoint presentations based on user input and customizations.

```python
import os
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN, MSO_ANCHOR
from datetime import datetime
import streamlit as st

def generate_presentation(lyrics): | Funtion Starts here

** This section imports necessary libraries and modules for working with PowerPoint presentations (pptx);

  • handling colors,
  • text alignment,
  • date/time operations,
  • imports Streamlit for creating the user interface.
    # Font customization options
    st.subheader("Font Customization")
    font_name = st.selectbox("Font:", ["Arial", "Times New Roman", "Verdana", "Helvetica", "Georgia", "Tahoma"])
    font_size = st.slider("Font Size:", min_value=1, max_value=72, value=12)
    font_color = st.color_picker("Font Color:")
  • Here, it sets up the user interface for font customization. Streamlit widgets like subheader, selectbox, slider, and color_picker are used to allow users to choose the font name, font size, and font color.
    # Convert hex color string to RGB int
    font_color_rgb = tuple(int(font_color[i:i+2], 16) for i in (1, 3, 5))
  • This line converts the user-selected hex color string to an RGB color format, which is used later in the code. It is used because the streamlit defaultl sents int as the color_Code and not as RGB > and then font_color_rbg returns the RBG color code to the (pptx).
    # Text formatting options
    st.subheader("Text Formatting")
    bold = st.checkbox("Bold")
    italics = st.checkbox("Italics")
    underline = st.checkbox("Underline")
  • This section sets up the user interface for text formatting. Streamlit checkboxes are used to enable or disable text formatting options like bold, italics, and underline_____.
    # Line spacing customization with predefined options
    st.subheader("Line Spacing")
    line_spacing_options = [1.0, 1.5, 2.0, 2.5, 3.0]
    line_spacing = st.selectbox("Select Line Spacing:", line_spacing_options)
  • Here, it allows users to customize line spacing. Streamlit's select_box widget provides predefined line spacing options.
    # Background color or custom background image
    st.subheader("Background")
    background_options = ["Black", "White", "Custom Image"]
    background_choice = st.radio("Select Background:", background_options)
  • This section sets up the user interface for background customization. Users can choose between a black background, a white background, or a custom image.
    # Custom background image upload
    custom_background = None
    if background_choice == "Custom Image":
        custom_background = st.file_uploader("Upload Custom Background Image", type=["jpg", "jpeg", "png"])
  • If the user selects the "Custom Image" option, they can upload a custom background image using Streamlit's file_uploader widget.

# Generate presentation button
    if st.button("Generate Presentation"):
        # Create a blank PowerPoint presentation
        presentation = Presentation()

        # Split input text into stanzas (assuming stanzas are separated by empty lines)
        stanzas = lyrics.split("\n\n")

        for stanza_text in stanzas:
            # Skip empty stanzas
            if not stanza_text.strip():
                continue

            # Add a blank slide
            slide = presentation.slides.add_slide(presentation.slide_layouts[6])

            # Set background color or custom background image
            if background_choice == "Black":
                background = slide.background
                fill = background.fill
                fill.solid()
                fill.fore_color.rgb = RGBColor(0, 0, 0)  # Black background
            elif background_choice == "White":
                background = slide.background
                fill = background.fill
                fill.solid()
                fill.fore_color.rgb = RGBColor(255, 255, 255)  # White background
            elif background_choice == "Custom Image" and custom_background is not None:
                # Use the uploaded custom background image
                slide.shapes.add_picture(custom_background, Inches(0), Inches(0), Inches(10), Inches(7.5))

            # Add text to the slide
            text_box = slide.shapes.add_textbox(Inches(1), Inches(1), Inches(8), Inches(5))
            text_frame = text_box.text_frame

            # Split the stanza into lines
            lines = stanza_text.split('\n')

            for line in lines:
                # Skip empty lines
                if not line.strip():
                    continue

                # Add a paragraph for each line
                p = text_frame.add_paragraph()
                p.text = line

                # Apply font customization to the entire stanza
                run = p.runs[0]
                run.font.name = font_name
                run.font.size = Pt(font_size)
                run.font.color.rgb = RGBColor(*font_color_rgb)

                # Apply line spacing
                text_frame.space_after = Pt(font_size * line_spacing - font_size)

                # Set vertical alignment to middle
                text_frame.vertical_anchor = MSO_ANCHOR.MIDDLE

                # Apply paragraph alignment (always centered)
                p.alignment = PP_ALIGN.CENTER

                # Apply text formatting
                if bold:
                    run.font.bold = True
                if italics:
                    run.font.italic = True
                if underline:
                    run.font.underline = True
  • This code basically adds up all the user defined settings and writes/creates a presentation only in Blank Presentation Page for every stanza in each slide.
# Get the current date and time
        current_date = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

        # Construct the file name with the current date and .pptx extension
        file_name = f"{current_date}.pptx"

        # Save the PowerPoint file with the current date as the file name
        presentation.save(file_name)

        st.success(f"Presentation generated successfully as {file_name}")
  • In this section the current_date is inputted as the final name as default, once the file is GENERATED it is saved as (temp) and then once it is downloaded it is removed using os_module in further code.
# Ask the user to download the generated presentation with the specified MIME type
        with open(file_name, "rb") as file:
            st.download_button(
                "Download Presentation",
                file.read(),
                key=file_name,
                mime="application/vnd.openxmlformats-officedocument.presentationml.presentation",
            )

        # Delete the temporary file after it's downloaded
        os.remove(file_name)

Certainly! This part of the code is responsible for creating a download button in the Streamlit application, allowing the user to download the generated PowerPoint presentation with a specified MIME (Multipurpose Internet Mail Extensions) type. Let's break down this code segment:

# Ask the user to download the generated presentation with the specified MIME type
with open(file_name, "rb") as file:
    st.download_button(
        "Download Presentation",
        file.read(),
        key=file_name,
        mime="application/vnd.openxmlformats-officedocument.presentationml.presentation",
    )
  • with open(file_name, "rb") as file:: This line opens the generated PowerPoint presentation file (file_name) in binary read mode ("rb") using a context manager. It prepares to read the contents of the file.

  • st.download_button(...): This is a Streamlit function used to create a download button. It takes the following arguments:

    • "Download Presentation": The text that appears on the download button, indicating what the user is downloading.

    • file.read(): This reads the contents of the opened presentation file (file_name) in binary format. The file variable represents the opened file, and read() reads its contents.

    • key=file_name: The key parameter assigns a unique identifier to the download button. In this case, it uses the file_name as the key, ensuring that Streamlit can track this specific download button.

    • mime="application/vnd.openxmlformats-officedocument.presentationml.presentation": This specifies the MIME type of the file being downloaded. In this case, it's set to the MIME type for PowerPoint presentations (PPTX files).

When the user clicks the "Download Presentation" button, Streamlit will trigger a download of the PowerPoint presentation file with the specified MIME type. The file_name ensures that the correct file is downloaded, and the MIME type ensures that the browser knows how to handle the file.

This functionality allows users to conveniently download the generated presentation directly from the Streamlit application for further use or distribution.


Clone this wiki locally