Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

We should make a python app with a Qt6 GUI that uses a LLM with Llama.cpp for python to…

  1. User

    We should make a python app with a Qt6 GUI that uses a LLM with Llama.cpp for python to take song lyrics as an input and return them highlighted according to the rhymes, similar rhymes go with similar highlight color, the closer the rhyme "not in the sentence but in its sound while said by someone" the closer the color is, this app should have two widgets that split the screen vertically, the widget in the left should be for the input, and the one in the right should be for the output with the lyrics and the highlights, the app should be dark mode by default, there should be tabs at the top of the GUI for function buttons ( load lyrics file (txt), change to light mode "if dark mode is the current theme", export highlighted rhymes "only shows up after the highlights are generated and the output of the LLM is available" ), if there are more functionalities that you think this app is missing just feel free to add them to the code, The name of the developer is HX which is me the one talking to you now, add a tab at the end of the tabs list with the tag "info" to give all the details about the app and the developer and the version, etc. You may also want to include "OpenAI-o1" to the list of developers since you also helped in making the app.

  2. Assistant

    Sure, HX! I'll help you create a Python application with a Qt6 GUI that processes song lyrics, highlights rhymes based on their similarity using an LLM via Llama.cpp for Python, and provides the functionalities you've described. Below is a comprehensive guide along with the complete code to get you started.

    Overview

    • Libraries Used:

      • PyQt6: For creating the GUI.
      • llama_cpp: To interact with the LLM via Llama.cpp (ensure it's installed and properly configured).
      • re: For regular expression operations.
      • json: For handling JSON data.
      • sys: For system-specific parameters and functions.
    • Application Features:

      • Dark Mode: Enabled by default with the option to switch to Light Mode.
      • Two Panels: Left for inputting or loading lyrics, right for displaying highlighted lyrics.
      • Tabs for Functionalities: Load Lyrics, Change Theme, Export Highlights, and Info.
      • Highlighting Rhymes: Rhyming words are highlighted with colors based on rhyme similarity.

    Prerequisites

    1. Install Python 3.7 or higher.

    2. Install Required Python Libraries:

      pip install PyQt6 llama_cpp
      
    3. Llama.cpp Setup:

    4. Prepare the LLM Model:

      • Download a compatible LLM model (e.g., LLaMA) and place it in an accessible directory.

    Complete Code

    Below is the complete Python script for the application. Save this as lyric_rhyme_highlighter.py.

    import sys
    import re
    import json
    from PyQt6.QtWidgets import (
        QApplication, QWidget, QVBoxLayout, QHBoxLayout,
        QPushButton, QTextEdit, QFileDialog, QTabWidget, QLabel, QMessageBox
    )
    from PyQt6.QtGui import QTextCursor, QColor, QTextCharFormat, QFont
    from PyQt6.QtCore import Qt
    from llama_cpp import Llama
    
    # Initialize Llama.cpp
    llm = Llama(model_path="path_to_your_model.bin")  # Replace with your model path
    
    class RhymeHighlighter(QWidget):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("Lyric Rhyme Highlighter")
            self.resize(1000, 600)
            self.current_theme = 'dark'
    
            self.init_ui()
    
        def init_ui(self):
            # Main layout
            main_layout = QVBoxLayout()
            self.setLayout(main_layout)
    
            # Tabs
            self.tabs = QTabWidget()
            self.tabs.setTabPosition(QTabWidget.TabPosition.North)
    
            # Function Tabs
            function_tab_layout = QHBoxLayout()
    
            self.load_button = QPushButton("Load Lyrics File")
            self.load_button.clicked.connect(self.load_lyrics)
            function_tab_layout.addWidget(self.load_button)
    
            self.theme_button = QPushButton("Change to Light Mode")
            self.theme_button.clicked.connect(self.toggle_theme)
            function_tab_layout.addWidget(self.theme_button)
    
            self.export_button = QPushButton("Export Highlighted Rhymes")
            self.export_button.setEnabled(False)
            self.export_button.clicked.connect(self.export_highlights)
            function_tab_layout.addWidget(self.export_button)
    
            self.tabs.addTab(QWidget(), "Functions")
            self.tabs.currentChanged.connect(self.on_tab_change)
    
            # Info Tab
            info_tab = self.create_info_tab()
            self.tabs.addTab(info_tab, "Info")
    
            main_layout.addWidget(self.tabs)
    
            # Splitter Layout
            splitter = QHBoxLayout()
    
            # Input Widget
            self.input_text = QTextEdit()
            self.input_text.setPlaceholderText("Enter or load your song lyrics here...")
            splitter.addWidget(self.input_text)
    
            # Output Widget
            self.output_text = QTextEdit()
            self.output_text.setReadOnly(True)
            splitter.addWidget(self.output_text)
    
            main_layout.addLayout(splitter)
    
            # Apply Dark Theme by Default
            self.apply_dark_theme()
    
        def create_info_tab(self):
            info_widget = QWidget()
            layout = QVBoxLayout()
    
            info_label = QLabel(
                "<h2>Lyric Rhyme Highlighter</h2>"
                "<p>Version: 1.0</p>"
                "<p>Developer: HX</p>"
                "<p>Assisted by: OpenAI-o1</p>"
                "<p>This application highlights rhymes in song lyrics based on their similarity using a Language Model.</p>"
            )
            info_label.setTextFormat(Qt.TextFormat.RichText)
            layout.addWidget(info_label)
            layout.addStretch()
            info_widget.setLayout(layout)
            return info_widget
    
        def load_lyrics(self):
            file_path, _ = QFileDialog.getOpenFileName(self, "Open Lyrics File", "", "Text Files (*.txt)")
            if file_path:
                try:
                    with open(file_path, 'r', encoding='utf-8') as file:
                        lyrics = file.read()
                        self.input_text.setPlainText(lyrics)
                except Exception as e:
                    QMessageBox.critical(self, "Error", f"Failed to load file:\n{e}")
    
        def toggle_theme(self):
            if self.current_theme == 'dark':
                self.apply_light_theme()
                self.current_theme = 'light'
                self.theme_button.setText("Change to Dark Mode")
            else:
                self.apply_dark_theme()
                self.current_theme = 'dark'
                self.theme_button.setText("Change to Light Mode")
    
        def apply_dark_theme(self):
            dark_style = """
                QWidget {
                    background-color: #2e2e2e;
                    color: #f0f0f0;
                }
                QTextEdit {
                    background-color: #3e3e3e;
                    color: #f0f0f0;
                }
                QPushButton {
                    background-color: #5e5e5e;
                    color: #f0f0f0;
                    border: none;
                    padding: 5px;
                }
                QPushButton:hover {
                    background-color: #7e7e7e;
                }
            """
            self.setStyleSheet(dark_style)
    
        def apply_light_theme(self):
            light_style = """
                QWidget {
                    background-color: #f0f0f0;
                    color: #2e2e2e;
                }
                QTextEdit {
                    background-color: #ffffff;
                    color: #2e2e2e;
                }
                QPushButton {
                    background-color: #d0d0d0;
                    color: #2e2e2e;
                    border: none;
                    padding: 5px;
                }
                QPushButton:hover {
                    background-color: #b0b0b0;
                }
            """
            self.setStyleSheet(light_style)
    
        def on_tab_change(self, index):
            if self.tabs.tabText(index) == "Functions":
                return
            # Future functionalities for other tabs can be added here
    
        def export_highlights(self):
            file_path, _ = QFileDialog.getSaveFileName(self, "Save Highlighted Lyrics", "", "Text Files (*.txt)")
            if file_path:
                try:
                    with open(file_path, 'w', encoding='utf-8') as file:
                        file.write(self.output_text.toHtml())
                    QMessageBox.information(self, "Success", "Highlighted lyrics exported successfully.")
                except Exception as e:
                    QMessageBox.critical(self, "Error", f"Failed to save file:\n{e}")
    
        def process_lyrics(self):
            lyrics = self.input_text.toPlainText()
            if not lyrics.strip():
                QMessageBox.warning(self, "Input Needed", "Please enter or load song lyrics first.")
                return
    
            # Use LLM to analyze rhymes
            try:
                prompt = (
                    "Analyze the following song lyrics and identify rhyming words. "
                    "Return a JSON array where each element contains the word and its rhyme group.\n\n"
                    f"Lyrics:\n{lyrics}"
                )
                response = llm(prompt, max_tokens=500)
                rhyme_data = json.loads(response)
                self.highlight_rhymes(rhyme_data, lyrics)
                self.export_button.setEnabled(True)
            except Exception as e:
                QMessageBox.critical(self, "Error", f"Failed to process lyrics:\n{e}")
    
        def highlight_rhymes(self, rhyme_data, lyrics):
            # Clear previous highlights
            self.output_text.clear()
            self.output_text.setPlainText(lyrics)
    
            cursor = self.output_text.textCursor()
            fmt = QTextCharFormat()
    
            # Define a color palette
            color_palette = [
                QColor("#FF5733"), QColor("#33FF57"), QColor("#3357FF"),
                QColor("#F333FF"), QColor("#FF33A8"), QColor("#33FFF6"),
                QColor("#A833FF"), QColor("#FFC133"), QColor("#33FFBD"),
                QColor("#FF3333")
            ]
    
            # Assign colors based on rhyme groups
            group_colors = {}
            for item in rhyme_data:
                group = item.get("rhyme_group")
                word = item.get("word")
                if group not in group_colors:
                    group_colors[group] = color_palette[len(group_colors) % len(color_palette)]
                color = group_colors[group]
    
                # Find all occurrences of the word and apply the color
                for match in re.finditer(rf'\b{re.escape(word)}\b', lyrics, re.IGNORECASE):
                    start, end = match.span()
                    cursor.setPosition(start)
                    cursor.setPosition(end, QTextCursor.MoveMode.KeepAnchor)
                    fmt.setForeground(color)
                    cursor.setCharFormat(fmt)
    
        def keyPressEvent(self, event):
            if event.key() == Qt.Key.Key_Return and event.modifiers() == Qt.KeyboardModifier.ControlModifier:
                # Ctrl + Enter to process lyrics
                self.process_lyrics()
            else:
                super().keyPressEvent(event)
    
    def main():
        app = QApplication(sys.argv)
        window = RhymeHighlighter()
        window.show()
    
        # Connect processing action (e.g., on loading lyrics or via a button)
        # For demonstration, process lyrics when user presses Ctrl+Enter
        window.input_text.setPlaceholderText("Enter lyrics and press Ctrl+Enter to highlight rhymes.")
    
        # Alternatively, add a button to process lyrics
        process_button = QPushButton("Highlight Rhymes")
        process_button.clicked.connect(window.process_lyrics)
        window.layout().insertWidget(0, process_button)
    
        sys.exit(app.exec())
    
    if __name__ == "__main__":
        main()
    

    Explanation of the Code

    1. Imports:

      • PyQt6 Modules: Used for creating the GUI components.
      • llama_cpp: To interact with the LLM for processing lyrics.
      • re & json: For processing text and handling JSON data.
    2. Llama Initialization:

      • Replace "path_to_your_model.bin" with the actual path to your LLM model file.
    3. RhymeHighlighter Class:

      • Initialization: Sets up the main window, themes, and layouts.
      • Tabs:
        • Functions Tab: Contains buttons for loading lyrics, changing theme, and exporting highlights.
        • Info Tab: Provides details about the application and developers.
      • Theme Application: Methods to apply Dark or Light themes.
      • Loading Lyrics: Enables users to load lyrics from a .txt file.
      • Exporting Highlights: Allows users to save the highlighted lyrics as an HTML file for preserving styles.
      • Processing Lyrics:
        • Sends the lyrics to the LLM to analyze and identify rhyming words.
        • Expects a JSON response with rhyme groups and associated words.
        • Highlights the rhyming words in the output text based on their rhyme groups.
      • Highlighting Logic:
        • Assigns different colors to different rhyme groups.
        • Uses regular expressions to find and highlight words.
    4. User Interaction:

      • Users can input lyrics manually or load from a file.
      • Pressing Ctrl + Enter or clicking the Highlight Rhymes button processes the lyrics.
      • Highlights appear in the right panel, and the Export button becomes available.
    5. Main Function:

      • Initializes the application and displays the main window.
      • Adds an additional Highlight Rhymes button for processing.

    Usage Instructions

    1. Run the Application:

      python lyric_rhyme_highlighter.py
      
    2. Load Lyrics:

      • Click on the Load Lyrics File button and select a .txt file containing your song lyrics.
      • Alternatively, manually enter lyrics in the left panel.
    3. Highlight Rhymes:

      • Press Ctrl + Enter or click the Highlight Rhymes button to process and highlight rhymes.
    4. Change Theme:

      • Click on the Change to Light Mode button to switch between Dark and Light themes.
    5. Export Highlights:

      • After highlighting, click on the Export Highlighted Rhymes button to save the output as an HTML file.
    6. View Info:

      • Navigate to the Info tab to view application details.

    Additional Functionalities (Future Enhancements)

    • Real-time Highlighting: Automatically highlight rhymes as the user types.
    • Customization Options: Allow users to choose color palettes or assign specific colors to rhyme groups.
    • Rhyme Scheme Display: Visual representation of the rhyme scheme (e.g., AABB, ABAB).
    • Save/Load Projects: Enable saving and loading of projects with their current states.
    • Integration with Music Platforms: Directly import lyrics from platforms like Genius or Spotify.

    Final Notes

    • LLM Response Format: Ensure that the LLM prompt and expected JSON response align. The current implementation assumes that the LLM returns a JSON array with objects containing word and rhyme_group. You might need to adjust the prompt or parsing logic based on the actual LLM response.

    • Error Handling: The application includes basic error handling. Depending on your use case, you might want to enhance it further.

    • Performance: For large lyrics files, processing might take some time. Consider implementing a loading indicator or running the processing in a separate thread to keep the UI responsive.

    Feel free to customize and expand the application further to suit your specific needs. If you encounter any issues or have additional questions, feel free to ask!