Untitled

 avatar
unknown
python
a year ago
9.1 kB
7
Indexable
import streamlit as st
import json
from langchain_groq import ChatGroq
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
import ast
# Load your API key (replace with your actual API key)
api_key = "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"

# Initialize ChatGroq
llm = ChatGroq(api_key=api_key)

def generate_lesson_content(subject):
    prompt_template = PromptTemplate(
        input_variables=["subject"],
        template="""
        Create a detailed lesson plan on the subject of {subject}. 
        Provide the following:
        1. Two lesson titles
        2. For each lesson, two page titles
        3. For each page, three subtitles
        4. For each page, a brief content summary (at least 2-3 sentences)

        Format your response EXACTLY as follows, including all brackets and colons:
        {{
        "subject_name": "{subject}",
        "lessons": [
            {{
                "lesson_title": "Lesson 1 Title",
                "pages": [
                    {{
                        "page_title": "Page 1 Title",
                        "page_subtitles": ["Subtitle 1", "Subtitle 2", "Subtitle 3"],
                        "page_content": "Detailed content for Page 1 (2-3 sentences)"
                    }},
                    {{
                        "page_title": "Page 2 Title",
                        "page_subtitles": ["Subtitle 1", "Subtitle 2", "Subtitle 3"],
                        "page_content": "Detailed content for Page 2 (2-3 sentences)"
                    }}
                ]
            }},
            {{
                "lesson_title": "Lesson 2 Title",
                "pages": [
                    {{
                        "page_title": "Page 1 Title",
                        "page_subtitles": ["Subtitle 1", "Subtitle 2", "Subtitle 3"],
                        "page_content": "Detailed content for Page 1 (2-3 sentences)"
                    }},
                    {{
                        "page_title": "Page 2 Title",
                        "page_subtitles": ["Subtitle 1", "Subtitle 2", "Subtitle 3"],
                        "page_content": "Detailed content for Page 2 (2-3 sentences)"
                    }}
                ]
            }}
        ]
        }}

        Ensure the content is informative, relevant to the subject of {subject}, and follows this EXACT JSON structure.
        """
    )
    
    chain = LLMChain(llm=llm, prompt=prompt_template)
    result = chain.invoke({"subject": subject})
    
    return result['text']
def handle_user_input(json_content):
    if not json_content.get("lessons"):
        st.warning("No lessons available. Please generate content first.")
        return json_content

    # Get the current lesson and page
    lesson_titles = [lesson.get("lesson_title", f"Lesson {i+1}") for i, lesson in enumerate(json_content["lessons"])]
    lesson_title = st.selectbox("Select a lesson", lesson_titles)
    
    lesson_index = lesson_titles.index(lesson_title)
    lesson = json_content["lessons"][lesson_index]
    
    if not lesson or not lesson.get("pages"):
        st.warning(f"No pages available for lesson: {lesson_title}")
        return json_content

    page_titles = [page.get("page_title", f"Page {i+1}") for i, page in enumerate(lesson["pages"])]
    page_title = st.selectbox("Select a page", page_titles)
    
    page_index = page_titles.index(page_title)
    page = lesson["pages"][page_index]
    
    if not page:
        st.warning(f"Page not found: {page_title}")
        return json_content

    # Get the current page content and subtitles
    page_content = page.get("page_content", "No content available.")
    page_subtitles = page.get("page_subtitles", [])

    # Display the original content
    st.subheader("Original Content")
    st.write(page_content)

    # Display subtitles
    if page_subtitles:
        st.subheader("Subtitles")
        for subtitle in page_subtitles:
            st.write(f"- {subtitle}")

    # Ask the user what to do with the content
    action = st.selectbox("What would you like to do with the content?", ["Accept", "Expand", "Summarize"])

    # Handle the user's action
    if action == "Accept":
        st.write("Content accepted without changes.")
    elif action == "Expand":
        # Ask the user to select a subtitle to expand
        if page_subtitles:
            subtitle = st.selectbox("Select a subtitle to expand", page_subtitles)
            prompt = PromptTemplate(
                input_variables=["subtitle", "page_title", "content"],
                template="Expand on '{subtitle}' in the context of {page_title}. Original content: {content}"
            )
            chain = LLMChain(llm=llm, prompt=prompt)
            expanded_content = chain.invoke({
                "subtitle": subtitle,
                "page_title": page_title,
                "content": page_content
            })
            st.subheader("Expanded Content")
            st.write(expanded_content['text'])
            page["page_content"] = expanded_content['text']
        else:
            st.warning("No subtitles available for expansion.")
    elif action == "Summarize":
        # Ask the user to select a length for the summary
        summary_length = st.selectbox("Select a summary length", ["Short", "Medium", "Long"])
        prompt = PromptTemplate(
            input_variables=["page_title", "summary_length", "content"],
            template="Summarize the content about {page_title} in a {summary_length} summary. Original content: {content}"
        )
        chain = LLMChain(llm=llm, prompt=prompt)
        summarized_content = chain.invoke({
            "page_title": page_title,
            "summary_length": summary_length.lower(),
            "content": page_content
        })
        st.subheader("Summarized Content")
        st.write(summarized_content['text'])
        page["page_content"] = summarized_content['text']

    return json_content
import re
def preprocess_json(json_string):
    # Remove any leading/trailing whitespace
    json_string = json_string.strip()
    
    # Use ast.literal_eval to safely evaluate the string as a Python literal
    try:
        parsed_data = ast.literal_eval(json_string)
        if isinstance(parsed_data, dict) and "lessons" in parsed_data:
            return parsed_data
        else:
            return {"subject_name": "", "lessons": []}
    except:
        # If ast.literal_eval fails, return an empty structure
        return {"subject_name": "", "lessons": []}

def main():
    st.title("Interactive Lesson Content Editor")

    # Initialize empty JSON content if not exists
    if 'json_content' not in st.session_state:
        st.session_state.json_content = {
            "subject_name": "",
            "lessons": []
        }

    # Input for subject
    subject = st.text_input("Enter the subject for the lesson content:")

    if subject and subject != st.session_state.json_content.get("subject_name", ""):
        with st.spinner("Generating lesson content..."):
            try:
                generated_content = generate_lesson_content(subject)
                # st.write("Debug - Generated Content:", generated_content)  # Debugging step
                if generated_content:
                    # Preprocess the generated content
                    processed_content = preprocess_json(generated_content)
                    # st.write("Debug - Processed Content:", processed_content)  # Debugging step
                    if processed_content:
                        st.session_state.json_content = processed_content
                        st.success("Lesson content generated successfully!")
                    else:
                        st.error("Failed to process the generated content. Please try again.")
                else:
                    st.error("Failed to generate content. Please try again.")
            except Exception as e:
                st.error(f"An error occurred: {str(e)}. Please try again.")

    if st.session_state.json_content.get("lessons"):
        # Handle user input
        updated_content = handle_user_input(st.session_state.json_content)
        if updated_content != st.session_state.json_content:
            st.session_state.json_content = updated_content
            st.success("Content updated successfully!")

        # Option to save the updated JSON
        if st.button("Save Changes"):
            with open(f'{subject.replace(" ", "_").lower()}_lesson_content.json', 'w') as f:
                json.dump(st.session_state.json_content, f, indent=2)
            st.success(f"Changes saved successfully to {subject.replace(' ', '_').lower()}_lesson_content.json!")

    # Debug: Display current JSON content
    if st.checkbox("Show current JSON content"):
        st.json(st.session_state.json_content)

if __name__ == "__main__":
    main()
Editor is loading...
Leave a Comment