File size: 5,914 Bytes
e2b249d
 
5be0b07
9321000
a374b60
e2b249d
c601604
 
e2b249d
 
c601604
e2b249d
 
 
c601604
 
e2b249d
 
 
 
a374b60
e2b249d
 
c601604
 
708c1b0
c601604
708c1b0
c601604
708c1b0
 
c601604
708c1b0
 
c601604
 
 
 
e2b249d
c601604
708c1b0
e2b249d
c601604
a374b60
9321000
c601604
708c1b0
9321000
708c1b0
 
c601604
 
 
 
 
 
 
 
 
f5eda1f
708c1b0
e2b249d
c601604
9321000
 
8a96712
c601604
 
8a96712
c601604
 
 
9321000
c601604
e2b249d
c601604
5be0b07
 
c601604
 
 
 
 
 
 
 
 
 
708c1b0
e2b249d
708c1b0
 
c601604
9321000
708c1b0
 
c601604
708c1b0
c601604
9321000
708c1b0
 
9321000
 
708c1b0
 
c601604
708c1b0
 
9321000
708c1b0
e2b249d
 
 
c601604
708c1b0
 
 
 
 
 
c601604
708c1b0
 
 
c601604
f5eda1f
 
 
 
 
 
 
 
 
e2b249d
 
5be0b07
 
708c1b0
 
 
 
f5eda1f
c601604
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import streamlit as st
import google.generativeai as genai
import json
import time
from streamlit.components.v1 import html

# Set up Gemini API (using your provided key)
api_key = "AIzaSyBbusXSbq7JTI8Sa7vjGqu-h2zluKhDpX8" 
genai.configure(api_key=api_key)

# Configure the Gemini model (as you specified)
model = genai.GenerativeModel(
    model_name="gemini-1.5-pro-latest",
    generation_config=genai.GenerationConfig(
        temperature=0.2, 
        max_output_tokens=2048 
    )
)

# Streamlit UI
st.set_page_config(page_title="Lecture Notes Mindmap Generator", layout="wide")
st.title("Lecture Notes Mindmap Generator")

# Session State
if "lecture_notes" not in st.session_state:
    st.session_state.lecture_notes = ""
if "current_mindmap" not in st.session_state:
    st.session_state.current_mindmap = None
if "processed_chunks" not in st.session_state:
    st.session_state.processed_chunks = 0

# Lecture Notes Input
lecture_notes = st.text_area("Paste your lecture notes here:", height=300, value=st.session_state.lecture_notes)

# Chunking (with explanation)
def chunk_notes(notes, chunk_size=800): 
    """Breaks down lecture notes into smaller chunks for efficient processing."""
    return [notes[i:i+chunk_size] for i in range(0, len(notes), chunk_size)]

# Mindmap Generation Step (with detailed instructions)
def generate_mindmap_step(notes_chunk, current_mindmap=None):
    prompt = f"""
    Create or extend a hierarchical mindmap structure based on the following lecture notes.
    The structure should be in JSON format, with each node having a 'name' and 'children' array.
    
    Current mindmap (if any):
    {json.dumps(current_mindmap) if current_mindmap else "{}"}
    
    New lecture notes chunk:
    {notes_chunk}

    Specific formatting instructions:
    1. Prioritize a clear, bulletin-style hierarchy (main topics, subtopics, supporting details).
    2. Use concise, informative names for each node to capture the essence of the concept.
    3. Ensure logical grouping: all children of a node should be directly related to its topic.
    4. Aim for 3-5 main topics to maintain a good overview and prevent overwhelming the user.
    5. Strive for consistency in depth and detail across similar levels of the mindmap.
    6. If a concept appears multiple times, find a way to consolidate or cross-reference it.
    7. **Important:** If you're unsure about the structure, err on the side of creating separate nodes for clarity.
    
    Return only the JSON structure of the entire updated mindmap, without any additional text or explanation.
    """

    try:
        response = model.generate_content(prompt)
        response_text = response.text.strip()

        # Robust JSON Parsing
        try:
            return json.loads(response_text)
        except json.JSONDecodeError as e:
            st.error(f"Error parsing JSON: {e}. Raw response: {response_text}")
    except Exception as e:
        st.error(f"An error occurred: {e}")

# Display Mindmap with Bulletin Style
def display_mindmap(data, indent=0):
    if isinstance(data, dict):
        if indent == 0: # Main topic
            st.markdown(f"### {data['name']}")
        else:  # Subtopic or detail
            st.markdown(f"{'  ' * indent}- {data['name']}")

        if 'children' in data and isinstance(data['children'], list):
            for child in data['children']:
                display_mindmap(child, indent + 1)

# Button Actions and UI Logic 
if st.button("Generate/Continue Mindmap"):
    if lecture_notes:
        st.session_state.lecture_notes = lecture_notes
        chunks = chunk_notes(lecture_notes)

        with st.spinner("Generating mindmap... This may take a few minutes."):
            for i in range(st.session_state.processed_chunks, len(chunks)):
                st.text(f"Processing chunk {i+1} of {len(chunks)}...")

                step_mindmap = generate_mindmap_step(chunks[i], st.session_state.current_mindmap)

                if step_mindmap:
                    st.session_state.current_mindmap = step_mindmap
                    st.session_state.processed_chunks = i + 1
                    time.sleep(20)  # Respect API rate limit
                else:
                    st.warning(f"Failed to process chunk {i+1}. You can try continuing from this point.")
                    break

            if st.session_state.current_mindmap:
                st.success(f"Mindmap generated successfully! Processed {st.session_state.processed_chunks} out of {len(chunks)} chunks.")
            else:
                st.error("Failed to generate the mindmap. Please try again.")
    else:
        st.warning("Please enter your lecture notes first.")

# Clear and Restart
if st.button("Clear and Restart"):
    st.session_state.lecture_notes = ""
    st.session_state.current_mindmap = None
    st.session_state.processed_chunks = 0
    st.success("Cleared all data. You can start a new mindmap generation.")

# Display Mindmap 
if st.session_state.current_mindmap:
    st.subheader("Current Mindmap")
    display_mindmap(st.session_state.current_mindmap)

    # Add an option to download the mindmap as JSON
    if st.button("Download Mindmap as JSON"):
        json_string = json.dumps(st.session_state.current_mindmap, indent=2)
        st.download_button(
            label="Click here to download",
            file_name="mindmap.json",
            mime="application/json",
            data=json_string
        )

st.write("""
To use this app:
1. Paste your lecture notes into the text area.
2. Click the "Generate/Continue Mindmap" button to start or continue the process.
3. The mindmap will be generated in chunks, and you can see the progress.
4. If the process is interrupted, you can continue from where it left off.
5. Use the "Clear and Restart" button to start over with new notes.
6. You can download the generated mindmap as a JSON file for future reference.
""")