ciaochris commited on
Commit
bb9f8aa
·
verified ·
1 Parent(s): f9a4b8d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -45
app.py CHANGED
@@ -18,15 +18,20 @@ import os
18
  import json
19
  import logging
20
  from typing import Dict, Any, Tuple
 
 
 
 
 
21
 
22
  # Set up logging
23
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
24
 
25
  # Initialize Groq client
26
  try:
27
- client = Groq(api_key=os.environ["GROQ_API_KEY"])
28
- except KeyError:
29
- logging.error("GROQ_API_KEY not found in environment variables")
30
  raise EnvironmentError("Please set the GROQ_API_KEY environment variable")
31
 
32
  def transcribe_audio(audio):
@@ -52,56 +57,62 @@ def transcribe_audio(audio):
52
  return f"Error in transcription: {str(e)}"
53
 
54
  def generate_tutor_output(subject: str, difficulty: str, student_input: str) -> Dict[str, str]:
55
- # Define enhanced math topics
56
- math_topics = {
57
- "quadratic equation": "solving quadratic equations, including methods like factoring, using the quadratic formula, and completing the square",
58
- "pythagorean theorem": "the Pythagorean theorem, its proof, and applications in geometry and trigonometry",
59
- "calculus": "fundamental concepts of calculus, including limits, derivatives, and integrals",
60
- "linear algebra": "basics of linear algebra, including vectors, matrices, and linear transformations",
61
- "statistics": "key concepts in statistics, such as probability distributions, hypothesis testing, and regression analysis"
 
 
 
 
 
 
 
 
 
 
62
  }
63
 
64
- # Check if it's a math topic and create an enhanced prompt
65
- is_math_topic = subject.lower() == "math"
66
  enhanced_topic = None
67
- for topic, description in math_topics.items():
68
- if topic.lower() in student_input.lower():
69
- enhanced_topic = description
 
 
 
70
  break
71
 
72
- # Create the prompt based on whether it's a math topic or not
73
- if is_math_topic and enhanced_topic:
74
  prompt = f"""
75
- You are an expert math tutor specializing in {enhanced_topic} at the {difficulty} level. The student has asked about: "{student_input}"
76
  Please provide your response in the following format:
77
-
78
  1. Lesson: A comprehensive lesson based on national educational standards on the topic (3-4 paragraphs), including its historical context.
79
-
80
  2. Example: A detailed step-by-step example problem with a full solution. Structure it as follows:
81
  - Start with "Example Problem:" followed by the question.
82
  - Then, list the steps to solve the problem, each on a new line starting with "Step 1:", "Step 2:", etc.
83
  - Finally, provide the answer starting with "Answer:".
84
-
85
  3. Real-World Application: A challenging real-world application of this concept, demonstrating its practical use.
86
-
87
- Format your entire response as a JSON object with keys: "lesson", "example", "real_world_problem".
88
  Ensure that the content for each key is a single string, with line breaks where appropriate.
89
  """
90
  else:
91
  prompt = f"""
92
  You are an expert tutor in {subject} at the {difficulty} level. The student has provided the following input: "{student_input}"
93
  Please generate your response in the following format:
94
-
95
  1. Lesson: Provide a descriptive, long, and engaging lesson on the topic (2-3 paragraphs).
96
-
97
  2. Example: Present an example problem related to the topic. Structure it as follows:
98
  - Start with "Example Problem:" followed by the question.
99
  - Then, list the steps to solve the problem, each on a new line starting with "Step 1:", "Step 2:", etc.
100
  - Finally, provide the answer starting with "Answer:".
101
-
102
  3. Real-World Application: Describe a real-world problem that can be solved using the concepts from the lesson.
103
-
104
- Format your entire response as a JSON object with keys: "lesson", "example", "real_world_problem".
105
  Ensure that the content for each key is a single string, with line breaks where appropriate.
106
  """
107
 
@@ -118,7 +129,7 @@ def generate_tutor_output(subject: str, difficulty: str, student_input: str) ->
118
  }
119
  ],
120
  model="llama3-groq-70b-8192-tool-use-preview",
121
- max_tokens=1000,
122
  )
123
  # Parse the JSON string into a dictionary before returning
124
  return json.loads(completion.choices[0].message.content)
@@ -126,15 +137,16 @@ def generate_tutor_output(subject: str, difficulty: str, student_input: str) ->
126
  logging.error(f"Error generating tutor output: {str(e)}")
127
  return {"error": f"Failed to generate tutor output: {str(e)}"}
128
 
129
- def process_output(output: Dict[str, Any]) -> Tuple[str, str, str]:
130
  try:
131
- lesson = str(output.get("lesson", "No lesson available"))
132
- example = str(output.get("example", "No example available"))
133
- real_world = str(output.get("real_world_problem", "No real-world problem available"))
134
- return lesson, example, real_world
 
135
  except Exception as e:
136
  logging.error(f"Error processing output: {str(e)}")
137
- return str(e), "", ""
138
 
139
  def create_interface() -> gr.Blocks:
140
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
@@ -164,16 +176,17 @@ def create_interface() -> gr.Blocks:
164
 
165
  with gr.Column(scale=3):
166
  transcription_output = gr.Textbox(label="Transcribed Audio (if provided)")
167
- lesson_output = gr.Markdown(label="Lesson")
168
- example_output = gr.Markdown(label="Example")
169
- real_world_output = gr.Markdown(label="Real-World Application")
 
170
 
171
  gr.Markdown("""
172
  ### How to Use
173
  1. Select a subject from the dropdown.
174
  2. Choose your difficulty level.
175
  3. Enter the topic or question you'd like to explore, or use the microphone to speak your question.
176
- 4. Click 'Teach Me' to receive a personalized lesson, example, and real-world application.
177
  5. Review the AI-generated content to enhance your learning.
178
  6. Use the 'Clear' button to reset all fields and start a new query.
179
  7. Feel free to ask follow-up questions or explore new topics!
@@ -201,25 +214,25 @@ def create_interface() -> gr.Blocks:
201
  logging.info(f"Processing input: subject={subject}, difficulty={difficulty}, student_input={student_input}")
202
 
203
  tutor_output = generate_tutor_output(subject, difficulty, student_input)
204
- lesson, example, real_world = process_output(tutor_output)
205
- return transcribed_text, lesson, example, real_world
206
  except Exception as e:
207
  logging.error(f"Error in process_input: {str(e)}")
208
- return str(e), "Error generating lesson", "Error generating example", "Error generating real-world problem"
209
 
210
  def clear_outputs():
211
- return [""] * 4 # Clear all four output fields
212
 
213
  submit_button.click(
214
  fn=process_input,
215
  inputs=[subject, difficulty, student_input, audio_input],
216
- outputs=[transcription_output, lesson_output, example_output, real_world_output]
217
  )
218
 
219
  clear_button.click(
220
  fn=clear_outputs,
221
  inputs=[],
222
- outputs=[transcription_output, lesson_output, example_output, real_world_output]
223
  )
224
 
225
  return demo
 
18
  import json
19
  import logging
20
  from typing import Dict, Any, Tuple
21
+ from dotenv import load_dotenv
22
+ import markdown2
23
+
24
+ # Load environment variables
25
+ load_dotenv()
26
 
27
  # Set up logging
28
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
29
 
30
  # Initialize Groq client
31
  try:
32
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
33
+ except Exception as e:
34
+ logging.error(f"Error initializing Groq client: {str(e)}")
35
  raise EnvironmentError("Please set the GROQ_API_KEY environment variable")
36
 
37
  def transcribe_audio(audio):
 
57
  return f"Error in transcription: {str(e)}"
58
 
59
  def generate_tutor_output(subject: str, difficulty: str, student_input: str) -> Dict[str, str]:
60
+ # Define enhanced topics for all subjects
61
+ topics = {
62
+ "math": {
63
+ "quadratic equation": "solving quadratic equations, including methods like factoring, using the quadratic formula, and completing the square",
64
+ "pythagorean theorem": "the Pythagorean theorem, its proof, and applications in geometry and trigonometry",
65
+ "calculus": "fundamental concepts of calculus, including limits, derivatives, and integrals",
66
+ "linear algebra": "basics of linear algebra, including vectors, matrices, and linear transformations",
67
+ "statistics": "key concepts in statistics, such as probability distributions, hypothesis testing, and regression analysis"
68
+ },
69
+ "science": {
70
+ "photosynthesis": "the process of photosynthesis in plants, including light-dependent and light-independent reactions",
71
+ "newton's laws": "Newton's laws of motion and their applications in classical mechanics",
72
+ "periodic table": "the structure and organization of the periodic table of elements",
73
+ "dna replication": "the process of DNA replication and its importance in cell division",
74
+ "climate change": "the causes and effects of climate change, including global warming and its impact on ecosystems"
75
+ },
76
+ # Add more subjects and topics as needed
77
  }
78
 
79
+ # Check if it's a specific topic and create an enhanced prompt
 
80
  enhanced_topic = None
81
+ for subject_topics in topics.values():
82
+ for topic, description in subject_topics.items():
83
+ if topic.lower() in student_input.lower():
84
+ enhanced_topic = description
85
+ break
86
+ if enhanced_topic:
87
  break
88
 
89
+ # Create the prompt based on whether it's a specific topic or not
90
+ if enhanced_topic:
91
  prompt = f"""
92
+ You are an expert tutor specializing in {enhanced_topic} at the {difficulty} level. The student has asked about: "{student_input}"
93
  Please provide your response in the following format:
 
94
  1. Lesson: A comprehensive lesson based on national educational standards on the topic (3-4 paragraphs), including its historical context.
 
95
  2. Example: A detailed step-by-step example problem with a full solution. Structure it as follows:
96
  - Start with "Example Problem:" followed by the question.
97
  - Then, list the steps to solve the problem, each on a new line starting with "Step 1:", "Step 2:", etc.
98
  - Finally, provide the answer starting with "Answer:".
 
99
  3. Real-World Application: A challenging real-world application of this concept, demonstrating its practical use.
100
+ 4. Quiz: Create a short quiz (3 multiple-choice questions) to test the student's understanding.
101
+ Format your entire response as a JSON object with keys: "lesson", "example", "real_world_problem", "quiz".
102
  Ensure that the content for each key is a single string, with line breaks where appropriate.
103
  """
104
  else:
105
  prompt = f"""
106
  You are an expert tutor in {subject} at the {difficulty} level. The student has provided the following input: "{student_input}"
107
  Please generate your response in the following format:
 
108
  1. Lesson: Provide a descriptive, long, and engaging lesson on the topic (2-3 paragraphs).
 
109
  2. Example: Present an example problem related to the topic. Structure it as follows:
110
  - Start with "Example Problem:" followed by the question.
111
  - Then, list the steps to solve the problem, each on a new line starting with "Step 1:", "Step 2:", etc.
112
  - Finally, provide the answer starting with "Answer:".
 
113
  3. Real-World Application: Describe a real-world problem that can be solved using the concepts from the lesson.
114
+ 4. Quiz: Create a short quiz (3 multiple-choice questions) to test the student's understanding.
115
+ Format your entire response as a JSON object with keys: "lesson", "example", "real_world_problem", "quiz".
116
  Ensure that the content for each key is a single string, with line breaks where appropriate.
117
  """
118
 
 
129
  }
130
  ],
131
  model="llama3-groq-70b-8192-tool-use-preview",
132
+ max_tokens=2000,
133
  )
134
  # Parse the JSON string into a dictionary before returning
135
  return json.loads(completion.choices[0].message.content)
 
137
  logging.error(f"Error generating tutor output: {str(e)}")
138
  return {"error": f"Failed to generate tutor output: {str(e)}"}
139
 
140
+ def process_output(output: Dict[str, Any]) -> Tuple[str, str, str, str]:
141
  try:
142
+ lesson = markdown2.markdown(str(output.get("lesson", "No lesson available")))
143
+ example = markdown2.markdown(str(output.get("example", "No example available")))
144
+ real_world = markdown2.markdown(str(output.get("real_world_problem", "No real-world problem available")))
145
+ quiz = markdown2.markdown(str(output.get("quiz", "No quiz available")))
146
+ return lesson, example, real_world, quiz
147
  except Exception as e:
148
  logging.error(f"Error processing output: {str(e)}")
149
+ return str(e), "", "", ""
150
 
151
  def create_interface() -> gr.Blocks:
152
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
 
176
 
177
  with gr.Column(scale=3):
178
  transcription_output = gr.Textbox(label="Transcribed Audio (if provided)")
179
+ lesson_output = gr.HTML(label="Lesson")
180
+ example_output = gr.HTML(label="Example")
181
+ real_world_output = gr.HTML(label="Real-World Application")
182
+ quiz_output = gr.HTML(label="Quiz")
183
 
184
  gr.Markdown("""
185
  ### How to Use
186
  1. Select a subject from the dropdown.
187
  2. Choose your difficulty level.
188
  3. Enter the topic or question you'd like to explore, or use the microphone to speak your question.
189
+ 4. Click 'Teach Me' to receive a personalized lesson, example, real-world application, and quiz.
190
  5. Review the AI-generated content to enhance your learning.
191
  6. Use the 'Clear' button to reset all fields and start a new query.
192
  7. Feel free to ask follow-up questions or explore new topics!
 
214
  logging.info(f"Processing input: subject={subject}, difficulty={difficulty}, student_input={student_input}")
215
 
216
  tutor_output = generate_tutor_output(subject, difficulty, student_input)
217
+ lesson, example, real_world, quiz = process_output(tutor_output)
218
+ return transcribed_text, lesson, example, real_world, quiz
219
  except Exception as e:
220
  logging.error(f"Error in process_input: {str(e)}")
221
+ return str(e), "Error generating lesson", "Error generating example", "Error generating real-world problem", "Error generating quiz"
222
 
223
  def clear_outputs():
224
+ return [""] * 5 # Clear all five output fields
225
 
226
  submit_button.click(
227
  fn=process_input,
228
  inputs=[subject, difficulty, student_input, audio_input],
229
+ outputs=[transcription_output, lesson_output, example_output, real_world_output, quiz_output]
230
  )
231
 
232
  clear_button.click(
233
  fn=clear_outputs,
234
  inputs=[],
235
+ outputs=[transcription_output, lesson_output, example_output, real_world_output, quiz_output]
236
  )
237
 
238
  return demo