sunbal7 commited on
Commit
242da2d
Β·
verified Β·
1 Parent(s): e33f38e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -83
app.py CHANGED
@@ -1,113 +1,90 @@
 
 
 
 
 
1
  import streamlit as st
2
  from transformers import pipeline
3
- from docx import Document
4
- from PyPDF2 import PdfReader
5
- from datetime import datetime
6
- from fpdf import FPDF
7
- import tempfile
8
- import os
9
-
10
-
11
 
 
12
  st.set_page_config(page_title="AI Study Plan Assistant", layout="wide")
13
 
14
-
15
- # Caching model load
16
  @st.cache_resource
17
  def load_models():
18
  summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
19
  qa_pipeline = pipeline("question-answering", model="distilbert-base-uncased-distilled-squad")
20
  return summarizer, qa_pipeline
21
 
22
- # Text extraction
23
- def extract_text(uploaded_file):
24
- ext = os.path.splitext(uploaded_file.name)[-1].lower()
 
 
25
  if ext == ".txt":
26
- return uploaded_file.read().decode("utf-8")
27
  elif ext == ".docx":
28
- doc = Document(uploaded_file)
29
  return "\n".join([para.text for para in doc.paragraphs])
30
  elif ext == ".pdf":
31
- pdf = PdfReader(uploaded_file)
32
- return "\n".join([page.extract_text() for page in pdf.pages if page.extract_text()])
 
 
 
33
  else:
34
- return None
35
 
36
- # Generate Study Plan
37
- def generate_study_plan(text, hours, exam_date, language):
38
- today = datetime.now().date()
39
  try:
 
 
40
  exam = datetime.strptime(exam_date.strip(), "%Y-%m-%d").date()
41
  days = (exam - today).days
42
- except:
43
- return "❌ Invalid date format. Use YYYY-MM-DD."
44
 
45
- if days <= 0:
46
- return "❌ Exam date must be in the future."
47
 
48
- prompt = f"Create a {days}-day study plan for this syllabus:\n{text}\nDaily study time: {hours} hours."
49
- if language == "Urdu":
50
- prompt += "\nTranslate the plan into Urdu."
51
 
52
- summary = summarizer(prompt, max_length=500, min_length=100, do_sample=False)
53
- return summary[0]['summary_text']
54
 
55
- # Generate PDF
56
- def create_pdf(content):
57
- pdf = FPDF()
58
- pdf.add_page()
59
- pdf.set_font("Arial", size=12)
60
- for line in content.split("\n"):
61
- pdf.multi_cell(0, 10, line)
62
- temp_path = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
63
- pdf.output(temp_path.name)
64
- return temp_path.name
65
 
66
- # Ask Question
67
- def answer_question(context, question):
68
  try:
 
69
  result = qa_pipeline({"context": context, "question": question})
70
- return result["answer"]
71
  except Exception as e:
72
  return f"⚠️ Error: {str(e)}"
73
 
74
- # UI
75
- st.set_page_config(page_title="AI Study Plan Assistant", layout="wide")
76
-
77
- st.title("πŸ“š AI Study Plan Assistant")
78
-
79
- with st.sidebar:
80
- st.header("Upload Syllabus & Set Options")
81
- uploaded_file = st.file_uploader("Upload a .pdf, .docx or .txt file", type=["pdf", "docx", "txt"])
82
- study_hours = st.number_input("Study Hours per Day", min_value=1, max_value=24, value=2)
83
- exam_date = st.text_input("Exam Date (YYYY-MM-DD)")
84
- language = st.selectbox("Language of Plan", ["English", "Urdu"])
85
-
86
- generate_btn = st.button("Generate Study Plan")
87
-
88
- # Display Plan
89
- if generate_btn and uploaded_file:
90
- with st.spinner("πŸ” Reading content..."):
91
- raw_text = extract_text(uploaded_file)
92
- if not raw_text:
93
- st.error("⚠️ Could not extract text from the file.")
94
- else:
95
- with st.spinner("✍️ Generating study plan..."):
96
- plan = generate_study_plan(raw_text, study_hours, exam_date, language)
97
- st.subheader("πŸ“„ Generated Study Plan")
98
- st.text_area("Study Plan", value=plan, height=400)
99
-
100
- pdf_path = create_pdf(plan)
101
- with open(pdf_path, "rb") as f:
102
- st.download_button(label="πŸ“₯ Download Study Plan as PDF", data=f, file_name="study_plan.pdf")
103
-
104
- # Ask a question
105
- st.markdown("---")
106
- st.subheader("❓ Ask a Question From Your Syllabus")
107
- if uploaded_file:
108
- question = st.text_input("Type your question:")
109
- if st.button("Get Answer"):
110
- context = extract_text(uploaded_file)
111
- with st.spinner("πŸ€– Searching for the answer..."):
112
- answer = answer_question(context, question)
113
- st.success(f"Answer: {answer}")
 
1
+ import os
2
+ import tempfile
3
+ from datetime import datetime
4
+ from PyPDF2 import PdfReader
5
+ from docx import Document
6
  import streamlit as st
7
  from transformers import pipeline
 
 
 
 
 
 
 
 
8
 
9
+ # βœ… Page config MUST be first Streamlit command
10
  st.set_page_config(page_title="AI Study Plan Assistant", layout="wide")
11
 
12
+ # Load models with caching
 
13
  @st.cache_resource
14
  def load_models():
15
  summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
16
  qa_pipeline = pipeline("question-answering", model="distilbert-base-uncased-distilled-squad")
17
  return summarizer, qa_pipeline
18
 
19
+ summarizer, qa_pipeline = load_models()
20
+
21
+ # Extract text from supported formats
22
+ def extract_text(file):
23
+ ext = os.path.splitext(file.name)[1].lower()
24
  if ext == ".txt":
25
+ return file.read().decode("utf-8")
26
  elif ext == ".docx":
27
+ doc = Document(file)
28
  return "\n".join([para.text for para in doc.paragraphs])
29
  elif ext == ".pdf":
30
+ pdf_reader = PdfReader(file)
31
+ text = ""
32
+ for page in pdf_reader.pages:
33
+ text += page.extract_text() + "\n"
34
+ return text
35
  else:
36
+ raise ValueError("Only .txt, .docx, and .pdf files are supported.")
37
 
38
+ # Generate study plan
39
+ def generate_plan(file, hours_per_day, exam_date, language):
 
40
  try:
41
+ content = extract_text(file)
42
+ today = datetime.now().date()
43
  exam = datetime.strptime(exam_date.strip(), "%Y-%m-%d").date()
44
  days = (exam - today).days
 
 
45
 
46
+ if days <= 0:
47
+ return "❌ Exam date must be in the future."
48
 
49
+ prompt = f"Create a {days}-day study plan for this syllabus:\n{content}\nDaily study time: {hours_per_day} hours."
50
+ if language == "Urdu":
51
+ prompt += "\nTranslate the plan into Urdu."
52
 
53
+ summary = summarizer(prompt, max_length=512, min_length=150, do_sample=False)
54
+ return summary[0]['summary_text']
55
 
56
+ except Exception as e:
57
+ return f"⚠️ Error: {str(e)}"
 
 
 
 
 
 
 
 
58
 
59
+ # Ask a question
60
+ def ask_question(file, question):
61
  try:
62
+ context = extract_text(file)
63
  result = qa_pipeline({"context": context, "question": question})
64
+ return result['answer']
65
  except Exception as e:
66
  return f"⚠️ Error: {str(e)}"
67
 
68
+ # Streamlit UI
69
+ st.sidebar.title("πŸ“š Study Assistant Options")
70
+ uploaded_file = st.sidebar.file_uploader("Upload syllabus (.txt, .docx, .pdf)", type=["txt", "docx", "pdf"])
71
+ study_hours = st.sidebar.number_input("Study hours per day", min_value=1, max_value=12, value=3)
72
+ exam_date = st.sidebar.text_input("Exam Date (YYYY-MM-DD)", value="2025-06-30")
73
+ language = st.sidebar.selectbox("Select Language", ["English", "Urdu"])
74
+
75
+ st.title("🧠 AI Study Plan & QA Assistant")
76
+
77
+ tab1, tab2 = st.tabs(["πŸ“… Generate Study Plan", "❓ Ask a Question"])
78
+
79
+ with tab1:
80
+ st.subheader("Generate a Personalized Study Plan")
81
+ if uploaded_file and st.button("Generate Study Plan"):
82
+ result = generate_plan(uploaded_file, study_hours, exam_date, language)
83
+ st.text_area("Study Plan", result, height=400)
84
+
85
+ with tab2:
86
+ st.subheader("Ask Questions from Uploaded Material")
87
+ question = st.text_input("Enter your question:")
88
+ if uploaded_file and question and st.button("Get Answer"):
89
+ answer = ask_question(uploaded_file, question)
90
+ st.text_area("Answer", answer, height=200)