sik247 commited on
Commit
50ccedb
·
1 Parent(s): a1d98f3

first push

Browse files
Files changed (1) hide show
  1. app.py +167 -0
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import streamlit as st
4
+ from openai import OpenAI
5
+ from dotenv import load_dotenv
6
+ load_dotenv()
7
+
8
+ # Initialize the OpenAI client using the API key from the environment.
9
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
10
+
11
+ def build_detailed_lecture_script(math_subject: str,
12
+ topic: str,
13
+ difficulty: str,
14
+ speaking_style: str,
15
+ example1: str,
16
+ problem1: str,
17
+ wordproblem: str,
18
+ prev_lecture: str = "",
19
+ max_tokens: int = 5000,
20
+ temperature: float = 0.4) -> str:
21
+ prompt = f"""
22
+ You are a math teacher. Create a comprehensive lecture script for a lesson in "{math_subject}" on the topic "{topic}"
23
+ that transitions seamlessly from start to finish. Deliver the lecture in a {speaking_style} style,
24
+ appropriate for a(n) {difficulty} audience, using English only.
25
+
26
+ The script must be fluent with smooth transitions and detailed explanations of the concepts.
27
+
28
+ 1. **Hook :**
29
+ Provide a concise, empowering introduction that engages the learners and clearly introduces the subject and topic.
30
+ If any relevant material from a previous lecture should be mentioned, briefly reference it here:
31
+ "{prev_lecture}"
32
+
33
+ 2. **Topic Intro :**
34
+ Present a concise background or interesting fact about the topic.
35
+
36
+ 3. **Core Concept Definition:**
37
+ Provide a clear definition of the core concepts. Explain their importance and mention any
38
+ fundamental equations, theorems, or limit definitions that underlie them. Include mathematical equations if necessary.
39
+
40
+ 4. **Detailed Explanation:**
41
+ Offer a detailed, step-by-step explanation of the topic. Incorporate deeper theoretical underpinnings—
42
+ such as derivations from first principles or explanations of common misconceptions and how to avoid them.
43
+
44
+ 5. **Example Problem:**
45
+ Use the following example problem for a thorough walkthrough and please add transitions so the script is fluent:
46
+ "{example1}"
47
+ - Provide a complete, step-by-step solution. Name it as step 1, step 2, etc.
48
+ - Write out the mathematical equations.
49
+ - Reference relevant theorems or limit definitions.
50
+ - Provide common mistakes with transitions and demonstrate how to correct them.
51
+ - Mention alternative methods or shortcuts where relevant with transitions.
52
+ - Clearly summarize the final result.
53
+
54
+ 6. **Problem 1:**
55
+ Use the following second problem:
56
+ "{problem1}"
57
+ Provide a complete, detailed solution, following the same guidelines and use transitions between each step:
58
+ - Step-by-step solution with numbered reasoning. Name it as step 1, step 2, etc.
59
+ - Reference relevant theorems/definitions.
60
+ - Write out the mathematical equations.
61
+ - Summarize the final result.
62
+
63
+ 7. **Word Problem:**
64
+ Use the following word problem:
65
+ "{wordproblem}"
66
+ Solve it thoroughly and use transitions between each step:
67
+ - Walk through each step in detail with numbered guidance. Name it as step 1, step 2, etc.
68
+ - Reference key theorems.
69
+ - Write out the mathematical equations.
70
+ - Using transitions, naturally add common pitfalls and offer alternative approaches.
71
+ - Provide a clear final summary.
72
+
73
+ 8. **Engagement, Reinforcement, and Conclusion:**
74
+ Summarize the key points and offer additional tips or alternative approaches for deeper understanding.
75
+ End with a motivational wrap-up, leaving the audience with a final thought or question.
76
+
77
+ Begin your response now.
78
+ """
79
+ response = client.chat.completions.create(
80
+ model="gpt-4o-2024-08-06",
81
+ messages=[{"role": "user", "content": prompt}],
82
+ max_tokens=max_tokens,
83
+ temperature=temperature
84
+ )
85
+ return response.choices[0].message.content.strip()
86
+
87
+ def add_transitions_and_smooth_script(text: str, max_tokens: int = 5000, temperature: float = 0.4) -> str:
88
+ """
89
+ Processes the lecture script through another LLM call to add smooth transitions between sections.
90
+ IMPORTANT: Retain all the detailed, numbered step-by-step breakdowns exactly as they are.
91
+ Only add transitional sentences to improve the overall flow of the narrative.
92
+ """
93
+ transition_prompt = f"""
94
+ You are an expert editor for academic lecture scripts. Below is a lecture script that contains detailed, numbered step-by-step explanations. Rewrite the script to add smooth, natural transitions between the different sections while preserving all the detailed steps and numbered instructions exactly as they are. Do not remove or alter any of the numbered steps or explanations—only insert transitional sentences and connect the sections into one seamless narrative. Please ensure transitions are added to the common pitfalls, alternative methods, and other sections so that it is fit for a lecture script.
95
+
96
+ Lecture Script:
97
+ {text}
98
+
99
+ Rewritten Lecture Script:
100
+ """
101
+ response = client.chat.completions.create(
102
+ model="gpt-4o-2024-08-06",
103
+ messages=[{"role": "user", "content": transition_prompt}],
104
+ max_tokens=max_tokens,
105
+ temperature=temperature
106
+ )
107
+ return response.choices[0].message.content.strip()
108
+
109
+ def unify_all_math_as_double_dollars(text: str) -> str:
110
+ """
111
+ Ensures that all LaTeX math (whether in $...$, $$...$$, \( ... \), or \[ ... \])
112
+ is converted into double-dollar $$...$$ blocks.
113
+ """
114
+ text = re.sub(r'\$\$(.+?)\$\$', r'__DOUBLE__PLACEHOLDER__\1__DOUBLE__PLACEHOLDER__', text, flags=re.DOTALL)
115
+ text = re.sub(r'\\\[(.+?)\\\]', r'__DBRACK__PLACEHOLDER__\1__DBRACK__PLACEHOLDER__', text, flags=re.DOTALL)
116
+ text = re.sub(r'\\\((.+?)\\\)', r'__DBPAREN__PLACEHOLDER__\1__DBPAREN__PLACEHOLDER__', text, flags=re.DOTALL)
117
+ text = re.sub(r'\$(.+?)\$', r'__SINGLE__PLACEHOLDER__\1__SINGLE__PLACEHOLDER__', text, flags=re.DOTALL)
118
+ text = re.sub(r'__DOUBLE__PLACEHOLDER__(.+?)__DOUBLE__PLACEHOLDER__', r'$$\1$$', text, flags=re.DOTALL)
119
+ text = re.sub(r'__DBRACK__PLACEHOLDER__(.+?)__DBRACK__PLACEHOLDER__', r'$$\1$$', text, flags=re.DOTALL)
120
+ text = re.sub(r'__DBPAREN__PLACEHOLDER__(.+?)__DBPAREN__PLACEHOLDER__', r'$$\1$$', text, flags=re.DOTALL)
121
+ text = re.sub(r'__SINGLE__PLACEHOLDER__(.+?)__SINGLE__PLACEHOLDER__', r'$$\1$$', text, flags=re.DOTALL)
122
+ return text
123
+
124
+ # --- Streamlit App Interface ---
125
+ st.title("Lecture Script Generator")
126
+
127
+ st.sidebar.header("Input Settings")
128
+ math_subject = st.sidebar.text_input("Math Subject", "Algebra 1")
129
+ topic = st.sidebar.text_input("Topic", "Equation and Relations")
130
+ difficulty = st.sidebar.selectbox("Difficulty", ["beginner", "intermediate", "advanced"])
131
+ speaking_style = st.sidebar.text_input("Speaking Style", "engaging and detailed")
132
+ prev_lecture = st.sidebar.text_input("Previous Lecture", "Coordinate Plane")
133
+
134
+ st.sidebar.header("Problems")
135
+ example1 = st.sidebar.text_area("Example Problem",
136
+ "Given the graph with the points A(2,7), B(-1,5), C(-2,-3), and D(5,-8), determine the domain and range of the graph")
137
+ problem1 = st.sidebar.text_area("Problem 1",
138
+ "Solve the equation when the domain is {-2, -1, 0, 4, 7} for 6x - 3y = 21")
139
+ wordproblem = st.sidebar.text_area("Word Problem",
140
+ "On a Friday night, a group of friends decided to go to the movies. Each movie ticket costs $8, and before the show, they all chipped in and bought snacks for $12 total to share. Write an equation that shows how the total cost y depends on the number of tickets x and figure out how much they’ll spend in total if they buy 5 tickets.")
141
+
142
+ # Optionally allow the user to edit the generated prompt.
143
+ edit_prompt = st.sidebar.checkbox("Edit Prompt Manually?")
144
+ if edit_prompt:
145
+ custom_prompt = st.sidebar.text_area("Custom Prompt", value="Enter your custom prompt here...")
146
+ else:
147
+ custom_prompt = None
148
+
149
+ if st.button("Generate Lecture Script"):
150
+ with st.spinner("Generating script..."):
151
+ # If a custom prompt is provided, you could pass it to the function or override the default.
152
+ # In this example, we'll use the default built prompt.
153
+ lecture_script = build_detailed_lecture_script(
154
+ math_subject=math_subject,
155
+ topic=topic,
156
+ difficulty=difficulty,
157
+ speaking_style=speaking_style,
158
+ example1=example1,
159
+ problem1=problem1,
160
+ wordproblem=wordproblem,
161
+ prev_lecture=prev_lecture
162
+ )
163
+ formatted_script = unify_all_math_as_double_dollars(lecture_script)
164
+ final_script = add_transitions_and_smooth_script(formatted_script)
165
+
166
+ st.success("Lecture script generated!")
167
+ st.text_area("Final Lecture Script", final_script, height=600)