File size: 4,858 Bytes
ad0d754
bc20a41
ebbd85b
ad0d754
 
ebbd85b
ad0d754
35fc402
ad0d754
 
8ca2f9f
ad0d754
 
 
 
 
 
35fc402
ad0d754
 
 
35fc402
8ca2f9f
ad0d754
 
 
8ca2f9f
ad0d754
ebbd85b
ad0d754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebbd85b
ad0d754
 
 
8ca2f9f
ad0d754
 
 
 
 
 
8ca2f9f
ad0d754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ca2f9f
ad0d754
8ca2f9f
ad0d754
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# app.py
import streamlit as st
import requests
from datetime import datetime
from fpdf import FPDF

# Replace with your actual OpenRouter or Hugging Face endpoint and key
API_URL = "https://openrouter.ai/api/v1/chat/completions"
API_KEY = "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"
MODEL = "mistralai/mistral-7b-instruct"

# ------------------------- AI QUERY FUNCTION -------------------------
def query_ai(prompt):
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    data = {
        "model": MODEL,
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.7
    }
    try:
        response = requests.post(API_URL, headers=headers, json=data)
        response.raise_for_status()
        return response.json()['choices'][0]['message']['content']
    except Exception as e:
        return f"❌ API Error: {str(e)}"

# ---------------------- EXPERIMENT TEMPLATES ------------------------
experiments = {
    "Vinegar + Baking Soda": {
        "hypothesis": "Mixing vinegar and baking soda will produce bubbles due to a chemical reaction.",
        "concept": "Acid-base reaction producing carbon dioxide."
    },
    "Floating Egg": {
        "hypothesis": "An egg will float in salt water but sink in plain water.",
        "concept": "Density difference between saltwater and freshwater."
    },
    "Lemon Battery": {
        "hypothesis": "A lemon can produce electricity to power a small LED.",
        "concept": "Chemical energy conversion to electrical energy."
    }
}

# -------------------------- PDF REPORT ------------------------------
def generate_pdf_report(exp_name, hypo, explanation, result):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=12)
    pdf.cell(200, 10, txt="Science Lab Report", ln=True, align='C')
    pdf.ln(10)
    pdf.multi_cell(0, 10, txt=f"Experiment: {exp_name}\n\nHypothesis: {hypo}\n\nAI Explanation: {explanation}\n\nExpected Result: {result}")
    filename = f"report_{datetime.now().strftime('%Y%m%d%H%M%S')}.pdf"
    pdf.output(filename)
    return filename

# --------------------------- STREAMLIT UI ---------------------------
st.set_page_config(page_title="πŸ§ͺ Science Lab Assistant", layout="centered")
st.title("πŸ§ͺ Science Lab Assistant")
st.markdown("Helping students understand, hypothesize, and explain science experiments.")

exp_choice = st.selectbox("Choose an experiment or enter your own:", list(experiments.keys()) + ["Custom Experiment"])

if exp_choice != "Custom Experiment":
    default_hypo = experiments[exp_choice]["hypothesis"]
    concept = experiments[exp_choice]["concept"]
else:
    default_hypo = ""
    concept = ""

with st.form("experiment_form"):
    exp_name = st.text_input("Experiment Name", value=exp_choice)
    hypo = st.text_area("Your Hypothesis", value=default_hypo)
    submit = st.form_submit_button("πŸ” Explain Experiment")

if submit:
    with st.spinner("Thinking like a scientist..."):
        prompt = f"Explain the following school science experiment clearly for a student.\n\nExperiment: {exp_name}\nHypothesis: {hypo}\nExplain what happens, why it happens, and what the expected result is."
        explanation = query_ai(prompt)

    st.success("AI Explanation")
    st.write(explanation)

    # Generate expected result
    with st.spinner("Predicting result..."):
        result = query_ai(f"What is the expected result of this experiment: {exp_name}?")
    st.info(f"**Expected Result:** {result}")

    # Conceptual Science
    if concept:
        st.caption(f"🧠 Science Concept: {concept}")

    # PDF Download
    pdf_file = generate_pdf_report(exp_name, hypo, explanation, result)
    with open(pdf_file, "rb") as file:
        st.download_button("πŸ“„ Download Lab Report (PDF)", file, file_name=pdf_file)

# --------------------- OPTIONAL FILE UPLOAD -------------------------
st.markdown("---")
st.subheader("πŸ“Έ Upload Your Lab Report Image (optional)")
uploaded_file = st.file_uploader("Upload an image for feedback", type=["jpg", "png", "jpeg"])
if uploaded_file:
    st.image(uploaded_file, caption="Uploaded Report", use_column_width=True)
    st.markdown("βœ… Received. AI feedback coming soon (future feature).")

# ------------------------ GLOSSARY HELPER ---------------------------
st.markdown("---")
st.subheader("πŸ“˜ Ask About a Science Term")
term = st.text_input("Enter a science term (e.g., osmosis, catalyst)")
if term:
    st.write(query_ai(f"Explain the term '{term}' in simple words for a student."))

# ---------------------- FEEDBACK SECTION ----------------------------
st.markdown("---")
st.subheader("πŸ’¬ Feedback")
user_feedback = st.text_area("What can we improve in this app?")
if user_feedback:
    st.success("Thanks! Your feedback was recorded (simulated). πŸ“¨")