# app.py import streamlit as st import pytesseract from PIL import Image import fitz # PyMuPDF import io import requests import re import numpy as np from fpdf import FPDF from datetime import datetime import os # --- Config --- API_URL = "https://openrouter.ai/api/v1/chat/completions" API_KEY = "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" MODEL = "mistralai/mistral-7b-instruct" # Set Tesseract path for different environments try: # For Windows if os.name == 'nt': pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' # For Linux (Streamlit Sharing) elif 'tesseract' not in os.environ.get('PATH', ''): pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract' except Exception as e: st.warning(f"Tesseract configuration issue: {str(e)}") # Set page config st.set_page_config( page_title="๐ฌ Science Lab Assistant", layout="centered", page_icon="๐ฌ", initial_sidebar_state="expanded" ) # Custom CSS for styling st.markdown(""" """, unsafe_allow_html=True) # Header st.markdown('
๐ฌ Science Lab Assistant
', unsafe_allow_html=True) # Introduction st.markdown("""Your all-in-one science companion! Design experiments, generate reports, and get AI-powered feedback on your lab work.
๐ Design Your Experiment
', unsafe_allow_html=True) with st.form("experiment_form"): # Pre-fill if template selected if selected_exp != "Custom Experiment" and selected_exp in experiments: default_hypo = experiments[selected_exp]["hypothesis"] concept = experiments[selected_exp]["concept"] exp_name = selected_exp else: default_hypo = "" concept = "" exp_name = st.text_input("Experiment Name", placeholder="e.g., Effect of Temperature on Enzyme Activity") hypo = st.text_area("Your Hypothesis", value=default_hypo, placeholder="What do you predict will happen?") materials = st.text_area("Materials Needed", placeholder="List all materials needed for this experiment") procedure = st.text_area("Procedure Steps", placeholder="Step-by-step instructions for conducting the experiment") submit = st.form_submit_button("๐ Generate Experiment Guide", use_container_width=True) if submit: if not exp_name or not hypo: st.warning("Please provide at least an experiment name and hypothesis") st.stop() with st.spinner("Designing your experiment guide..."): prompt = f""" Create a comprehensive guide for a science experiment with the following details: Experiment Name: {exp_name} Hypothesis: {hypo} Materials: {materials if materials else 'Not specified'} Procedure: {procedure if procedure else 'Not specified'} Please provide: 1. A clear explanation of the scientific concept behind the experiment 2. Step-by-step instructions for conducting the experiment 3. Safety precautions 4. Expected results and why they're expected 5. How to interpret the results """ explanation = query_ai(prompt) if explanation: st.success("โ Experiment Guide Generated!") st.balloons() # Display explanation st.markdown("### ๐งช Experiment Guide") st.markdown(f"๐ฌ Popular Science Experiments
', unsafe_allow_html=True) col1, col2 = st.columns(2) with col1: with st.container(): st.markdown('๐ค Upload Your Lab Report
', unsafe_allow_html=True) uploaded_file = st.file_uploader("Upload image (JPG, PNG) or PDF", type=["jpg", "jpeg", "png", "pdf"], label_visibility="collapsed") lab_text = "" if uploaded_file: file_bytes = uploaded_file.read() file_ext = uploaded_file.name.split(".")[-1].lower() if file_ext == "pdf": try: doc = fitz.open(stream=file_bytes, filetype="pdf") for page in doc: lab_text += page.get_text() st.success("โ PDF text extracted successfully!") except Exception as e: st.error(f"Error reading PDF: {str(e)}") else: try: image = Image.open(io.BytesIO(file_bytes)) st.image(image, caption="Uploaded Image", width=300) # OCR processing with st.spinner("Extracting text from image..."): try: lab_text = pytesseract.image_to_string(image) st.success("โ Text extracted from image!") except pytesseract.pytesseract.TesseractNotFoundError: st.error(""" **Tesseract OCR not found!** To enable image text extraction: 1. Install Tesseract OCR on your system 2. Add it to your system PATH 3. Restart the application For Windows: Download from [UB-Mannheim/tesseract](https://github.com/UB-Mannheim/tesseract/wiki) For Linux: `sudo apt install tesseract-ocr` For Mac: `brew install tesseract` """) st.stop() except Exception as e: st.error(f"OCR Error: {str(e)}") st.stop() except Exception as e: st.error(f"Error processing image: {str(e)}") # Allow text editing if lab_text: st.markdown('โ๏ธ Extracted Text
', unsafe_allow_html=True) st.caption("Review and edit the extracted text if needed before analysis") lab_text = st.text_area("", lab_text, height=300, label_visibility="collapsed") # --- AI Evaluation --- if lab_text.strip(): # -- AI Evaluation Prompt -- full_prompt = f"""You are a science teacher evaluating a student's lab report. Please provide a comprehensive analysis: Lab Report: {lab_text} Evaluation Guidelines: 1. **Section Check**: Identify which of these sections are present and which are missing: - Title - Objective - Hypothesis - Materials - Procedure - Observations - Results - Conclusion - References 2. **Completeness Score**: - Assign a numerical score from 1-10 based on completeness - Justify the score based on missing sections and content quality 3. **Improvement Tips**: - For each missing section, explain why it's important - Provide specific suggestions for improvement (e.g., "Try writing a more detailed observation section by including quantitative data") - Highlight any sections that need more detail or clarity 4. **Structure Response**: - Start with: "### Missing Sections:" - Then: "### Completeness Score: X/10" - Then: "### Improvement Tips:" - Finally: "### Detailed Feedback:" Be concise but thorough in your analysis. """ if st.button("๐งช Analyze Report", use_container_width=True): with st.spinner("๐ Analyzing report with AI. This may take 20-30 seconds..."): result = query_ai(full_prompt) if result: st.success("โ Analysis Complete!") st.balloons() # Extract score using regex score_match = re.search(r"Completeness Score:\s*(\d+)/10", result, re.IGNORECASE) score = int(score_match.group(1)) if score_match else None # Display score in a card if score is not None: with st.container(): st.markdown('โ Ask About Your Report
', unsafe_allow_html=True) col1, col2 = st.columns([3, 1]) with col1: user_question = st.text_input("Ask a question about your lab report", placeholder="e.g., How can I improve my hypothesis?") with col2: st.markdown("", unsafe_allow_html=True) ask_button = st.button("๐ Ask Question", use_container_width=True) if (ask_button or user_question) and user_question.strip(): with st.spinner("Thinking..."): followup_prompt = f"""Lab Report: {lab_text} Question: {user_question} Answer the question based on the lab report. If the question can't be answered from the report, suggest what information the student should add to answer it. """ followup_response = query_ai(followup_prompt) if followup_response: st.markdown("### ๐ฌ AI Response") st.markdown(f'๐ Sample Lab Report
', unsafe_allow_html=True) st.markdown(""" **Title:** Effect of Temperature on Enzyme Activity **Objective:** To investigate how temperature affects catalase enzyme activity **Hypothesis:** Enzyme activity will increase with temperature up to 37ยฐC, then decrease **Materials:** Test tubes, hydrogen peroxide, liver extract, thermometer **Procedure:** 1. Prepare test tubes at 5 different temperatures 2. Add equal amounts of hydrogen peroxide and liver extract 3. Measure oxygen production **Observations:** More bubbles at 37ยฐC compared to lower or higher temperatures **Conclusion:** Enzyme activity peaks at body temperature """) st.info("๐ Upload your own lab report to get a personalized analysis!") # Footer st.markdown("---") st.markdown(' ', unsafe_allow_html=True)