ziyadsuper2017 commited on
Commit
708c1b0
·
verified ·
1 Parent(s): 8a96712

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -62
app.py CHANGED
@@ -19,36 +19,41 @@ model = genai.GenerativeModel(
19
  # Streamlit UI
20
  st.title("Lecture Notes Mindmap Generator")
21
 
 
 
 
 
 
 
 
 
22
  # Text area for input
23
- lecture_notes = st.text_area("Paste your lecture notes here:", height=300)
 
 
 
 
24
 
25
- def generate_mindmap_step(notes, current_mindmap=None):
26
  prompt = f"""
27
- Create or extend a hierarchical mindmap structure from the following lecture notes.
28
  The structure should be in JSON format, with each node having a 'name' and optional 'children' array.
29
 
30
- If a current mindmap is provided, extend it. Otherwise, start a new one.
31
- Focus on creating a comprehensive structure, but limit your response to about 1500 tokens.
32
-
33
- Current mindmap (if any):
34
- {json.dumps(current_mindmap) if current_mindmap else "None"}
35
 
36
- Lecture notes:
37
- {notes}
38
 
39
- Return only the JSON structure, without any additional text or explanation.
40
- If you haven't covered all the content, include a node named "MORE_CONTENT_PENDING" at the end.
41
  """
42
 
43
  try:
44
  response = model.generate_content(prompt)
45
  response_text = response.text.strip()
46
 
47
- # Debug: Print raw response
48
- st.text("Raw API Response:")
49
- st.text(response_text)
50
-
51
- # Attempt to parse JSON, handling potential leading/trailing characters
52
  try:
53
  mindmap_step = json.loads(response_text)
54
  except json.JSONDecodeError:
@@ -61,35 +66,17 @@ def generate_mindmap_step(notes, current_mindmap=None):
61
  else:
62
  raise ValueError("Unable to extract valid JSON from the response")
63
 
64
- return mindmap_step, "MORE_CONTENT_PENDING" in str(mindmap_step)
65
  except Exception as e:
66
  st.error(f"An error occurred while generating the mindmap: {str(e)}")
67
- return None, False
68
-
69
- def merge_mindmaps(base, extension):
70
- if not base:
71
- return extension
72
-
73
- def merge_nodes(node1, node2):
74
- if 'children' not in node1:
75
- node1['children'] = []
76
- if 'children' in node2:
77
- for child in node2['children']:
78
- existing = next((n for n in node1['children'] if n['name'] == child['name']), None)
79
- if existing:
80
- merge_nodes(existing, child)
81
- else:
82
- node1['children'].append(child)
83
-
84
- merge_nodes(base, extension)
85
- return base
86
 
87
  def display_mindmap(data, indent=0):
88
  if isinstance(data, str):
89
  try:
90
  data = json.loads(data)
91
  except json.JSONDecodeError:
92
- st.error("Failed to parse the generated mindmap data. Please try again.")
93
  return
94
 
95
  if isinstance(data, dict):
@@ -101,46 +88,52 @@ def display_mindmap(data, indent=0):
101
  for item in data:
102
  display_mindmap(item, indent)
103
 
104
- # Button to generate mindmap
105
- if st.button("Generate Mindmap"):
106
  if lecture_notes:
 
 
 
107
  with st.spinner("Generating mindmap... This may take a few minutes."):
108
- full_mindmap = None
109
- more_content = True
110
- iteration = 0
111
-
112
- while more_content and iteration < 10: # Limit to 10 iterations as a safeguard
113
- iteration += 1
114
- st.text(f"Processing iteration {iteration}...")
115
 
116
- step_mindmap, more_content = generate_mindmap_step(lecture_notes, full_mindmap)
117
 
118
  if step_mindmap:
119
- full_mindmap = merge_mindmaps(full_mindmap, step_mindmap)
 
120
  time.sleep(20) # Respect API rate limit
121
  else:
122
- st.warning(f"Iteration {iteration} failed to generate a valid mindmap step. Continuing to next iteration.")
123
- continue
124
 
125
- if full_mindmap:
126
- st.session_state.mindmap_data = json.dumps(full_mindmap)
127
- st.success("Mindmap generated successfully!")
128
  else:
129
- st.error("Failed to generate the complete mindmap. Please try again.")
130
  else:
131
  st.warning("Please enter your lecture notes first.")
132
 
133
- # Display the mindmap if data is available
134
- if 'mindmap_data' in st.session_state:
135
- st.subheader("Generated Mindmap")
136
- display_mindmap(st.session_state.mindmap_data)
 
 
 
 
 
 
 
137
 
138
  st.write("""
139
  To use this app:
140
  1. Paste your lecture notes into the text area.
141
- 2. Click the "Generate Mindmap" button.
142
- 3. Wait for the mindmap to be generated (this may take a few minutes).
143
- 4. The generated mindmap will be displayed below.
 
144
 
145
  This app uses Google's Gemini AI to structure your notes into a hierarchical mindmap format.
146
  It processes the notes in multiple steps to handle large inputs and complex structures.
 
19
  # Streamlit UI
20
  st.title("Lecture Notes Mindmap Generator")
21
 
22
+ # Initialize session state variables
23
+ if 'lecture_notes' not in st.session_state:
24
+ st.session_state.lecture_notes = ""
25
+ if 'current_mindmap' not in st.session_state:
26
+ st.session_state.current_mindmap = None
27
+ if 'processed_chunks' not in st.session_state:
28
+ st.session_state.processed_chunks = 0
29
+
30
  # Text area for input
31
+ lecture_notes = st.text_area("Paste your lecture notes here:", height=300, value=st.session_state.lecture_notes)
32
+
33
+ def chunk_notes(notes, chunk_size=500):
34
+ words = notes.split()
35
+ return [' '.join(words[i:i+chunk_size]) for i in range(0, len(words), chunk_size)]
36
 
37
+ def generate_mindmap_step(notes_chunk, current_mindmap=None):
38
  prompt = f"""
39
+ Extend the hierarchical mindmap structure based on the following chunk of lecture notes.
40
  The structure should be in JSON format, with each node having a 'name' and optional 'children' array.
41
 
42
+ Current mindmap:
43
+ {json.dumps(current_mindmap) if current_mindmap else "{}"}
 
 
 
44
 
45
+ New lecture notes chunk:
46
+ {notes_chunk}
47
 
48
+ Return only the JSON structure of the entire updated mindmap, without any additional text or explanation.
49
+ Ensure the JSON is valid and complete.
50
  """
51
 
52
  try:
53
  response = model.generate_content(prompt)
54
  response_text = response.text.strip()
55
 
56
+ # Try to parse JSON, handling potential leading/trailing characters
 
 
 
 
57
  try:
58
  mindmap_step = json.loads(response_text)
59
  except json.JSONDecodeError:
 
66
  else:
67
  raise ValueError("Unable to extract valid JSON from the response")
68
 
69
+ return mindmap_step
70
  except Exception as e:
71
  st.error(f"An error occurred while generating the mindmap: {str(e)}")
72
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
  def display_mindmap(data, indent=0):
75
  if isinstance(data, str):
76
  try:
77
  data = json.loads(data)
78
  except json.JSONDecodeError:
79
+ st.error("Failed to parse the mindmap data. Please try again.")
80
  return
81
 
82
  if isinstance(data, dict):
 
88
  for item in data:
89
  display_mindmap(item, indent)
90
 
91
+ # Button to generate or continue mindmap
92
+ if st.button("Generate/Continue Mindmap"):
93
  if lecture_notes:
94
+ st.session_state.lecture_notes = lecture_notes
95
+ chunks = chunk_notes(lecture_notes)
96
+
97
  with st.spinner("Generating mindmap... This may take a few minutes."):
98
+ for i in range(st.session_state.processed_chunks, len(chunks)):
99
+ st.text(f"Processing chunk {i+1} of {len(chunks)}...")
 
 
 
 
 
100
 
101
+ step_mindmap = generate_mindmap_step(chunks[i], st.session_state.current_mindmap)
102
 
103
  if step_mindmap:
104
+ st.session_state.current_mindmap = step_mindmap
105
+ st.session_state.processed_chunks = i + 1
106
  time.sleep(20) # Respect API rate limit
107
  else:
108
+ st.warning(f"Failed to process chunk {i+1}. You can try continuing from this point.")
109
+ break
110
 
111
+ if st.session_state.current_mindmap:
112
+ st.success(f"Mindmap generated successfully! Processed {st.session_state.processed_chunks} out of {len(chunks)} chunks.")
 
113
  else:
114
+ st.error("Failed to generate the mindmap. Please try again.")
115
  else:
116
  st.warning("Please enter your lecture notes first.")
117
 
118
+ # Button to clear and restart
119
+ if st.button("Clear and Restart"):
120
+ st.session_state.lecture_notes = ""
121
+ st.session_state.current_mindmap = None
122
+ st.session_state.processed_chunks = 0
123
+ st.success("Cleared all data. You can start a new mindmap generation.")
124
+
125
+ # Display the current state of the mindmap
126
+ if st.session_state.current_mindmap:
127
+ st.subheader("Current Mindmap")
128
+ display_mindmap(st.session_state.current_mindmap)
129
 
130
  st.write("""
131
  To use this app:
132
  1. Paste your lecture notes into the text area.
133
+ 2. Click the "Generate/Continue Mindmap" button to start or continue the process.
134
+ 3. The mindmap will be generated in chunks, and you can see the progress.
135
+ 4. If the process is interrupted, you can continue from where it left off.
136
+ 5. Use the "Clear and Restart" button to start over with new notes.
137
 
138
  This app uses Google's Gemini AI to structure your notes into a hierarchical mindmap format.
139
  It processes the notes in multiple steps to handle large inputs and complex structures.