CoreQuest-AI / app.py
AIbyKaindu's picture
Update app.py
299a13d verified
Raw
History Blame Contribute Delete
10.3 kB
import os
import requests
import streamlit as st
from leaderboard import init_leaderboard, update_leaderboard, show_leaderboard
from ragout import learning_galaxy_answer
# Initialize session
if "xp" not in st.session_state:
st.session_state.xp = 0
st.session_state.level = 1
init_leaderboard()
# Model setup
MODEL_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
def enhanced_query_model(topic):
headers = {"Authorization": f"Bearer {os.environ['HF_Token']}"}
prompt = f"""
You are a physics and mathematics AI tutor.
Given the topic: "{topic}"
1. Provide a simple and clear explanation suitable for high school or college students.
2. Create 3 meaningful practice questions to test their understanding.
3. Suggest an appropriate simulation (either a description or a real link) to help visualize the concept.
Format:
---
Explanation:
...
Questions:
1.
2.
3.
Suggested Simulation:
...
---
"""
payload = {"inputs": prompt}
response = requests.post(MODEL_URL, headers=headers, json=payload)
result = response.json()
try:
if isinstance(result, list) and "generated_text" in result[0]:
return result[0]["generated_text"]
else:
return "⚠️ Unexpected format. Try another topic."
except Exception as e:
return f"⚠️ API Error: {e}"
def find_simulation_link(topic):
sim_map = {
"projectile motion": "https://phet.colorado.edu/sims/html/projectile-motion/latest/projectile-motion_en.html",
"forces": "https://phet.colorado.edu/sims/html/forces-and-motion-basics/latest/forces-and-motion-basics_en.html",
"electric circuits": "https://phet.colorado.edu/sims/html/circuit-construction-kit-dc/latest/circuit-construction-kit-dc_en.html",
"waves": "https://phet.colorado.edu/sims/html/waves-intro/latest/waves-intro_en.html",
"optics": "https://phet.colorado.edu/sims/html/bending-light/latest/bending-light_en.html",
}
for key in sim_map:
if key in topic.lower():
return sim_map[key]
return "https://phet.colorado.edu/en/simulations/category/physics"
def update_xp(points):
st.session_state.xp += points
if st.session_state.xp >= 100:
st.session_state.level += 1
st.session_state.xp = 0
# Streamlit UI
st.set_page_config(page_title="CoreQuest Galaxy 🌌", page_icon="🎯")
st.title("🎯 CoreQuest: Master Physics and Math!")
st.caption("Learn with AI tutors, RAG-enhanced answers, XP leveling, and interactive simulations!")
st.sidebar.header("πŸ† Leaderboard and XP Tracker")
show_leaderboard()
topic = st.text_input("πŸ“˜ Enter a Physics or Math Topic:")
if topic:
with st.spinner("Generating deep explanations and simulations..."):
output = enhanced_query_model(topic)
st.markdown("### πŸ€– AI Response")
st.write(output)
update_xp(10)
st.progress(st.session_state.xp)
st.write(f"πŸ† Level {st.session_state.level} | XP: {st.session_state.xp} Points")
st.markdown("---")
st.subheader("πŸ”­ Simulation Area")
sim_url = find_simulation_link(topic)
st.components.v1.iframe(sim_url, height=500)
st.markdown("---")
st.subheader("πŸ”§ Actions")
if st.button("🌌 Ask Learning Galaxy GPT"):
galaxy_question = st.text_input("Ask a more advanced question:", key="galaxy_input")
if galaxy_question:
with st.spinner("Learning Galaxy thinking..."):
galaxy_answer = learning_galaxy_answer(galaxy_question)
st.success(galaxy_answer)
update_xp(10)
if st.button("🎁 See a Hint"):
st.info("Hint: Sketch diagrams, list formulas, or visualize forces/fields.")
update_xp(3)
if st.button("πŸ”„ Get Another Set of Practice"):
with st.spinner("Loading more questions..."):
new_output = enhanced_query_model(topic)
st.write(new_output)
update_xp(7)
st.markdown("---")
st.subheader("πŸ… Submit Your XP Score")
player_name = st.text_input("πŸ‘€ Enter your name to save XP:")
if st.button("πŸ† Save to Leaderboard"):
update_leaderboard(player_name, st.session_state.xp)
st.success("XP submitted!")
show_leaderboard()
st.markdown("---")
st.caption("Created with ❀️ by CoreQuest Galaxy πŸš€ Powered by Hugging Face + Learning Galaxy ✨")
# --- πŸ”₯ Galactic Upgrades Section ---
st.markdown("## πŸš€ Galactic Upgrades")
st.info("Explore extra challenges and boosters to earn even more XP and become a true CoreQuest legend!")
# --- 🌟 Daily Challenge System ---
import random
daily_challenges = [
"Explain Newton's First Law with a real-world example.",
"Solve a basic derivative problem using the power rule.",
"Describe the concept of kinetic and potential energy.",
"Draw and label a free body diagram for a falling object.",
"Write the difference between electric current and voltage.",
"Sketch how a convex lens focuses light.",
"Describe Special Relativity in one sentence."
]
today_challenge = random.choice(daily_challenges)
st.subheader("🧩 Daily Challenge")
st.success(today_challenge)
if st.button("βœ… Complete Challenge (Claim 15 XP)"):
update_xp(15)
st.balloons()
st.success("You completed today's challenge! 15 XP awarded.")
# --- πŸ›Έ Galactic XP Boosts (Random Event!) ---
boost_active = random.choice([True, False])
if boost_active:
st.markdown("### 🌌 **Galactic XP Boost Active!**")
st.info("All actions give **+5 bonus XP** for the next 10 minutes!")
def update_xp_boost(points):
bonus_points = points + 5
st.session_state.xp += bonus_points
if st.session_state.xp >= 100:
st.balloons()
st.success("🌟 LEVEL UP! Congratulations!")
st.session_state.level += 1
st.session_state.xp = 0
# If you want, replace update_xp(points) with update_xp_boost(points) during boost time
else:
st.caption("β˜„οΈ No Galactic Boost right now. Check back later!")
# --- πŸ† Hall of Fame (Top 3 Players Auto-Show) ---
st.markdown("---")
st.subheader("πŸ† Hall of Fame - Top 3 Explorers")
# Sort and display top 3 leaderboard players
if "leaderboard" in st.session_state and st.session_state.leaderboard:
top_players = st.session_state.leaderboard[:3]
for idx, player in enumerate(top_players, start=1):
st.success(f"πŸ… {idx}. {player['name']} - {player['xp']} XP")
else:
st.info("No top players yet β€” be the first to reach the Hall of Fame!")
st.markdown("---")
st.caption("🌌 CoreQuest Galaxy | Built with ❀️ and Science Magic ✨")
player_name = st.text_input("πŸ‘€ Enter your name to save your progress:")
if st.button("πŸ† Submit to Leaderboard"):
badge = get_badge(st.session_state.xp)
update_leaderboard(player_name, st.session_state.xp, st.session_state.level, badge)
st.success("Your progress is saved into the CoreQuest Galaxy archive!")
show_leaderboard()
if topic:
import json
# --- πŸš€ CoreQuest Flexible AI Response Handler ---
def enhanced_query_model(topic):
headers = {"Authorization": f"Bearer " + os.environ['HF_TOKEN']}
prompt = f"""
You are a physics and mathematics AI tutor.
Given the topic: "{topic}"
1. Provide a simple and clear explanation suitable for high school or college students.
2. Create 3 meaningful practice questions to test their understanding.
3. Suggest an appropriate simulation (either a description or a real link) to help visualize the concept.
Format:
---
Explanation:
...
Questions:
1.
2.
3.
Suggested Simulation:
...
---
"""
payload = {"inputs": prompt}
response = requests.post(MODEL_URL, headers=headers, json=payload)
try:
result = response.json()
# Optional: Log every response for debugging
with open("response_debug.txt", "a") as debug:
debug.write(f"\n\nTOPIC: {topic}\nRESPONSE:\n{json.dumps(result, indent=2)}")
# Smart Flexible Parsing
if isinstance(result, list):
if "generated_text" in result[0]:
return result[0]["generated_text"]
elif "text" in result[0]:
return result[0]["text"]
else:
return str(result[0])
elif isinstance(result, dict):
if "generated_text" in result:
return result["generated_text"]
elif "text" in result:
return result["text"]
elif "error" in result:
return f"⚠️ Error from model: {result['error']}"
else:
return str(result)
else:
return "⚠️ Unexpected response format from the model."
except Exception as e:
return f"⚠️ API Error: {e}"
# --- 🎯 Modular Display of Sections (New functionality) ---
def display_response_parts(raw_output):
st.markdown("### πŸ€– AI Response")
try:
parts = raw_output.split("Questions:")
explanation = parts[0].replace("Explanation:", "").strip()
questions = parts[1].split("Suggested Simulation:")[0].strip() if "Suggested Simulation:" in parts[1] else parts[1].strip()
sim = parts[1].split("Suggested Simulation:")[1].strip() if "Suggested Simulation:" in parts[1] else "N/A"
st.markdown("#### πŸ“˜ Explanation")
st.write(explanation)
st.markdown("#### ❓ Practice Questions")
st.write(questions)
st.markdown("#### πŸ”­ Suggested Simulation")
st.write(sim)
except Exception as e:
st.error(f"⚠️ Error displaying structured output: {e}")
st.write(raw_output)
# --- πŸš€ Bonus Features (Optional Enhancements) ---
def celebrate_big_xp():
"""Special XP celebrations."""
if st.session_state.xp >= 500:
st.balloons()
st.success("πŸ† You’ve earned over 500 XP! You're a CoreQuest Champion!")
def show_fun_facts():
"""Fun facts to engage learners."""
facts = [
"πŸ’‘ Did you know? A day on Venus is longer than a year on Venus!",
"πŸ’‘ In physics, light behaves both as a particle and as a wave!",
"πŸ’‘ There are infinitely many prime numbers β€” proven by Euclid over 2,000 years ago!"
]