File size: 6,839 Bytes
64664c6 ff19147 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 04e1114 0c8f0ca 64664c6 0c8f0ca 04e1114 7ca880c 0c8f0ca 7ca880c 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 ff19147 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 ff19147 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 ff19147 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca ff19147 64664c6 ff19147 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca 64664c6 0c8f0ca ff19147 64664c6 0c8f0ca | 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | import os
import streamlit as st
from groq import Groq
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
import pandas as pd
import docx
from pypdf import PdfReader
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
import tempfile
# -----------------------------
# GROQ CLIENT
# -----------------------------
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
# -----------------------------
# PAGE CONFIG
# -----------------------------
st.set_page_config(
page_title="AI Study Assistant π",
page_icon="π",
layout="wide"
)
# -----------------------------
# SIDEBAR
# -----------------------------
st.sidebar.title("π Settings")
education_level = st.sidebar.selectbox(
"Select Education Level",
[
"Primary School",
"Middle School",
"Secondary School",
"High School",
"Undergraduate",
"Graduate"
]
)
st.sidebar.markdown("---")
st.sidebar.write("Developed by **Ahmad Bilal** | Fiverr Portfolio Demo")
# -----------------------------
# HEADER
# -----------------------------
st.markdown(
"""
<div style='text-align:center; padding:10px; background-color:#f0f2f6; border-radius:10px'>
<h1 style='color:#0f4c81'>π AI Study Assistant</h1>
<p style='font-size:18px'>Upload study materials and ask questions instantly!</p>
</div>
""",
unsafe_allow_html=True
)
# -----------------------------
# FILE UPLOADER
# -----------------------------
uploaded_files = st.file_uploader(
"Upload Study Documents",
type=["pdf","docx","txt","csv","xlsx"],
accept_multiple_files=True
)
valid_files = []
if uploaded_files:
MAX_FILE_SIZE = 20 * 1024 * 1024
for file in uploaded_files:
if file.size > MAX_FILE_SIZE:
st.error(f"{file.name} is too large. Upload files under 20MB.")
else:
valid_files.append(file)
st.success(f"{len(valid_files)} file(s) ready for processing")
# -----------------------------
# FILE LOADERS
# -----------------------------
def load_pdf(file):
reader = PdfReader(file)
text = ""
for page in reader.pages:
if page.extract_text():
text += page.extract_text()
return text
def load_docx(file):
doc = docx.Document(file)
return "\n".join([p.text for p in doc.paragraphs])
def load_csv(file):
df = pd.read_csv(file)
return df.to_string()
def load_xlsx(file):
df = pd.read_excel(file)
return df.to_string()
def load_txt(file):
return file.read().decode("utf-8")
# -----------------------------
# DOCUMENT PROCESSING
# -----------------------------
def process_docs(files):
text = ""
for file in files:
if file.type == "application/pdf":
text += load_pdf(file)
elif file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
text += load_docx(file)
elif file.type == "text/csv":
text += load_csv(file)
elif file.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
text += load_xlsx(file)
else:
text += load_txt(file)
return text
# -----------------------------
# VECTOR STORE
# -----------------------------
@st.cache_resource
def create_vectorstore(text):
splitter = RecursiveCharacterTextSplitter(
chunk_size=800,
chunk_overlap=100
)
chunks = splitter.split_text(text)
embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
vectorstore = FAISS.from_texts(chunks, embeddings)
return vectorstore
# -----------------------------
# PROMPT BUILDER
# -----------------------------
def build_prompt(context, question, level):
style = {
"Primary School": "Explain like teaching a 5 year old using fun examples.",
"Middle School": "Explain with easy examples.",
"Secondary School": "Explain clearly using simple ideas.",
"High School": "Explain with reasoning and examples.",
"Undergraduate": "Explain in academic but clear language.",
"Graduate": "Provide detailed academic explanation."
}
prompt = f"""
Use the study material below to answer the question.
Study Material:
{context}
Question:
{question}
Explanation Style:
{style[level]}
"""
return prompt
# -----------------------------
# GROQ LLM
# -----------------------------
def ask_llm(prompt):
chat_completion = client.chat.completions.create(
messages=[{"role":"user","content":prompt}],
model="llama-3.3-70b-versatile"
)
return chat_completion.choices[0].message.content
# -----------------------------
# SUMMARY
# -----------------------------
def generate_summary(text):
prompt = f"""
Create a short and simple summary of this study material.
{text}
"""
return ask_llm(prompt)
# -----------------------------
# PDF GENERATOR
# -----------------------------
def create_pdf(text):
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
styles = getSampleStyleSheet()
story = [Paragraph(text, styles["Normal"])]
doc = SimpleDocTemplate(temp_file.name)
doc.build(story)
return temp_file.name
# -----------------------------
# MAIN LOGIC
# -----------------------------
if valid_files:
raw_text = process_docs(valid_files)
vectorstore = create_vectorstore(raw_text)
st.markdown("---")
st.subheader("β Ask a Question")
question = st.text_input("Type your question")
if question:
col1, col2 = st.columns([2,1])
docs = vectorstore.similarity_search(question, k=3)
context = "\n".join([doc.page_content for doc in docs])
prompt = build_prompt(context, question, education_level)
answer = ask_llm(prompt)
with col1:
st.markdown("### π Answer")
st.success(answer)
with col2:
st.markdown("### π Summary")
if st.button("Generate Summary"):
summary = generate_summary(context)
st.info(summary)
st.download_button(
"Download Markdown",
summary,
file_name="summary.md"
)
pdf_file = create_pdf(summary)
with open(pdf_file, "rb") as f:
st.download_button(
"Download PDF",
f,
file_name="summary.pdf"
)
else:
st.info("π Upload at least one study document to start.") |