HFUsman commited on
Commit
5e95f0c
·
verified ·
1 Parent(s): 1bc0555

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -31
app.py CHANGED
@@ -4,7 +4,6 @@ from groq import Groq
4
  from io import BytesIO
5
  from PyPDF2 import PdfReader
6
  import docx
7
- from docx import Document
8
  from textwrap import wrap
9
  import json
10
 
@@ -54,12 +53,17 @@ def chunk_text(text, max_tokens=2000):
54
  Returns:
55
  list: A list of text chunks.
56
  """
57
- char_limit = max_tokens * 4 # Approximation: 1 token = 4 characters
 
58
  chunks = wrap(text, char_limit)
59
  return chunks
60
 
61
  # Helper Functions
 
62
  def summarize_topic(text, topic):
 
 
 
63
  messages = [
64
  {"role": "system", "content": "Summarize the following lesson content."},
65
  {"role": "user", "content": f"Context: {text}\n\nSummarize the topic: {topic}"},
@@ -67,7 +71,72 @@ def summarize_topic(text, topic):
67
  response = client.chat.completions.create(messages=messages, model="llama-3.3-70b-versatile", stream=False)
68
  return response.choices[0].message.content
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  def generate_assignment(text, topic):
 
 
 
71
  messages = [
72
  {"role": "system", "content": "Generate a conceptual-based assignment from the following lesson content."},
73
  {"role": "user", "content": f"Context: {text}\n\nGenerate a conceptual-based assignment for the topic: {topic}."},
@@ -75,33 +144,23 @@ def generate_assignment(text, topic):
75
  response = client.chat.completions.create(messages=messages, model="llama-3.3-70b-versatile", stream=False)
76
  return response.choices[0].message.content
77
 
78
- # Function to export content to a Word document
79
- def export_to_docx(content, filename):
80
  """
81
- Exports the provided content to a .docx file.
82
- Args:
83
- content (str): The text content to be exported.
84
- filename (str): The desired filename for the exported document.
85
  """
86
- doc = Document()
87
- doc.add_heading("Exported Content", level=1)
88
- doc.add_paragraph(content)
89
- buffer = BytesIO()
90
- doc.save(buffer)
91
- buffer.seek(0)
92
- st.download_button(
93
- label=f"Download {filename}",
94
- data=buffer,
95
- file_name=filename,
96
- mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
97
- )
98
 
99
  # Streamlit app layout
100
  st.title("EduAI Assistant for Teachers")
101
  st.markdown("""
102
  Welcome to the AI-powered teaching assistant!
103
  - Upload your lesson files or input text.
104
- - Ask questions, summarize topics, create quizzes and assignments tailored to different grades.
105
  """)
106
 
107
  # Sidebar: File Upload and Options
@@ -113,12 +172,15 @@ manual_input = st.sidebar.text_area("Or paste lesson text here", height=200)
113
  st.sidebar.header("Select Action")
114
  task = st.sidebar.selectbox("What would you like to do?", [
115
  "Summarize a Topic",
116
- "Generate Conceptual Assignment"
 
 
 
 
117
  ])
118
 
119
  # Main Actions
120
  if manual_input or uploaded_files:
121
- # Combine uploaded files into a single text
122
  combined_text = ""
123
  if uploaded_files:
124
  for file in uploaded_files:
@@ -132,25 +194,55 @@ if manual_input or uploaded_files:
132
  st.stop()
133
 
134
  lesson_text = combined_text if uploaded_files else manual_input
135
- text_chunks = chunk_text(lesson_text) # Split text into manageable chunks
136
 
137
  if task == "Summarize a Topic":
138
  topic = st.text_input("Enter the topic or keywords:")
139
  if st.button("Summarize"):
140
  summaries = [summarize_topic(chunk, topic) for chunk in text_chunks]
141
- final_summary = "\n\n".join(summaries)
142
  st.write("### Summary")
143
- st.write(final_summary)
144
- export_to_docx(final_summary, "Summary.docx")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
  elif task == "Generate Conceptual Assignment":
147
  topic = st.text_input("Enter the topic for assignment generation:")
148
  if st.button("Generate Assignment"):
149
  assignments = [generate_assignment(chunk, topic) for chunk in text_chunks]
150
- final_assignment = "\n\n".join(assignments)
151
  st.write("### Conceptual Assignment")
152
- st.write(final_assignment)
153
- export_to_docx(final_assignment, "Assignment.docx")
154
-
 
 
 
 
 
155
  else:
156
  st.info("Please upload files or enter lesson text to begin.")
 
4
  from io import BytesIO
5
  from PyPDF2 import PdfReader
6
  import docx
 
7
  from textwrap import wrap
8
  import json
9
 
 
53
  Returns:
54
  list: A list of text chunks.
55
  """
56
+ # Approximation: 1 token = 4 characters
57
+ char_limit = max_tokens * 4
58
  chunks = wrap(text, char_limit)
59
  return chunks
60
 
61
  # Helper Functions
62
+
63
  def summarize_topic(text, topic):
64
+ """
65
+ Summarize a specific topic from the given text.
66
+ """
67
  messages = [
68
  {"role": "system", "content": "Summarize the following lesson content."},
69
  {"role": "user", "content": f"Context: {text}\n\nSummarize the topic: {topic}"},
 
71
  response = client.chat.completions.create(messages=messages, model="llama-3.3-70b-versatile", stream=False)
72
  return response.choices[0].message.content
73
 
74
+ def ask_question(text, question):
75
+ """
76
+ Answer a question based on the given text.
77
+ """
78
+ messages = [
79
+ {"role": "system", "content": "You are a helpful teaching assistant."},
80
+ {"role": "user", "content": f"Context: {text}\n\nQuestion: {question}"},
81
+ ]
82
+ response = client.chat.completions.create(messages=messages, model="llama-3.3-70b-versatile", stream=False)
83
+ return response.choices[0].message.content
84
+
85
+ def generate_mcqs(text, num_questions):
86
+ """
87
+ Generate multiple-choice questions from the given text.
88
+ Args:
89
+ text (str): The input text for generating MCQs.
90
+ num_questions (int): The number of MCQs to generate.
91
+ Returns:
92
+ list: A list of MCQs, or an empty list if parsing fails.
93
+ """
94
+ messages = [
95
+ {"role": "system", "content": "Generate multiple-choice questions for a lesson."},
96
+ {"role": "user", "content": f"Context: {text}\n\nGenerate {num_questions} MCQs as a JSON array. Each MCQ should have 'question', 'options', and 'answer' fields."},
97
+ ]
98
+ response = client.chat.completions.create(messages=messages, model="llama-3.3-70b-versatile", stream=False)
99
+
100
+ raw_response = response.choices[0].message.content
101
+ st.write(f"Raw Response: {raw_response}") # Display the raw response in Streamlit for debugging
102
+
103
+ cleaned_response = raw_response.strip()
104
+
105
+ try:
106
+ mcqs = json.loads(cleaned_response)
107
+ if isinstance(mcqs, list):
108
+ formatted_mcqs = []
109
+ for i, mcq in enumerate(mcqs, 1):
110
+ question = mcq['question']
111
+ options = "\n".join([f"{chr(97 + idx)}) {option}" for idx, option in enumerate(mcq['options'])])
112
+ answer = mcq['answer']
113
+ formatted_mcqs.append(f"**Q{i}. {question}**\n{options}\n\nAnswer: {answer}\n")
114
+ return formatted_mcqs
115
+ else:
116
+ st.error("The generated MCQs are not in the expected format.")
117
+ return []
118
+ except json.JSONDecodeError as e:
119
+ st.error(f"Error decoding MCQs: {e}. Raw response: {cleaned_response}")
120
+ return []
121
+ except Exception as e:
122
+ st.error(f"Unexpected error: {e}")
123
+ return []
124
+
125
+ def adapt_lesson_for_grade(text, grade):
126
+ """
127
+ Adapt lesson content for a specific grade level.
128
+ """
129
+ messages = [
130
+ {"role": "system", "content": "Adapt the lesson content for a specific grade."},
131
+ {"role": "user", "content": f"Context: {text}\n\nAdapt this lesson for {grade}."},
132
+ ]
133
+ response = client.chat.completions.create(messages=messages, model="llama-3.3-70b-versatile", stream=False)
134
+ return response.choices[0].message.content
135
+
136
  def generate_assignment(text, topic):
137
+ """
138
+ Generate a conceptual-based assignment from the given lesson or topic.
139
+ """
140
  messages = [
141
  {"role": "system", "content": "Generate a conceptual-based assignment from the following lesson content."},
142
  {"role": "user", "content": f"Context: {text}\n\nGenerate a conceptual-based assignment for the topic: {topic}."},
 
144
  response = client.chat.completions.create(messages=messages, model="llama-3.3-70b-versatile", stream=False)
145
  return response.choices[0].message.content
146
 
147
+ def provide_learning_resources(topic):
 
148
  """
149
+ Generate a list of learning resources for a specific topic.
 
 
 
150
  """
151
+ messages = [
152
+ {"role": "system", "content": "Provide a list of learning resources for a specific topic."},
153
+ {"role": "user", "content": f"Generate a list of books, websites, or courses for learning about: {topic}."},
154
+ ]
155
+ response = client.chat.completions.create(messages=messages, model="llama-3.3-70b-versatile", stream=False)
156
+ return response.choices[0].message.content
 
 
 
 
 
 
157
 
158
  # Streamlit app layout
159
  st.title("EduAI Assistant for Teachers")
160
  st.markdown("""
161
  Welcome to the AI-powered teaching assistant!
162
  - Upload your lesson files or input text.
163
+ - Ask questions, summarize topics, create quizzes, assignments, and access learning resources.
164
  """)
165
 
166
  # Sidebar: File Upload and Options
 
172
  st.sidebar.header("Select Action")
173
  task = st.sidebar.selectbox("What would you like to do?", [
174
  "Summarize a Topic",
175
+ "Ask Questions",
176
+ "Generate MCQs",
177
+ "Adapt Lesson for Grades",
178
+ "Generate Conceptual Assignment",
179
+ "Provide Learning Resources" # New feature added
180
  ])
181
 
182
  # Main Actions
183
  if manual_input or uploaded_files:
 
184
  combined_text = ""
185
  if uploaded_files:
186
  for file in uploaded_files:
 
194
  st.stop()
195
 
196
  lesson_text = combined_text if uploaded_files else manual_input
197
+ text_chunks = chunk_text(lesson_text)
198
 
199
  if task == "Summarize a Topic":
200
  topic = st.text_input("Enter the topic or keywords:")
201
  if st.button("Summarize"):
202
  summaries = [summarize_topic(chunk, topic) for chunk in text_chunks]
 
203
  st.write("### Summary")
204
+ st.write("\n\n".join(summaries))
205
+
206
+ elif task == "Ask Questions":
207
+ question = st.text_input("Enter your question:")
208
+ if st.button("Get Answer"):
209
+ answers = [ask_question(chunk, question) for chunk in text_chunks]
210
+ st.write("### Answer")
211
+ st.write("\n\n".join(answers))
212
+
213
+ elif task == "Generate MCQs":
214
+ num_questions = st.slider("Number of questions to generate:", 1, 10, 5)
215
+ if st.button("Generate MCQs"):
216
+ mcqs = []
217
+ for chunk in text_chunks:
218
+ mcqs.extend(generate_mcqs(chunk, num_questions))
219
+ st.write("### Multiple Choice Questions")
220
+ for i, mcq in enumerate(mcqs, 1):
221
+ st.write(f"**Q{i}. {mcq['question']}**")
222
+ for option in mcq['options']:
223
+ st.write(f"- {option}")
224
+ st.write(f"**Answer:** {mcq['answer']}")
225
+ st.write("---")
226
+
227
+ elif task == "Adapt Lesson for Grades":
228
+ grade = st.selectbox("Select the target grade level:", [f"Grade {i}" for i in range(1, 17)])
229
+ if st.button("Adapt Lesson"):
230
+ adapted_lessons = [adapt_lesson_for_grade(chunk, grade) for chunk in text_chunks]
231
+ st.write(f"### Lesson Adapted for {grade}")
232
+ st.write("\n\n".join(adapted_lessons))
233
 
234
  elif task == "Generate Conceptual Assignment":
235
  topic = st.text_input("Enter the topic for assignment generation:")
236
  if st.button("Generate Assignment"):
237
  assignments = [generate_assignment(chunk, topic) for chunk in text_chunks]
 
238
  st.write("### Conceptual Assignment")
239
+ st.write("\n\n".join(assignments))
240
+
241
+ elif task == "Provide Learning Resources":
242
+ topic = st.text_input("Enter the topic for learning resources:")
243
+ if st.button("Generate Resources"):
244
+ resources = provide_learning_resources(topic)
245
+ st.write("### Learning Resources")
246
+ st.write(resources)
247
  else:
248
  st.info("Please upload files or enter lesson text to begin.")