mariaanwer commited on
Commit
7afc98c
·
verified ·
1 Parent(s): 88b6ac8

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +108 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,110 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import os
3
+ import shutil
4
  import streamlit as st
5
+ from langchain_huggingface import HuggingFaceEndpoint, HuggingFaceEmbeddings, ChatHuggingFace
6
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
7
+ from langchain_community.vectorstores import Chroma
8
+ from langchain_community.document_loaders import PyPDFLoader
9
+ from langchain_core.messages import HumanMessage, SystemMessage
10
 
11
+ # -----------------------------
12
+ # 1. Page Configuration
13
+ # -----------------------------
14
+ st.set_page_config(page_title="AI Study Assistant", layout="wide")
15
+ st.title("🎓 AI Study Assistant (Llama 3)")
16
+ st.markdown("---")
17
+
18
+ # Get token from secrets/environment
19
+ token = os.environ.get("HUGGINGFACEHUB_API_TOKEN2")
20
+
21
+ # -----------------------------
22
+ # 2. RAG Logic
23
+ # -----------------------------
24
+ def process_lecture_pdf(uploaded_file):
25
+ temp_path = os.path.join("/tmp", uploaded_file.name)
26
+ with open(temp_path, "wb") as f:
27
+ f.write(uploaded_file.getbuffer())
28
+
29
+ loader = PyPDFLoader(temp_path)
30
+ docs = loader.load()
31
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=700, chunk_overlap=100)
32
+ chunks = text_splitter.split_documents(docs)
33
+
34
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
35
+
36
+ db_path = "/tmp/chroma_db"
37
+ if os.path.exists(db_path):
38
+ shutil.rmtree(db_path)
39
+
40
+ vectorstore = Chroma.from_documents(
41
+ documents=chunks,
42
+ embedding=embeddings,
43
+ persist_directory=db_path
44
+ )
45
+ return vectorstore.as_retriever(search_kwargs={"k": 3}), docs
46
+
47
+ # -----------------------------
48
+ # 3. Model Setup (Llama 3 8B Instruct)
49
+ # -----------------------------
50
+ llm_endpoint = HuggingFaceEndpoint(
51
+ # Updated Repo ID for Llama 3
52
+ repo_id="meta-llama/Meta-Llama-3-8B-Instruct",
53
+ task="conversational",
54
+ huggingfacehub_api_token=token,
55
+ max_new_tokens=1024, # Llama 3 handles longer contexts well
56
+ temperature=0.6 # Slightly higher for better prose
57
+ )
58
+
59
+ chat_llm = ChatHuggingFace(llm=llm_endpoint)
60
+
61
+ # -----------------------------
62
+ # 4. User Interface
63
+ # -----------------------------
64
+ col1, col2 = st.columns([1, 2])
65
+
66
+ with col1:
67
+ st.header("📂 Upload Notes")
68
+ uploaded_file = st.file_uploader("Upload Lecture PDF", type="pdf")
69
+
70
+ if uploaded_file:
71
+ if 'retriever' not in st.session_state or st.session_state.get('last_file') != uploaded_file.name:
72
+ with st.spinner("Analyzing PDF with Llama 3..."):
73
+ retriever, full_docs = process_lecture_pdf(uploaded_file)
74
+ st.session_state.retriever = retriever
75
+ st.session_state.full_text = "\n".join([d.page_content for d in full_docs])
76
+ st.session_state.last_file = uploaded_file.name
77
+ st.success("Ready to study!")
78
+
79
+ st.header("📝 Summarize")
80
+ if st.button("Summarize Content"):
81
+ if 'full_text' in st.session_state:
82
+ with st.spinner("Llama 3 is summarizing..."):
83
+ # We can now use SystemMessage to give Llama 3 a "persona"
84
+ messages = [
85
+ SystemMessage(content="You are a helpful university teaching assistant. Summarize the following text clearly."),
86
+ HumanMessage(content=f"Notes: {st.session_state.full_text[:4000]}")
87
+ ]
88
+ response = chat_llm.invoke(messages)
89
+ st.write(response.content)
90
+ else:
91
+ st.warning("Please upload a PDF first.")
92
+
93
+ with col2:
94
+ st.header("💬 Ask Questions")
95
+ user_query = st.text_input("Ask about your lecture:")
96
+
97
+ if user_query:
98
+ if 'retriever' in st.session_state:
99
+ with st.spinner("Searching..."):
100
+ context_docs = st.session_state.retriever.invoke(user_query)
101
+ context_text = "\n\n".join([doc.page_content for doc in context_docs])
102
+
103
+ messages = [
104
+ SystemMessage(content="Use the provided context to answer the student's question accurately."),
105
+ HumanMessage(content=f"Context: {context_text}\n\nQuestion: {user_query}")
106
+ ]
107
+ response = chat_llm.invoke(messages)
108
+ st.info(response.content)
109
+ else:
110
+ st.warning("Upload a PDF to start.")