Enginuity_CE / app.py
Ci-Dave's picture
Added Files
a288b14
import streamlit as st
from fpdf import FPDF
import google.generativeai as genai
import fitz
import os
import pandas as pd
# Configure Gemini API
try:
api_key = st.secrets["gemini"]["api_key"]
genai.configure(api_key=api_key)
except KeyError:
st.error("API key not found. Please check your Streamlit secrets configuration.")
MODEL_ID = "gemini-1.5-flash"
gen_model = genai.GenerativeModel(MODEL_ID)
# Ensure 'static' directory exists
os.makedirs("static", exist_ok=True)
# Custom CSS for larger font and sidebar adjustments
st.markdown("""
<style>
body, h1, h2, h3, h4, h5, h6 {
font-size: 20px;
}
.stSidebar {
font-size: 20px;
width: 400px;
}
.css-1d391kg {
padding-top: 10px;
padding-left: 10px;
padding-right: 10px;
}
.sidebar-title {
font-size: 50px;
font-weight: bold;
padding-bottom: 20px;
}
</style>
""", unsafe_allow_html=True)
# Page Navigation with Enlarged Sidebar
def main():
st.sidebar.markdown('<div class="sidebar-title">Enginuity CE</div>', unsafe_allow_html=True)
st.sidebar.header("Navigation Menu")
page = st.sidebar.radio("Go to", ["Home", "Calculator Guides", "Course Subject Selector", "PDF Analysis (Summary, Quiz, Glossary)", "Schedule Planner"])
if page == "Home":
home_page()
elif page == "Calculator Guides":
calculator_guides_page()
elif page == "Course Subject Selector":
course_subject_page()
elif page == "PDF Analysis (Summary, Quiz, Glossary)":
pdf_analysis_page()
elif page == "Schedule Planner":
schedule_planner_page()
# Home Page
def home_page():
st.title("Welcome to Enginuity CE")
st.write("This app offers AI-powered solutions for civil engineering students in the Philippines.")
st.header("📘 Page Descriptions")
st.subheader("1. Calculator Guides")
st.write(
"Access a variety of calculator techniques and formulas for different Civil Engineering subjects. "
"You can also input specific questions to receive AI-generated explanations and guides tailored to your needs."
)
st.subheader("2. Course Subject Selector")
st.write(
"Easily generate AI-powered study materials in PDF format. Select your year level and subject to receive detailed content "
"that covers key concepts and essential topics for your studies."
)
st.subheader("3. PDF Analysis (Summary, Quiz, Glossary)")
st.write(
"Upload a PDF file containing study material or notes, and let the AI summarize its contents, generate quizzes for practice, "
"or extract important terms for a glossary. Download the results as a PDF for easy offline access."
)
st.subheader("4. Schedule Planner")
st.write(
"Effortlessly plan your weekly schedule by selecting subjects and specifying your availability. "
"This tool is designed for both students and teachers to create organized study or teaching schedules. "
"AI can help optimize your schedule based on your preferences and requirements."
)
# Calculator Guides Page
def calculator_guides_page():
st.title("Calculator Guides")
st.write("Choose your course subject to view calculator techniques and formulas.")
year = st.selectbox("Select Year:", ["1st Year", "2nd Year", "3rd Year"])
subjects = {
"1st Year": ["Algebra", "Trigonometry", "General Chemistry", "Physics I"],
"2nd Year": ["Calculus II", "Differential Equations", "Statics and Dynamics", "Surveying"],
"3rd Year": ["Structural Engineering", "Hydraulics", "Soil Mechanics", "Construction Management"]
}
subject = st.selectbox("Select Subject:", subjects[year])
user_prompt = st.text_area("Enter your specific question or request about this subject:")
st.write("""
### Instructions:
1. Select your year level and subject.
2. Enter a specific question or request if you have one.
3. Click the **Show Calculator Guides** button to view AI-generated content.
""")
if st.button("Show Calculator Guides"):
try:
response = gen_model.generate_content(f"Provide calculator techniques and formulas for {subject} in Civil Engineering. Additionally, answer the user's question: {user_prompt}")
st.write(response.text if hasattr(response, 'text') else "Error generating content.")
except Exception as e:
st.error(f"Error during content generation: {e}")
# Schedule Planner Page
def schedule_planner_page():
st.title("Schedule Planner")
st.write("Follow the steps below to plan your schedule:")
st.write("1. Select your role (Student or Teacher).")
st.write("2. If you're a student, choose your year level.")
st.write("3. Select your subjects and assign a day and time slot for each.")
st.write("4. Optionally, add important dates and additional preferences.")
st.write("5. Click 'Generate Schedule Plan' to get an AI-optimized schedule.")
role = st.radio("Select your role:", ["Student", "Teacher"])
year = st.selectbox("Select Year (for Students):", ["1st Year", "2nd Year", "3rd Year"], disabled=(role == "Teacher"))
subjects = {
"1st Year": ["Algebra", "Trigonometry", "General Chemistry", "Physics I"],
"2nd Year": ["Calculus II", "Differential Equations", "Statics and Dynamics", "Surveying"],
"3rd Year": ["Structural Engineering", "Hydraulics", "Soil Mechanics", "Construction Management"]
}
selected_subjects = st.multiselect("Select Subjects:", subjects.get(year, []))
schedule = {}
for subj in selected_subjects:
day = st.selectbox(f"Select Day for {subj}", ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
time_range = st.slider(f"Select time for {subj} ({day})", 6, 22, (8, 10))
schedule[subj] = {"day": day, "time": time_range}
st.write("## Mark Your Calendar")
st.date_input("Select Important Dates:", [])
user_prompt = st.text_area("Enter additional preferences or requirements for your schedule:")
if st.button("Generate Schedule Plan"):
try:
response = gen_model.generate_content(
f"Generate a precise weekly schedule for a {role} in Civil Engineering. Subjects: {selected_subjects}, Schedule: {schedule}, Additional Requirements: {user_prompt}"
)
st.write(response.text if hasattr(response, 'text') else "Error generating schedule.")
except Exception as e:
st.error(f"Error generating schedule: {e}")
# PDF Analysis Page
def pdf_analysis_page():
st.title("PDF Analysis: Summary, Quiz, or Glossary")
st.write("Follow the steps below to analyze your PDF:")
st.write("1. Upload your PDF file.")
st.write("2. Select the action: summarize, generate a quiz, or create a glossary.")
st.write("3. Click 'Generate Result' to see the output and download it as a PDF.")
uploaded_file = st.file_uploader("Upload PDF File", type=["pdf"])
if uploaded_file is not None:
try:
pdf_data = uploaded_file.read()
doc = fitz.Document(stream=pdf_data, filetype="pdf")
pdf_text = "".join(page.get_text() for page in doc)
st.text_area("Extracted PDF Content", pdf_text[:3000])
action = st.selectbox("Choose Action:", ["Summary", "Quiz Generation", "Glossary Generation"])
if st.button("Generate Result"):
response = gen_model.generate_content(f"{action} this text: {pdf_text}")
content = response.text if hasattr(response, 'text') else "Error generating content."
rows = content.split('\n')
data = [row.split('|') for row in rows if '|' in row]
if data:
df = pd.DataFrame(data)
st.dataframe(df)
else:
st.write(content)
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt=f"{action} Result", ln=True, align='C')
for line in rows:
pdf.multi_cell(0, 10, line)
pdf_file = os.path.join("static", f"{action}_result.pdf")
pdf.output(pdf_file)
with open(pdf_file, "rb") as f:
st.download_button(label="Download PDF", data=f, file_name=f"{action}_result.pdf")
st.success(f"{action} result generated and available for download.")
except Exception as e:
st.error(f"Error reading PDF: {e}")
# Course Subject Page
def course_subject_page():
st.title("Course Subject Selector")
st.write("Follow the steps below to generate study materials:")
st.write("1. Select your year level and subject.")
st.write("2. Click 'Generate PDF Study Material' to create and download a PDF.")
year = st.selectbox("Select Year:", ["1st Year", "2nd Year", "3rd Year"])
subjects = {
"1st Year": ["Algebra", "Trigonometry", "General Chemistry", "Physics I"],
"2nd Year": ["Calculus II", "Differential Equations", "Statics and Dynamics", "Surveying"],
"3rd Year": ["Structural Engineering", "Hydraulics", "Soil Mechanics", "Construction Management"]
}
subject = st.selectbox("Select Subject:", subjects[year])
if st.button("Generate PDF Study Material"):
generate_pdf(subject)
# Function to generate PDF study material
def generate_pdf(subject):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt=f"Study Material for {subject}", ln=True, align='C')
pdf.output(f"static/{subject}_study_material.pdf")
st.success(f"PDF for {subject} generated successfully!")
if __name__ == "__main__":
main()