engrphoenix's picture
Update app.py
001485a verified
raw
history blame
3.88 kB
import streamlit as st
from PyPDF2 import PdfReader
import pandas as pd
from transformers import pipeline
import random
# Load the Hugging Face model for text generation and summarization (FLAN-T5 or T5-Small)
@st.cache_resource
def load_text_generator():
return pipeline("text2text-generation", model="google/flan-t5-base") # Efficient and professional model
text_generator = load_text_generator()
# Function to extract text from a PDF file
def extract_pdf_content(pdf_file):
reader = PdfReader(pdf_file)
content = ""
for page in reader.pages:
content += page.extract_text()
return content
# Function to extract content from a text file
def extract_text_file(file):
return file.read().decode("utf-8")
# Function to load a CSV file
def read_csv_file(file):
df = pd.read_csv(file)
return df.to_string()
# Function to search for a topic in the extracted content
def search_topic_in_content(content, topic):
sentences = content.split(".") # Break content into sentences
topic_sentences = [s for s in sentences if topic.lower() in s.lower()] # Filter sentences containing the topic
return ". ".join(topic_sentences) if topic_sentences else None
# Function to generate structured content using Hugging Face model
def generate_professional_content(topic):
prompt = f"Explain '{topic}' in bullet points, highlighting the key concepts, examples, and applications in a professional manner for electrical engineering students."
response = text_generator(prompt, max_length=300, num_return_sequences=1)
return response[0]['generated_text']
# Function to generate a quiz question
def generate_quiz(topic):
questions = [
f"What is the fundamental principle of {topic}?",
f"Name a practical application of {topic}.",
f"What are the key equations associated with {topic}?",
f"Describe how {topic} is used in real-world scenarios.",
f"List common problems and solutions related to {topic}.",
]
return random.choice(questions)
# Streamlit App
st.title("Generative AI for Electrical Engineering Education")
st.sidebar.header("AI-Based Tutor")
# File upload section
uploaded_file = st.sidebar.file_uploader("Upload Study Material (PDF/TXT/CSV)", type=["pdf", "txt", "csv"])
topic = st.sidebar.text_input("Enter a topic (e.g., Newton's Third Law, DC Motors)")
# Process uploaded file
content = ""
if uploaded_file:
file_type = uploaded_file.name.split(".")[-1]
if file_type == "pdf":
content = extract_pdf_content(uploaded_file)
elif file_type == "txt":
content = extract_text_file(uploaded_file)
elif file_type == "csv":
content = read_csv_file(uploaded_file)
st.sidebar.success(f"{uploaded_file.name} uploaded successfully!")
st.write("**Extracted Content from File:**")
st.write(content[:1000] + "...") # Display a snippet of the content
# Generate study material
if st.button("Generate Study Material"):
if topic:
st.header(f"Study Material: {topic}")
# Extract relevant content from the uploaded material
filtered_content = search_topic_in_content(content, topic) if content else ""
if filtered_content:
st.write("**Relevant Extracted Content from Uploaded Material:**")
st.write(filtered_content)
else:
st.warning("No relevant content found in the uploaded material. Generating AI-based content instead.")
ai_content = generate_professional_content(topic)
st.write("**AI-Generated Content:**")
st.write(ai_content)
else:
st.warning("Please enter a topic!")
# Generate quiz
if st.button("Generate Quiz"):
if topic:
st.header("Quiz Question")
question = generate_quiz(topic)
st.write(question)
else:
st.warning("Please enter a topic!")