Hamzasajjad38 commited on
Commit
0c6e676
Β·
verified Β·
1 Parent(s): 05c8581

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -74
app.py CHANGED
@@ -3,10 +3,7 @@ import spacy
3
  import torch
4
  import subprocess
5
  import sys
6
- import tempfile
7
- import os
8
  from transformers import T5ForConditionalGeneration, AutoTokenizer
9
- from fpdf import FPDF
10
 
11
  subprocess.run(
12
  [sys.executable, "-m", "spacy", "download", "en_core_web_sm"],
@@ -18,24 +15,19 @@ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, use_fast=True)
18
  model = T5ForConditionalGeneration.from_pretrained(MODEL_ID)
19
  device = "cuda" if torch.cuda.is_available() else "cpu"
20
  model = model.to(device)
 
21
 
22
- nlp = spacy.load("en_core_web_sm")
23
-
24
- # ── Core generation function ──────────────────────────────────────────
25
  def generate_questions(passage, num_questions, question_type):
26
- if not passage.strip():
27
- return "⚠️ Please enter a passage.", None
28
-
29
- doc = nlp(passage)
30
 
31
- # Extract candidate answers: named entities first, then noun chunks
32
  candidates = [ent.text for ent in doc.ents]
 
33
  if len(candidates) < num_questions:
34
  candidates += [chunk.text for chunk in doc.noun_chunks]
35
 
36
- # Deduplicate and limit
37
- seen = set()
38
- unique = []
39
  for c in candidates:
40
  if c.lower() not in seen and len(c.split()) <= 5:
41
  seen.add(c.lower())
@@ -43,9 +35,9 @@ def generate_questions(passage, num_questions, question_type):
43
  candidates = unique[:num_questions]
44
 
45
  if not candidates:
46
- return "⚠️ Could not extract answer candidates from this passage. Try a longer or more detailed passage.", None
47
 
48
- output_lines = []
49
  for i, answer in enumerate(candidates):
50
  highlighted = passage.replace(answer, f"<hl> {answer} <hl>", 1)
51
  input_text = f"generate question: {highlighted}"
@@ -58,69 +50,40 @@ def generate_questions(passage, num_questions, question_type):
58
  if question_type == "True / False":
59
  question = f"True or False: {question.rstrip('?')}?"
60
 
61
- output_lines.append(f"Q{i+1}: {question}")
62
- output_lines.append(f" Answer: {answer}\n")
63
-
64
- return "\n".join(output_lines)
65
-
66
- # ── PDF export ────────────────────────────────────────────────────────
67
- def export_pdf(passage, num_questions, question_type):
68
- result = generate_questions(passage, num_questions, question_type)
69
- if result.startswith("⚠️"):
70
- return None
71
-
72
- pdf = FPDF()
73
- pdf.add_page()
74
- pdf.set_font("Helvetica", "B", 14)
75
- pdf.cell(0, 10, "Generated Question Paper", ln=True, align="C")
76
- pdf.ln(4)
77
- pdf.set_font("Helvetica", size=10)
78
- pdf.multi_cell(0, 6, f"Passage: {passage[:200]}...")
79
- pdf.ln(6)
80
- pdf.set_font("Helvetica", size=11)
81
- for line in result.split("\n"):
82
- pdf.multi_cell(0, 7, line)
83
- pdf.ln(4)
84
-
85
- tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
86
- pdf.output(tmp.name)
87
- return tmp.name
88
-
89
- # ── Gradio UI ─────────────────────────────────────────────────────────
90
- with gr.Blocks(title="Automatic Question Generator", theme=gr.themes.Soft()) as demo:
91
 
92
- gr.Markdown("""
93
- # 🧠 Automatic Question Generator
94
- **Fine-tuned T5-small on SQuAD 1.1** Β· Generates questions from any educational passage
95
- """)
96
 
97
  with gr.Row():
98
- with gr.Column(scale=2):
99
  passage_input = gr.Textbox(
100
  label="Input Passage",
101
  placeholder="Paste any educational paragraph here...",
102
  lines=8
103
  )
104
- with gr.Row():
105
- num_q = gr.Slider(1, 6, value=3, step=1, label="Number of questions")
106
- q_type = gr.Dropdown(
107
- ["Short answer", "True / False"],
108
- value="Short answer",
109
- label="Question type"
110
- )
111
- with gr.Row():
112
- gen_btn = gr.Button("⚑ Generate Questions", variant="primary")
113
- pdf_btn = gr.Button("πŸ“„ Export PDF")
114
-
115
- with gr.Column(scale=2):
116
- output_box = gr.Textbox(label="Generated Questions", lines=16, interactive=False)
117
- pdf_output = gr.File(label="Download PDF", visible=True)
118
-
119
- # Sample passages
120
  gr.Examples(
121
  examples=[
122
  ["Photosynthesis is a process used by plants to convert light energy into chemical energy stored in glucose. It occurs inside chloroplasts using chlorophyll to absorb sunlight.", 3, "Short answer"],
123
- ["The Industrial Revolution began in Britain in the late 18th century. The steam engine, invented by James Watt, transformed manufacturing, agriculture, and transportation across the country.", 3, "Short answer"],
124
  ["Machine learning is a subset of artificial intelligence where systems learn from data to improve performance without being explicitly programmed.", 2, "True / False"],
125
  ],
126
  inputs=[passage_input, num_q, q_type]
@@ -131,10 +94,5 @@ with gr.Blocks(title="Automatic Question Generator", theme=gr.themes.Soft()) as
131
  inputs=[passage_input, num_q, q_type],
132
  outputs=output_box
133
  )
134
- pdf_btn.click(
135
- fn=export_pdf,
136
- inputs=[passage_input, num_q, q_type],
137
- outputs=pdf_output
138
- )
139
 
140
- demo.launch(share=False, server_name="0.0.0.0")
 
3
  import torch
4
  import subprocess
5
  import sys
 
 
6
  from transformers import T5ForConditionalGeneration, AutoTokenizer
 
7
 
8
  subprocess.run(
9
  [sys.executable, "-m", "spacy", "download", "en_core_web_sm"],
 
15
  model = T5ForConditionalGeneration.from_pretrained(MODEL_ID)
16
  device = "cuda" if torch.cuda.is_available() else "cpu"
17
  model = model.to(device)
18
+ nlp = spacy.load("en_core_web_sm")
19
 
 
 
 
20
  def generate_questions(passage, num_questions, question_type):
21
+ if not passage.strip() or len(passage) < 30:
22
+ return "⚠️ Please enter a longer passage."
 
 
23
 
24
+ doc = nlp(passage)
25
  candidates = [ent.text for ent in doc.ents]
26
+
27
  if len(candidates) < num_questions:
28
  candidates += [chunk.text for chunk in doc.noun_chunks]
29
 
30
+ seen, unique = set(), []
 
 
31
  for c in candidates:
32
  if c.lower() not in seen and len(c.split()) <= 5:
33
  seen.add(c.lower())
 
35
  candidates = unique[:num_questions]
36
 
37
  if not candidates:
38
+ return "⚠️ Could not extract candidates. Try a longer passage."
39
 
40
+ lines = []
41
  for i, answer in enumerate(candidates):
42
  highlighted = passage.replace(answer, f"<hl> {answer} <hl>", 1)
43
  input_text = f"generate question: {highlighted}"
 
50
  if question_type == "True / False":
51
  question = f"True or False: {question.rstrip('?')}?"
52
 
53
+ lines.append(f"Q{i+1}: {question}")
54
+ lines.append(f" Answer: {answer}\n")
55
+
56
+ return "\n".join(lines)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
+ with gr.Blocks(title="Automatic Question Generator", theme=gr.themes.Soft()) as demo:
59
+ gr.Markdown("# 🧠 Automatic Question Generator\n**Fine-tuned T5-small on SQuAD 1.1**")
 
 
60
 
61
  with gr.Row():
62
+ with gr.Column():
63
  passage_input = gr.Textbox(
64
  label="Input Passage",
65
  placeholder="Paste any educational paragraph here...",
66
  lines=8
67
  )
68
+ num_q = gr.Slider(1, 6, value=3, step=1, label="Number of questions")
69
+ q_type = gr.Dropdown(
70
+ ["Short answer", "True / False"],
71
+ value="Short answer",
72
+ label="Question type"
73
+ )
74
+ gen_btn = gr.Button("⚑ Generate Questions", variant="primary")
75
+
76
+ with gr.Column():
77
+ output_box = gr.Textbox(
78
+ label="Generated Questions",
79
+ lines=16,
80
+ interactive=False
81
+ )
82
+
 
83
  gr.Examples(
84
  examples=[
85
  ["Photosynthesis is a process used by plants to convert light energy into chemical energy stored in glucose. It occurs inside chloroplasts using chlorophyll to absorb sunlight.", 3, "Short answer"],
86
+ ["The Industrial Revolution began in Britain in the late 18th century. The steam engine invented by James Watt transformed manufacturing and transportation.", 3, "Short answer"],
87
  ["Machine learning is a subset of artificial intelligence where systems learn from data to improve performance without being explicitly programmed.", 2, "True / False"],
88
  ],
89
  inputs=[passage_input, num_q, q_type]
 
94
  inputs=[passage_input, num_q, q_type],
95
  outputs=output_box
96
  )
 
 
 
 
 
97
 
98
+ demo.launch(server_name="0.0.0.0", server_port=7860)