Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,111 +1,67 @@
|
|
| 1 |
|
| 2 |
import gradio as gr
|
| 3 |
-
import requests
|
| 4 |
import os
|
| 5 |
-
import
|
| 6 |
|
| 7 |
-
|
| 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 |
-
|
| 17 |
"model": GROQ_MODEL,
|
| 18 |
-
"messages": [
|
|
|
|
|
|
|
| 19 |
}
|
| 20 |
-
response = requests.post("https://api.groq.com/openai/v1/chat/completions",
|
| 21 |
return response.json()['choices'][0]['message']['content']
|
| 22 |
|
| 23 |
-
# ------------------
|
| 24 |
-
|
| 25 |
-
"
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 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 |
-
|
|
|
|
| 61 |
else:
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
def
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 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"β
|
| 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}
|
| 131 |
-
|
| 132 |
-
# ------------------
|
| 133 |
-
with gr.Blocks(
|
| 134 |
-
gr.Markdown("
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
gr.
|
| 159 |
-
gr.
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
)
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 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 |
+
|