iffazainab commited on
Commit
e380563
Β·
verified Β·
1 Parent(s): c57020d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -159
app.py CHANGED
@@ -1,111 +1,67 @@
1
 
2
  import gradio as gr
3
- import requests
4
  import os
5
- import random
6
 
7
- # ------------------ GROQ SETTINGS ------------------
8
- GROQ_API_KEY = os.getenv("GROQ_API_KEY") or "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"
9
  GROQ_MODEL = "llama3-70b-8192"
10
 
 
11
  def query_gpt(prompt):
12
  headers = {
13
  "Authorization": f"Bearer {GROQ_API_KEY}",
14
  "Content-Type": "application/json"
15
  }
16
- data = {
17
  "model": GROQ_MODEL,
18
- "messages": [{"role": "user", "content": prompt}]
 
 
19
  }
20
- response = requests.post("https://api.groq.com/openai/v1/chat/completions", json=data, headers=headers)
21
  return response.json()['choices'][0]['message']['content']
22
 
23
- # ------------------ SYLLABUS DATA ------------------
24
- class_subject_chapters = {
25
- "9": {
26
- "Physics": ["Introduction to Physics", "Kinematics", "Dynamics", "Turning Effect of Forces", "Gravitation", "Work and Energy", "Properties of Matter", "Thermal Properties of Matter", "Transfer of Heat"],
27
- "Biology": ["Introduction to Biology", "Solving a Biological Problem", "Biodiversity", "Cells and Tissues", "Cell Cycle", "Enzymes", "Bioenergetics", "Nutrition", "Transport"],
28
- "Chemistry": ["Fundamentals of Chemistry", "Structure of Atoms", "Periodic Table", "Structure of Molecules", "Physical States of Matter", "Solutions", "Electrochemistry", "Chemical Reactivity"]
29
- },
30
- "10": {
31
- "Physics": ["Simple Harmonic Motion and Waves", "Sound", "Geometrical Optics", "Electrostatics", "Current Electricity", "Electromagnetism", "Basic Electronics", "Information and Communication Technology", "Atomic and Nuclear Physics"],
32
- "Biology": ["Gaseous Exchange", "Homeostasis", "Coordination and Control", "Support and Movement", "Reproduction", "Inheritance", "Man and His Environment", "Biotechnology", "Pharmacology"],
33
- "Chemistry": ["Chemical Equilibrium", "Acids, Bases and Salts", "Organic Chemistry", "Hydrocarbons", "Biochemistry", "Environmental Chemistry", "Chemical Industries"]
34
- },
35
- "11": {
36
- "Physics": ["Measurements", "Vectors and Equilibrium", "Motion and Force", "Work and Energy", "Circular Motion", "Fluid Dynamics", "Oscillations", "Waves", "Physical Optics", "Thermodynamics"],
37
- "Biology": ["Introduction to Biology", "Biological Molecules", "Enzymes", "The Cell", "Cell Cycle", "Variety of Life", "Kingdom Prokaryotae", "Kingdom Protista", "Kingdom Fungi", "Kingdom Plantae", "Kingdom Animalia"],
38
- "Chemistry": ["Basic Concepts", "Experimental Techniques", "Gases", "Liquids and Solids", "Atomic Structure", "Chemical Bonding", "Thermochemistry", "Chemical Equilibrium", "Ionic Equilibrium", "Redox Reactions"]
39
- },
40
- "12": {
41
- "Physics": ["Electrostatics", "Current Electricity", "Electromagnetism", "Electromagnetic Induction", "Alternating Current", "Physics of Solids", "Electronics", "Dawn of Modern Physics", "Atomic Spectra", "Nuclear Physics"],
42
- "Biology": ["Homeostasis", "Support and Movement", "Coordination and Control", "Reproduction", "Growth and Development", "Chromosomes and DNA", "Biotechnology", "Evolution", "Ecosystem", "Some Major Ecosystems"],
43
- "Chemistry": ["Periodic Classification", "Transition Elements", "Chemical Reactivity", "Alcohols and Phenols", "Aldehydes and Ketones", "Carboxylic Acids", "Amines", "Polymers", "Biochemistry", "Environmental Chemistry"]
44
- }
45
- }
46
-
47
- # ------------------ FILE READER ------------------
48
- def read_uploaded_file(file):
49
- if file is None:
50
- return ""
51
- if file.name.endswith(".txt"):
52
- return file.read().decode("utf-8")
53
- elif file.name.endswith(".pdf"):
54
- from PyPDF2 import PdfReader
55
- reader = PdfReader(file)
56
- return "\n".join(page.extract_text() for page in reader.pages if page.extract_text())
57
  elif file.name.endswith(".docx"):
58
- import docx
59
  doc = docx.Document(file)
60
- return "\n".join(p.text for p in doc.paragraphs)
 
61
  else:
62
- return "Unsupported file format. Please upload a PDF, DOCX, or TXT file."
63
-
64
- # ------------------ MAIN BOT FUNCTION ------------------
65
- def tutor_bot(mode, selected_class, selected_subject, selected_chapter, action_type, uploaded_file):
66
- if mode == "File Upload Mode" and uploaded_file is not None:
67
- file_text = read_uploaded_file(uploaded_file)
68
- if not file_text.strip():
69
- return "Could not read text from the uploaded file."
70
- prompt = f"Based on the following content, {action_type.lower()}: \n\n{file_text[:4000]}" # keep it under token limits
71
- gpt_response = query_gpt(prompt)
72
- return gpt_response
73
-
74
- elif mode == "Syllabus Mode":
75
- if not selected_class or not selected_subject or not selected_chapter:
76
- return "Please select class, subject, and chapter."
77
- prompt = f"The user is studying in Class {selected_class}. Give a detailed response for the chapter '{selected_chapter}' in the subject '{selected_subject}'."
78
- if action_type == "Summarize Important Points":
79
- prompt = f"Summarize the key points of the chapter '{selected_chapter}' from Class {selected_class} {selected_subject}."
80
- elif action_type == "Generate MCQs":
81
- prompt = f"Create 5 multiple choice questions (MCQs) with 4 options each for the chapter '{selected_chapter}' from Class {selected_class} {selected_subject}."
82
- elif action_type == "Simplify Concepts":
83
- prompt = f"Explain in very simple terms the important concepts from the chapter '{selected_chapter}' from Class {selected_class} {selected_subject} for a 14-year-old student."
84
-
85
- gpt_response = query_gpt(prompt)
86
- search_query = f"{selected_class} {selected_subject} {selected_chapter} in Urdu"
87
- youtube_link = f"https://www.youtube.com/results?search_query={search_query.replace(' ', '+')}"
88
- gpt_response += f"\n\nπŸŽ₯ **Watch this topic on YouTube:** [Click here]({youtube_link})"
89
- return gpt_response
90
-
91
- return "Invalid mode or missing input."
92
-
93
- # ------------------ HANGMAN GAME FUNCTIONS ------------------
94
  def generate_question_answer(class_level, subject, chapter):
95
  prompt = f"Give one short quiz question and a one-word answer from the chapter '{chapter}' in Class {class_level} {subject}. Format:\nQuestion: ...\nAnswer: ..."
96
  result = query_gpt(prompt)
97
-
98
  lines = result.strip().split("\n")
99
  question = ""
100
  answer = ""
101
-
102
  for line in lines:
103
  if line.lower().startswith("question:"):
104
  question = line.split(":", 1)[1].strip()
105
  elif line.lower().startswith("answer:"):
106
  answer = line.split(":", 1)[1].strip().lower()
107
-
108
- answer = ''.join(filter(str.isalpha, answer)) # remove non-alpha characters
109
  return question, answer
110
 
111
  def start_hangman_game(class_level, subject, chapter):
@@ -116,95 +72,60 @@ def guess_letter(letter, answer, current_display, wrong_guesses_left, guessed_le
116
  letter = letter.lower()
117
  if letter in guessed_letters or len(letter) != 1:
118
  return current_display, f"You already guessed '{letter}' or invalid guess.", wrong_guesses_left, guessed_letters
119
-
120
  guessed_letters.append(letter)
121
  if letter in answer:
122
  new_display = "".join([letter if answer[i] == letter else current_display[i] for i in range(len(answer))])
123
  if "_" not in new_display:
124
  return new_display, "πŸŽ‰ You won!", wrong_guesses_left, guessed_letters
125
- return new_display, f"βœ… Good guess!", wrong_guesses_left, guessed_letters
126
  else:
127
  wrong_guesses_left -= 1
128
  if wrong_guesses_left == 0:
129
- return current_display, f"❌ Game over! The word was '{answer}'.", wrong_guesses_left, guessed_letters
130
- return current_display, f"❌ Wrong guess! {wrong_guesses_left} tries left.", wrong_guesses_left, guessed_letters
131
-
132
- # ------------------ GRADIO UI ------------------
133
- with gr.Blocks(title="AI Textbook Tutor") as app:
134
- gr.Markdown("## πŸ“˜ AI Textbook Tutor\nChoose a mode to either upload your file or select chapter-wise content to get summaries, MCQs, or simplified explanations.")
135
-
136
- mode = gr.Radio(["Syllabus Mode", "File Upload Mode"], label="Select Mode", value="Syllabus Mode")
137
-
138
- with gr.Row():
139
- class_dropdown = gr.Dropdown(label="Class", choices=list(class_subject_chapters.keys()))
140
- subject_dropdown = gr.Dropdown(label="Subject")
141
- chapter_dropdown = gr.Dropdown(label="Chapter")
142
-
143
- file_input = gr.File(label="Upload File (PDF, DOCX, TXT)", file_types=[".pdf", ".docx", ".txt"])
144
- action_dropdown = gr.Radio(["Summarize Important Points", "Generate MCQs", "Simplify Concepts"], label="Task", value="Summarize Important Points")
145
-
146
- run_button = gr.Button("Run Tutor 🧠")
147
- output_box = gr.Markdown()
148
-
149
- def update_subjects(selected_class):
150
- return gr.update(choices=list(class_subject_chapters[selected_class].keys()), value=None)
151
-
152
- def update_chapters(selected_class, selected_subject):
153
- return gr.update(choices=class_subject_chapters[selected_class][selected_subject], value=None)
154
-
155
- def toggle_ui(selected_mode):
156
- if selected_mode == "File Upload Mode":
157
- return (
158
- gr.update(visible=False),
159
- gr.update(visible=False),
160
- gr.update(visible=False),
161
- gr.update(visible=True)
162
- )
163
- else:
164
- return (
165
- gr.update(visible=True),
166
- gr.update(visible=True),
167
- gr.update(visible=True),
168
- gr.update(visible=False)
169
- )
170
-
171
- class_dropdown.change(update_subjects, inputs=class_dropdown, outputs=subject_dropdown)
172
- subject_dropdown.change(update_chapters, inputs=[class_dropdown, subject_dropdown], outputs=chapter_dropdown)
173
- mode.change(toggle_ui, inputs=mode, outputs=[class_dropdown, subject_dropdown, chapter_dropdown, file_input])
174
-
175
- run_button.click(
176
- tutor_bot,
177
- inputs=[mode, class_dropdown, subject_dropdown, chapter_dropdown, action_dropdown, file_input],
178
- outputs=output_box
179
- )
180
-
181
- # ------------------ HANGMAN GAME TAB ------------------
182
- with gr.Tab("🎯 Hangman Game"):
183
- gr.Markdown("### 🎯 Educational Hangman Game Based on Topic")
184
-
185
- hangman_class = gr.Dropdown(label="Class", choices=list(class_subject_chapters.keys()))
186
- hangman_subject = gr.Dropdown(label="Subject")
187
- hangman_chapter = gr.Dropdown(label="Chapter")
188
-
189
- start_btn = gr.Button("Start Game")
190
-
191
- hangman_question = gr.Markdown()
192
- display_word = gr.Textbox(label="Word", interactive=False)
193
- game_msg = gr.Textbox(label="Status", interactive=False)
194
- letter_input = gr.Textbox(label="Enter a letter")
195
- guess_btn = gr.Button("Guess")
196
-
197
- hidden_answer = gr.State()
198
- wrong_guesses = gr.State()
199
- guessed_letters = gr.State()
200
-
201
- hangman_class.change(update_subjects, inputs=hangman_class, outputs=hangman_subject)
202
- hangman_subject.change(update_chapters, inputs=[hangman_class, hangman_subject], outputs=hangman_chapter)
203
-
204
- start_btn.click(start_hangman_game, inputs=[hangman_class, hangman_subject, hangman_chapter], outputs=[hangman_question, display_word, game_msg, wrong_guesses, hidden_answer, guessed_letters])
205
-
206
- guess_btn.click(guess_letter, inputs=[letter_input, hidden_answer, display_word, wrong_guesses, guessed_letters], outputs=[display_word, game_msg, wrong_guesses, guessed_letters])
207
 
208
  app.launch()
209
 
210
 
 
 
1
 
2
  import gradio as gr
 
3
  import os
4
+ import requests
5
 
6
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY") or "YOUR_GROQ_API_KEY_HERE"
 
7
  GROQ_MODEL = "llama3-70b-8192"
8
 
9
+ # ------------------ GPT QUERY FUNCTION ------------------
10
  def query_gpt(prompt):
11
  headers = {
12
  "Authorization": f"Bearer {GROQ_API_KEY}",
13
  "Content-Type": "application/json"
14
  }
15
+ json_data = {
16
  "model": GROQ_MODEL,
17
+ "messages": [
18
+ {"role": "user", "content": prompt}
19
+ ]
20
  }
21
+ response = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=json_data)
22
  return response.json()['choices'][0]['message']['content']
23
 
24
+ # ------------------ TEXTBOOK TUTOR FUNCTION ------------------
25
+ def tutor_from_topic(class_level, subject, chapter, query):
26
+ prompt = f"You are an intelligent and helpful textbook tutor for Pakistani students. Based on Class {class_level}, Subject {subject}, Chapter {chapter}, answer the following: {query}"
27
+ return query_gpt(prompt)
28
+
29
+ # ------------------ FILE HANDLING ------------------
30
+ def extract_text_from_file(file):
31
+ import PyPDF2
32
+ import docx
33
+ text = ""
34
+ if file.name.endswith(".pdf"):
35
+ reader = PyPDF2.PdfReader(file)
36
+ for page in reader.pages:
37
+ text += page.extract_text()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  elif file.name.endswith(".docx"):
 
39
  doc = docx.Document(file)
40
+ for para in doc.paragraphs:
41
+ text += para.text + "\n"
42
  else:
43
+ text = file.read().decode("utf-8")
44
+ return text
45
+
46
+ def tutor_from_file(file, query):
47
+ content = extract_text_from_file(file)
48
+ prompt = f"You are a helpful tutor. Based on the following notes, answer the question: \nNotes:\n{content}\n\nQuestion: {query}"
49
+ return query_gpt(prompt)
50
+
51
+ # ------------------ HANGMAN GAME ------------------
52
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  def generate_question_answer(class_level, subject, chapter):
54
  prompt = f"Give one short quiz question and a one-word answer from the chapter '{chapter}' in Class {class_level} {subject}. Format:\nQuestion: ...\nAnswer: ..."
55
  result = query_gpt(prompt)
 
56
  lines = result.strip().split("\n")
57
  question = ""
58
  answer = ""
 
59
  for line in lines:
60
  if line.lower().startswith("question:"):
61
  question = line.split(":", 1)[1].strip()
62
  elif line.lower().startswith("answer:"):
63
  answer = line.split(":", 1)[1].strip().lower()
64
+ answer = ''.join(filter(str.isalpha, answer))
 
65
  return question, answer
66
 
67
  def start_hangman_game(class_level, subject, chapter):
 
72
  letter = letter.lower()
73
  if letter in guessed_letters or len(letter) != 1:
74
  return current_display, f"You already guessed '{letter}' or invalid guess.", wrong_guesses_left, guessed_letters
 
75
  guessed_letters.append(letter)
76
  if letter in answer:
77
  new_display = "".join([letter if answer[i] == letter else current_display[i] for i in range(len(answer))])
78
  if "_" not in new_display:
79
  return new_display, "πŸŽ‰ You won!", wrong_guesses_left, guessed_letters
80
+ return new_display, f"βœ… Correct guess!", wrong_guesses_left, guessed_letters
81
  else:
82
  wrong_guesses_left -= 1
83
  if wrong_guesses_left == 0:
84
+ return current_display, f"❌ Game over! The correct word was '{answer}'.", wrong_guesses_left, guessed_letters
85
+ return current_display, f"❌ Wrong guess! {wrong_guesses_left} attempts left.", wrong_guesses_left, guessed_letters
86
+
87
+ # ------------------ UI ------------------
88
+ with gr.Blocks() as app:
89
+ gr.Markdown("# πŸ“˜ AI Textbook Tutor + Study Games")
90
+
91
+ with gr.Tabs():
92
+ with gr.TabItem("πŸ“š Ask Your Tutor"):
93
+ with gr.Row():
94
+ class_level = gr.Dropdown(["9", "10", "1st Year", "2nd Year"], label="Class")
95
+ subject = gr.Textbox(label="Subject")
96
+ chapter = gr.Textbox(label="Chapter")
97
+ query = gr.Textbox(label="Your Question")
98
+ ask_btn = gr.Button("Ask")
99
+ answer = gr.Textbox(label="Tutor Answer")
100
+ ask_btn.click(fn=tutor_from_topic, inputs=[class_level, subject, chapter, query], outputs=answer)
101
+
102
+ with gr.TabItem("πŸ“‚ Upload Notes"):
103
+ file_input = gr.File(label="Upload PDF, DOCX, or TXT")
104
+ query2 = gr.Textbox(label="Your Question")
105
+ ask_btn2 = gr.Button("Ask from Notes")
106
+ answer2 = gr.Textbox(label="Tutor Answer")
107
+ ask_btn2.click(fn=tutor_from_file, inputs=[file_input, query2], outputs=answer2)
108
+
109
+ with gr.TabItem("🎯 Hangman Game"):
110
+ with gr.Row():
111
+ class_level_hg = gr.Dropdown(["9", "10", "1st Year", "2nd Year"], label="Class")
112
+ subject_hg = gr.Textbox(label="Subject")
113
+ chapter_hg = gr.Textbox(label="Chapter")
114
+ start_btn = gr.Button("Start Hangman Game")
115
+ question_display = gr.Textbox(label="Question", interactive=False)
116
+ word_display = gr.Textbox(label="Word", interactive=False)
117
+ feedback_display = gr.Textbox(label="Feedback", interactive=False)
118
+ guess_input = gr.Textbox(label="Guess a letter")
119
+ guess_btn = gr.Button("Guess")
120
+
121
+ wrong_guesses_left = gr.State(6)
122
+ correct_answer = gr.State("")
123
+ guessed_letters = gr.State([])
124
+
125
+ start_btn.click(fn=start_hangman_game, inputs=[class_level_hg, subject_hg, chapter_hg], outputs=[question_display, word_display, feedback_display, wrong_guesses_left, correct_answer, guessed_letters])
126
+ guess_btn.click(fn=guess_letter, inputs=[guess_input, correct_answer, word_display, wrong_guesses_left, guessed_letters], outputs=[word_display, feedback_display, wrong_guesses_left, guessed_letters])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
  app.launch()
129
 
130
 
131
+