nightprogrammer commited on
Commit
daa9004
·
verified ·
1 Parent(s): cb8398f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -58
app.py CHANGED
@@ -1,75 +1,79 @@
1
  import streamlit as st
2
- import pdfplumber
3
- import logging
4
  import os
5
- import threading
6
- from llama_index.core import VectorStoreIndex
7
- from langchain_community.vectorstores import FAISS
8
- from langchain_community.embeddings import OpenAIEmbeddings
9
- from langchain_community.chat_models import ChatOpenAI
10
- from langchain.text_splitter import RecursiveCharacterTextSplitter
11
- from streamlit.runtime.scriptrunner import add_script_run_ctx, get_script_run_ctx
12
 
13
- # Suppress Streamlit warnings
14
- logging.getLogger("streamlit").setLevel(logging.ERROR)
15
 
16
- # Ensure Streamlit runs in the correct execution context
17
- ctx = get_script_run_ctx()
18
- add_script_run_ctx(ctx)
19
 
20
- # Explicitly set Streamlit UI mode to prevent bare mode issues
21
- os.environ["STREAMLIT_SERVER_RUN_ON_SAVE"] = "true"
22
-
23
- # Configure Streamlit app
24
- st.set_page_config(page_title="📚 Curriculum Assistant", layout="wide")
25
- st.title("📚 Curriculum Assistant for Teachers")
26
-
27
- def process_document(file):
28
- """Extracts text from syllabus file"""
29
  text = ""
30
- with pdfplumber.open(file) as pdf:
31
- for page in pdf.pages:
32
- text += page.extract_text() + "\n"
33
  return text
34
 
35
- def create_vector_store(text):
36
- """Embeds syllabus chunks for retrieval"""
37
- splitter = RecursiveCharacterTextSplitter(chunk_size=500)
38
- docs = splitter.split_text(text)
39
- vectorstore = FAISS.from_texts(docs, OpenAIEmbeddings())
40
- return vectorstore
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- def generate_response(prompt, context):
43
- """Queries AI model with relevant syllabus chunks"""
44
- model = ChatOpenAI(model="gpt-4", temperature=0.7)
45
- response = model.predict(f"Using the following syllabus context:\n{context}\nGenerate: {prompt}")
46
- return response
47
 
48
- # File uploader
49
- uploaded_file = st.file_uploader("Upload syllabus or textbook (PDF/Word)", type=["pdf", "docx"])
50
 
51
  if uploaded_file:
52
- syllabus_text = process_document(uploaded_file)
53
- vector_db = create_vector_store(syllabus_text)
54
- st.success("Syllabus processed successfully!")
 
 
55
 
56
- # Chat interface
57
- if "messages" not in st.session_state:
58
- st.session_state["messages"] = []
59
 
60
- user_input = st.chat_input("Ask about lesson plans, MCQs, or worksheets")
61
- if user_input:
62
- response = generate_response(user_input, syllabus_text)
63
- st.session_state["messages"].append(("User", user_input))
64
- st.session_state["messages"].append(("Assistant", response))
65
 
66
- for role, msg in st.session_state["messages"]:
67
- st.chat_message(role).write(msg)
 
 
 
 
 
 
 
68
 
69
- # Check for multithreading issues
70
- def check_multithreading():
71
- """Ensures Streamlit functions run in the main thread"""
72
- if threading.current_thread().name != "MainThread":
73
- st.warning("⚠️ Streamlit functions should run in the main thread to avoid execution issues.")
74
 
75
- check_multithreading()
 
 
 
 
 
1
  import streamlit as st
2
+ import tempfile
 
3
  import os
4
+ import docx
5
+ import PyPDF2
 
 
 
 
 
6
 
7
+ import openai # Or use HuggingFace's transformers/pipelines for open-source models
 
8
 
9
+ # Set your OpenAI API key (or replace with Hugging Face model and pipeline)
10
+ OPENAI_API_KEY = st.secrets["OPENAI_API_KEY"]
 
11
 
12
+ def extract_text_from_pdf(file):
13
+ reader = PyPDF2.PdfReader(file)
 
 
 
 
 
 
 
14
  text = ""
15
+ for page in reader.pages:
16
+ text += page.extract_text() + "\n"
 
17
  return text
18
 
19
+ def extract_text_from_docx(file):
20
+ doc = docx.Document(file)
21
+ text = "\n".join([para.text for para in doc.paragraphs])
22
+ return text
23
+
24
+ def generate_questions(text, instruction):
25
+ # You can replace this with a HuggingFace pipeline (e.g., text-generation with Llama3)
26
+ openai.api_key = OPENAI_API_KEY
27
+ prompt = (
28
+ f"Given the following content:\n\n{text}\n\n"
29
+ f"{instruction}\n"
30
+ "Provide the output in a clear, numbered list."
31
+ )
32
+ response = openai.ChatCompletion.create(
33
+ model="gpt-3.5-turbo", # or "gpt-4" if available
34
+ messages=[{"role": "system", "content": "You are a helpful assistant."},
35
+ {"role": "user", "content": prompt}],
36
+ max_tokens=800,
37
+ temperature=0.7,
38
+ )
39
+ return response.choices[0].message.content.strip()
40
+
41
+ st.title("Quiz & MCQ Generator Chatbot 🤖")
42
+ st.write("Upload a PDF or DOCX, then ask me to generate MCQs, questions, or a quiz!")
43
 
44
+ if "chat_history" not in st.session_state:
45
+ st.session_state["chat_history"] = []
 
 
 
46
 
47
+ uploaded_file = st.file_uploader("Upload PDF or DOCX", type=["pdf", "docx"])
48
+ file_text = ""
49
 
50
  if uploaded_file:
51
+ if uploaded_file.type == "application/pdf":
52
+ file_text = extract_text_from_pdf(uploaded_file)
53
+ elif uploaded_file.type in ["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/msword"]:
54
+ file_text = extract_text_from_docx(uploaded_file)
55
+ st.success("File uploaded and extracted!")
56
 
57
+ user_input = st.text_input("You:", key="chat_input")
 
 
58
 
59
+ if st.button("Send"):
60
+ if user_input:
61
+ st.session_state.chat_history.append(("user", user_input))
 
 
62
 
63
+ # If user asks for MCQs, questions, quiz, etc., use document context
64
+ if any(keyword in user_input.lower() for keyword in ["mcq", "quiz", "question", "test"]):
65
+ if file_text:
66
+ answer = generate_questions(file_text, user_input)
67
+ else:
68
+ answer = "Please upload a PDF or DOCX file first!"
69
+ else:
70
+ # Generic chat (can also use LLM here)
71
+ answer = "Please ask me to generate MCQs, questions, or a quiz from your uploaded file!"
72
 
73
+ st.session_state.chat_history.append(("bot", answer))
 
 
 
 
74
 
75
+ for sender, message in st.session_state.chat_history:
76
+ if sender == "user":
77
+ st.markdown(f"**You:** {message}")
78
+ else:
79
+ st.markdown(f"**Bot:** {message}")