gopalaKrishna1236 commited on
Commit
b4c392a
Β·
verified Β·
1 Parent(s): 789f4c5

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +62 -66
  2. requirements.txt +1 -2
app.py CHANGED
@@ -1,89 +1,85 @@
1
  import os, requests
 
2
  from pypdf import PdfReader
3
- import streamlit as st
4
 
5
- # --- Setup ---
6
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
7
- if not OPENAI_API_KEY:
8
- st.warning("⚠️ Set your OpenAI key using the next cell before generating.")
9
  OPENAI_URL = "https://api.openai.com/v1/chat/completions"
10
  MODEL = "gpt-4o-mini"
11
  MAX_PAGES, MAX_CHARS = 15, 10000
12
 
13
- # --- UI ---
14
- st.set_page_config(page_title="StudySnap", page_icon="πŸ“š", layout="centered")
15
- st.title("πŸ“š StudySnap β€” Summaries + MCQs")
16
- tab1, tab2 = st.tabs(["Paste Text", "Upload PDF"])
17
- length = st.radio("Output length:", ["short","medium","long"], index=1, horizontal=True)
 
 
 
 
18
 
19
- with tab1:
20
- text_input = st.text_area("Paste your notes/article here:", height=220)
21
-
22
- with tab2:
23
- pdf_file = st.file_uploader("Upload PDF (first 15 pages only)", type=["pdf"])
24
-
25
- # --- Helpers ---
26
- def extract_pdf_text(file):
27
- r = PdfReader(file)
28
- pages = min(len(r.pages), MAX_PAGES)
29
- text = "\n".join(r.pages[i].extract_text() or "" for i in range(pages))
30
- lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
31
- return "\n".join(lines)[:MAX_CHARS]
32
-
33
- def call_openai(system, user):
34
  if not OPENAI_API_KEY:
35
- raise RuntimeError("API key missing.")
36
  headers = {"Authorization": f"Bearer {OPENAI_API_KEY}", "Content-Type": "application/json"}
37
- body = {"model": MODEL, "messages":[{"role":"system","content":system},{"role":"user","content":user}], "temperature":0.2}
 
 
 
 
 
 
 
38
  r = requests.post(OPENAI_URL, headers=headers, json=body, timeout=60)
39
  r.raise_for_status()
40
  return r.json()["choices"][0]["message"]["content"]
41
 
42
- # --- AI Wrappers ---
43
- def summarize(txt, length):
44
- sys = ("You are a precise study assistant. Summarize in bullet points for MBA-level students. "
45
- "short=5 bullets, medium=8–10, long=12–15.")
46
- usr = f"Length: {length}\n\nCONTENT:\n{txt[:MAX_CHARS]}"
47
  return call_openai(sys, usr)
48
 
49
- def make_mcqs(txt):
50
- sys = ("Create 10 single-answer MCQs with 4 options (A–D), plus 'Answer: X' and a short explanation. "
51
- "Keep options plausible, style professional.")
52
- usr = txt[:8000]
 
53
  return call_openai(sys, usr)
54
 
55
- # --- Main ---
56
- if st.button("Generate", type="primary"):
57
- if pdf_file:
58
- content = extract_pdf_text(pdf_file)
59
- title = pdf_file.name
60
- elif text_input.strip():
61
- content = text_input.strip()
62
- title = "Pasted Text"
63
- else:
64
- st.warning("Paste text or upload a PDF first.")
65
- st.stop()
66
 
67
- if len(content) < 200:
68
- st.warning("Input too short.")
69
- st.stop()
 
 
 
 
 
70
 
71
- with st.spinner("Summarizing..."):
72
- try:
73
- summary = summarize(content, length)
74
- st.success("βœ… Summary Ready!")
75
- st.markdown(summary)
76
- except Exception as e:
77
- st.error(f"Summarization failed: {e}")
78
- st.stop()
79
 
80
- st.divider()
81
- st.subheader("🧠 Practice β€” 10 MCQs")
82
- with st.spinner("Generating questions..."):
83
- try:
84
- mcqs = make_mcqs(content)
85
- st.markdown(mcqs)
86
- except Exception as e:
87
- st.error(f"MCQ generation failed: {e}")
 
 
88
 
89
- st.caption("MVP limits: 15 pages / 10k characters. We never store your files.")
 
 
1
  import os, requests
2
+ import gradio as gr
3
  from pypdf import PdfReader
 
4
 
 
5
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
 
 
6
  OPENAI_URL = "https://api.openai.com/v1/chat/completions"
7
  MODEL = "gpt-4o-mini"
8
  MAX_PAGES, MAX_CHARS = 15, 10000
9
 
10
+ def extract_text(pdf_file):
11
+ try:
12
+ reader = PdfReader(pdf_file)
13
+ pages = min(len(reader.pages), MAX_PAGES)
14
+ text = "\n".join((reader.pages[i].extract_text() or "") for i in range(pages))
15
+ lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
16
+ return "\n".join(lines)[:MAX_CHARS]
17
+ except Exception:
18
+ return ""
19
 
20
+ def call_openai(system_prompt, user_content):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  if not OPENAI_API_KEY:
22
+ raise RuntimeError("Missing OPENAI_API_KEY (set it in Space β†’ Settings β†’ Secrets).")
23
  headers = {"Authorization": f"Bearer {OPENAI_API_KEY}", "Content-Type": "application/json"}
24
+ body = {
25
+ "model": MODEL,
26
+ "messages": [
27
+ {"role": "system", "content": system_prompt},
28
+ {"role": "user", "content": user_content}
29
+ ],
30
+ "temperature": 0.2
31
+ }
32
  r = requests.post(OPENAI_URL, headers=headers, json=body, timeout=60)
33
  r.raise_for_status()
34
  return r.json()["choices"][0]["message"]["content"]
35
 
36
+ def summarize(content, length):
37
+ sys = ("You are a precise study assistant for MBA-level students. "
38
+ "Summarize in clean bullet points; short=5 bullets, medium=8-10, long=12-15.")
39
+ usr = f"Length: {length}\n\nCONTENT:\n{content[:MAX_CHARS]}"
 
40
  return call_openai(sys, usr)
41
 
42
+ def mcqs(content):
43
+ sys = ("Create 10 single-answer MCQs from the content. "
44
+ "Each item: question + 4 options labeled A)–D), then a line 'Answer: X' "
45
+ "and a one-sentence explanation.")
46
+ usr = f"CONTENT:\n{content[:8000]}"
47
  return call_openai(sys, usr)
48
 
49
+ def generate(pasted_text, pdf_file, length):
50
+ source = ""
51
+ if pdf_file is not None:
52
+ source = extract_text(pdf_file)
53
+ if not source and pasted_text:
54
+ source = pasted_text.strip()[:MAX_CHARS]
55
+ if not source:
56
+ return "❌ Paste text or upload a PDF.", ""
57
+ if len(source) < 200:
58
+ return "❌ Input too short.", ""
 
59
 
60
+ try:
61
+ summary_md = summarize(source, length)
62
+ except Exception as e:
63
+ return f"❌ Summarization failed: {e}", ""
64
+ try:
65
+ mcq_md = mcqs(source)
66
+ except Exception as e:
67
+ mcq_md = f"❌ MCQ generation failed: {e}"
68
 
69
+ summary_md = f"### πŸ“„ Summary\n\n{summary_md}"
70
+ mcq_md = f"### 🧠 Practice β€” 10 MCQs\n\n{mcq_md}"
71
+ return summary_md, mcq_md
 
 
 
 
 
72
 
73
+ with gr.Blocks(title="StudySnap β€” Summaries + MCQs") as demo:
74
+ gr.Markdown("# πŸ“š StudySnap\nUpload a PDF or paste text. Get a clean summary + 10 MCQs.")
75
+ with gr.Row():
76
+ pasted = gr.Textbox(label="Paste Text", lines=10, placeholder="Paste your lecture notes or article here…")
77
+ pdf = gr.File(label="Upload PDF (first 15 pages)", file_types=[".pdf"])
78
+ length = gr.Radio(["short", "medium", "long"], value="medium", label="Output length")
79
+ btn = gr.Button("Generate", variant="primary")
80
+ out_summary = gr.Markdown()
81
+ out_mcq = gr.Markdown()
82
+ btn.click(fn=generate, inputs=[pasted, pdf, length], outputs=[out_summary, out_mcq])
83
 
84
+ if __name__ == "__main__":
85
+ demo.launch()
requirements.txt CHANGED
@@ -1,4 +1,3 @@
1
- streamlit>=1.36
2
  pypdf>=4.2
3
- python-docx>=1.1
4
  requests>=2.32
 
1
+ gradio>=4.44
2
  pypdf>=4.2
 
3
  requests>=2.32