ziyadsuper2017's picture
Update app.py
c601604 verified
raw
history blame contribute delete
No virus
5.91 kB
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.
""")