sunbal7 commited on
Commit
431d541
Β·
verified Β·
1 Parent(s): 11018b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -102
app.py CHANGED
@@ -1,119 +1,116 @@
1
  # app.py
 
2
  import streamlit as st
3
  import requests
4
- from datetime import datetime
5
  from fpdf import FPDF
 
 
 
 
 
6
 
7
- # Replace with your actual OpenRouter or Hugging Face endpoint and key
8
- API_URL = "https://openrouter.ai/api/v1/chat/completions"
9
  API_KEY = "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"
10
  MODEL = "mistralai/mistral-7b-instruct"
11
 
12
- # ------------------------- AI QUERY FUNCTION -------------------------
13
- def query_ai(prompt):
 
14
  headers = {
15
  "Authorization": f"Bearer {API_KEY}",
16
  "Content-Type": "application/json"
17
  }
18
  data = {
19
  "model": MODEL,
20
- "messages": [{"role": "user", "content": prompt}],
21
- "temperature": 0.7
 
22
  }
23
- try:
24
- response = requests.post(API_URL, headers=headers, json=data)
25
- response.raise_for_status()
26
  return response.json()['choices'][0]['message']['content']
27
- except Exception as e:
28
- return f"❌ API Error: {str(e)}"
29
-
30
- # ---------------------- EXPERIMENT TEMPLATES ------------------------
31
- experiments = {
32
- "Vinegar + Baking Soda": {
33
- "hypothesis": "Mixing vinegar and baking soda will produce bubbles due to a chemical reaction.",
34
- "concept": "Acid-base reaction producing carbon dioxide."
35
- },
36
- "Floating Egg": {
37
- "hypothesis": "An egg will float in salt water but sink in plain water.",
38
- "concept": "Density difference between saltwater and freshwater."
39
- },
40
- "Lemon Battery": {
41
- "hypothesis": "A lemon can produce electricity to power a small LED.",
42
- "concept": "Chemical energy conversion to electrical energy."
43
- }
44
- }
45
-
46
- # -------------------------- PDF REPORT ------------------------------
47
- def generate_pdf_report(exp_name, hypo, explanation, result):
48
- pdf = FPDF()
49
- pdf.add_page()
50
- pdf.set_font("Arial", size=12)
51
- pdf.cell(200, 10, txt="Science Lab Report", ln=True, align='C')
52
- pdf.ln(10)
53
- pdf.multi_cell(0, 10, txt=f"Experiment: {exp_name}\n\nHypothesis: {hypo}\n\nAI Explanation: {explanation}\n\nExpected Result: {result}")
54
- filename = f"report_{datetime.now().strftime('%Y%m%d%H%M%S')}.pdf"
55
- pdf.output(filename)
56
- return filename
57
-
58
- # --------------------------- STREAMLIT UI ---------------------------
59
- st.set_page_config(page_title="πŸ§ͺ Science Lab Assistant", layout="centered")
60
- st.title("πŸ§ͺ Science Lab Assistant")
61
- st.markdown("Helping students understand, hypothesize, and explain science experiments.")
62
-
63
- exp_choice = st.selectbox("Choose an experiment or enter your own:", list(experiments.keys()) + ["Custom Experiment"])
64
-
65
- if exp_choice != "Custom Experiment":
66
- default_hypo = experiments[exp_choice]["hypothesis"]
67
- concept = experiments[exp_choice]["concept"]
68
- else:
69
- default_hypo = ""
70
- concept = ""
71
-
72
- with st.form("experiment_form"):
73
- exp_name = st.text_input("Experiment Name", value=exp_choice)
74
- hypo = st.text_area("Your Hypothesis", value=default_hypo)
75
- submit = st.form_submit_button("πŸ” Explain Experiment")
76
-
77
- if submit:
78
- with st.spinner("Thinking like a scientist..."):
79
- 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."
80
- explanation = query_ai(prompt)
81
-
82
- st.success("AI Explanation")
83
- st.write(explanation)
84
-
85
- # Generate expected result
86
- with st.spinner("Predicting result..."):
87
- result = query_ai(f"What is the expected result of this experiment: {exp_name}?")
88
- st.info(f"**Expected Result:** {result}")
89
-
90
- # Conceptual Science
91
- if concept:
92
- st.caption(f"🧠 Science Concept: {concept}")
93
-
94
- # PDF Download
95
- pdf_file = generate_pdf_report(exp_name, hypo, explanation, result)
96
- with open(pdf_file, "rb") as file:
97
- st.download_button("πŸ“„ Download Lab Report (PDF)", file, file_name=pdf_file)
98
-
99
- # --------------------- OPTIONAL FILE UPLOAD -------------------------
100
- st.markdown("---")
101
- st.subheader("πŸ“Έ Upload Your Lab Report Image (optional)")
102
- uploaded_file = st.file_uploader("Upload an image for feedback", type=["jpg", "png", "jpeg"])
103
  if uploaded_file:
104
- st.image(uploaded_file, caption="Uploaded Report", use_column_width=True)
105
- st.markdown("βœ… Received. AI feedback coming soon (future feature).")
106
-
107
- # ------------------------ GLOSSARY HELPER ---------------------------
108
- st.markdown("---")
109
- st.subheader("πŸ“˜ Ask About a Science Term")
110
- term = st.text_input("Enter a science term (e.g., osmosis, catalyst)")
111
- if term:
112
- st.write(query_ai(f"Explain the term '{term}' in simple words for a student."))
113
-
114
- # ---------------------- FEEDBACK SECTION ----------------------------
115
- st.markdown("---")
116
- st.subheader("πŸ’¬ Feedback")
117
- user_feedback = st.text_area("What can we improve in this app?")
118
- if user_feedback:
119
- st.success("Thanks! Your feedback was recorded (simulated). πŸ“¨")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # app.py
2
+
3
  import streamlit as st
4
  import requests
 
5
  from fpdf import FPDF
6
+ import pytesseract
7
+ from PIL import Image
8
+ import fitz # PyMuPDF
9
+ import io
10
+ import re
11
 
12
+ # ====== CONFIG ======
 
13
  API_KEY = "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"
14
  MODEL = "mistralai/mistral-7b-instruct"
15
 
16
+ # ====== FUNCTIONS ======
17
+ def query_llm(prompt):
18
+ url = "https://openrouter.ai/api/v1/chat/completions"
19
  headers = {
20
  "Authorization": f"Bearer {API_KEY}",
21
  "Content-Type": "application/json"
22
  }
23
  data = {
24
  "model": MODEL,
25
+ "messages": [
26
+ {"role": "user", "content": prompt}
27
+ ]
28
  }
29
+ response = requests.post(url, headers=headers, json=data)
30
+ if response.status_code == 200:
 
31
  return response.json()['choices'][0]['message']['content']
32
+ else:
33
+ return f"❌ API Error: {response.text}"
34
+
35
+ def extract_text_from_image(image):
36
+ return pytesseract.image_to_string(Image.open(image))
37
+
38
+ def extract_text_from_pdf(pdf_file):
39
+ text = ""
40
+ doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
41
+ for page in doc:
42
+ text += page.get_text()
43
+ return text
44
+
45
+ def evaluate_lab_report(text):
46
+ missing_sections = []
47
+ suggestions = []
48
+ score = 0
49
+ total = 5
50
+
51
+ if re.search(r"objective", text, re.I): score += 1
52
+ else:
53
+ missing_sections.append("Objective")
54
+ suggestions.append("Add a clear objective stating what the experiment is trying to discover.")
55
+
56
+ if re.search(r"hypothesis", text, re.I): score += 1
57
+ else:
58
+ missing_sections.append("Hypothesis")
59
+ suggestions.append("Include a hypothesis that predicts the experiment outcome.")
60
+
61
+ if re.search(r"procedure|method", text, re.I): score += 1
62
+ else:
63
+ missing_sections.append("Procedure")
64
+ suggestions.append("Describe the steps followed during the experiment.")
65
+
66
+ if re.search(r"observation", text, re.I): score += 1
67
+ else:
68
+ missing_sections.append("Observation")
69
+ suggestions.append("Mention what was observed during the experiment.")
70
+
71
+ if re.search(r"conclusion", text, re.I): score += 1
72
+ else:
73
+ missing_sections.append("Conclusion")
74
+ suggestions.append("Summarize the findings in a conclusion.")
75
+
76
+ return score, total, missing_sections, suggestions
77
+
78
+ # ====== STREAMLIT UI ======
79
+ st.set_page_config(page_title="πŸ§ͺ AI Science Lab Assistant", layout="centered")
80
+ st.title("πŸ§ͺ AI Science Lab Assistant")
81
+ st.markdown("Upload your **lab report** (image or PDF), and the AI will analyze, evaluate, and answer questions about it!")
82
+
83
+ uploaded_file = st.file_uploader("πŸ“€ Upload Lab Report (Image or PDF)", type=["png", "jpg", "jpeg", "pdf"])
84
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  if uploaded_file:
86
+ with st.spinner("πŸ” Extracting content..."):
87
+ if uploaded_file.type == "application/pdf":
88
+ text_content = extract_text_from_pdf(uploaded_file)
89
+ else:
90
+ text_content = extract_text_from_image(uploaded_file)
91
+
92
+ st.subheader("πŸ“„ Extracted Text")
93
+ st.text_area("Here is what we found:", value=text_content, height=250)
94
+
95
+ st.subheader("πŸ“Š Report Evaluation")
96
+ score, total, missing, tips = evaluate_lab_report(text_content)
97
+ st.markdown(f"βœ… **Score**: {score}/{total}")
98
+ if missing:
99
+ st.markdown("❗ **Missing Sections**:")
100
+ for m in missing:
101
+ st.write(f"- {m}")
102
+ if tips:
103
+ st.markdown("πŸ’‘ **Improvement Tips**:")
104
+ for t in tips:
105
+ st.write(f"- {t}")
106
+
107
+ st.subheader("πŸ’¬ Ask a Question About This Report")
108
+ user_q = st.text_input("Your question:")
109
+ if user_q:
110
+ full_prompt = f"Here is a science lab report:
111
+ {text_content}\n\nNow answer this question about it:\n{user_q}"
112
+ response = query_llm(full_prompt)
113
+ st.markdown(f"**Answer**: {response}")
114
+
115
+ else:
116
+ st.info("Please upload a lab report image or PDF to get started.")