Mehdi commited on
Commit ·
83ec3f5
1
Parent(s): 08b63c1
feat: switch to MiniCPM4-8B, add robustness, score tracker, language selector
Browse files- model/llm.py: upgrade to MiniCPM4-8B with bfloat16 and chat template
- requirements.txt: relax transformers pin to >=4.50.0
- core/parser.py: handle corrupt/scanned/empty PDFs with clear errors
- app.py: graceful error handling in all pipeline steps
- app.py: session score tracker (correct/total with verdict parsing)
- app.py: FR/EN language selector wired to question and evaluation prompts
- core/questioner.py: language param in prompt
- core/evaluator.py: language param in prompt
Files changed (7)
- TASK.md+4-4
- app.py+57-19
- core/evaluator.py+3-1
- core/parser.py+13-2
- core/questioner.py+3-2
- model/llm.py+14-10
- requirements.txt+1-1
6 unmodified lines789101112135 unmodified lines19202122232425261 unmodified line282930313233346 unmodified lines- core/chunker.py: paragraph-based text chunking with min/max word caps- core/questioner.py: LLM-based question generation with professor prompt- core/evaluator.py: LLM-based answer evaluation with tutor prompt- model/llm.py: MiniCPM4-8B singleton wrapper via HuggingFace Transformers- app.py: full Gradio UI with PDF upload, question generation, answer evaluation- requirements.txt: all dependencies listed- README.md: project description and file structure5 unmodified lines### 🧪 Testing & Bug Fixes- [ ] End-to-end test: upload real PDF → load → generate question → answer → get feedback- [ ] Handle edge cases: empty PDF, scanned PDF (no text), very short PDF- [ ] Handle model loading errors gracefully in the UI- [ ] Test with multiple PDF types (slides, textbook chapters, lecture notes)- [ ] Fix any ZeroGPU cold start issues (model takes time to load)1 unmodified line- [ ] Replace default Gradio theme with fully custom CSS using gr.Server- [ ] Add PaperProf logo and branding- [ ] Add progress indicator when model is generating- [ ] Add session score tracker (X/Y correct answers)- [ ] Add difficulty selector (Easy / Normal / Hard mode)- [ ] Add language selector (French / English)- [ ] Show source chunk used for the question (collapsible)6 unmodified lines789101112135 unmodified lines19202122232425261 unmodified line282930313233346 unmodified lines- core/chunker.py: paragraph-based text chunking with min/max word caps- core/questioner.py: LLM-based question generation with professor prompt- core/evaluator.py: LLM-based answer evaluation with tutor prompt- model/llm.py: MiniCPM4-8B singleton wrapper via HuggingFace Transformers (bfloat16, chat template)- app.py: full Gradio UI with PDF upload, question generation, answer evaluation- requirements.txt: all dependencies listed- README.md: project description and file structure5 unmodified lines### 🧪 Testing & Bug Fixes- [ ] End-to-end test: upload real PDF → load → generate question → answer → get feedback- [x] Handle edge cases: empty PDF, scanned PDF (no text), very short PDF- [x] Handle model loading errors gracefully in the UI- [ ] Test with multiple PDF types (slides, textbook chapters, lecture notes)- [ ] Fix any ZeroGPU cold start issues (model takes time to load)1 unmodified line- [ ] Replace default Gradio theme with fully custom CSS using gr.Server- [ ] Add PaperProf logo and branding- [ ] Add progress indicator when model is generating- [x] Add session score tracker (X/Y correct answers)- [ ] Add difficulty selector (Easy / Normal / Hard mode)- [ ] Add language selector (French / English)- [ ] Show source chunk used for the question (collapsible)
24 unmodified lines2526272829303132333435363738394041424344454647484950515253549 unmodified lines6465666768697071727374757 unmodified lines838485868788899091929394959697989924 unmodified lines# State helpers# ---------------------------------------------------------------------------def load_pdf(pdf_file):"""Parse the PDF and split it into chunks; return a status message."""text = extract_text(pdf_file.name)chunks = chunk_text(text)return chunks, f"Loaded {len(chunks)} thematic chunks from your PDF."@spaces.GPU(duration=60)def new_question(chunks):"""Pick a random chunk and generate a question from it."""if not chunks:return "", "", "Please upload a PDF first."chunk = random.choice(chunks)question = generate_question(chunk)return question, chunk, ""@spaces.GPU(duration=120)def submit_answer(question, chunk, student_answer):"""Evaluate the student's answer and return feedback."""if not question:return "Generate a question first."feedback = evaluate_answer(question, chunk, student_answer)return feedback# ---------------------------------------------------------------------------9 unmodified lineschunks_state = gr.State([])chunk_state = gr.State("")with gr.Row():pdf_input = gr.File(label="Upload course PDF", file_types=[".pdf"])load_btn = gr.Button("Load PDF")load_status = gr.Textbox(label="Status", interactive=False)with gr.Row():question_box = gr.Textbox(label="Question", interactive=False, lines=4)7 unmodified linesload_btn.click(load_pdf,inputs=[pdf_input],outputs=[chunks_state, load_status],)new_q_btn.click(new_question,inputs=[chunks_state],outputs=[question_box, chunk_state, feedback_box],)submit_btn.click(submit_answer,inputs=[question_box, chunk_state, answer_box],outputs=[feedback_box],)if __name__ == "__main__":24 unmodified lines2526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586879 unmodified lines9798991001011021031041051061071081091101111121137 unmodified lines12112212312412512612712812913013113213313413513613724 unmodified lines# State helpers# ---------------------------------------------------------------------------def _parse_verdict(feedback: str) -> bool:"""Return True if the feedback verdict is 'Correct' (not partial/incorrect)."""for line in feedback.splitlines():low = line.lower()if "verdict" in low:return "correct" in low and "partially" not in low and "incorrect" not in lowreturn Falsedef _score_label(correct: int, total: int) -> str:return f"Score: {correct}/{total}" if total > 0 else "Score: —"def load_pdf(pdf_file):"""Parse the PDF and split it into chunks; return a status message and reset score."""if pdf_file is None:return [], "No file uploaded.", 0, 0try:text = extract_text(pdf_file.name)chunks = chunk_text(text)except ValueError as e:return [], f"Error: {e}", 0, 0except Exception as e:return [], f"Unexpected error reading PDF: {e}", 0, 0if not chunks:return [], "PDF loaded but no usable text chunks found (document too short?).", 0, 0return chunks, f"Loaded {len(chunks)} thematic chunks from your PDF.", 0, 0@spaces.GPU(duration=60)def new_question(chunks, language):"""Pick a random chunk and generate a question from it."""if not chunks:return "", "", "Please upload a PDF first."try:chunk = random.choice(chunks)question = generate_question(chunk, language=language)return question, chunk, ""except Exception as e:return "", "", f"Error generating question: {e}"@spaces.GPU(duration=120)def submit_answer(question, chunk, student_answer, correct, total, language):"""Evaluate the student's answer, update score, and return feedback."""if not question:return "Generate a question first.", correct, total, _score_label(correct, total)if not student_answer.strip():return "Please write an answer before submitting.", correct, total, _score_label(correct, total)try:feedback = evaluate_answer(question, chunk, student_answer, language=language)total += 1if _parse_verdict(feedback):correct += 1return feedback, correct, total, _score_label(correct, total)except Exception as e:return f"Error evaluating answer: {e}", correct, total, _score_label(correct, total)# ---------------------------------------------------------------------------9 unmodified lineschunks_state = gr.State([])chunk_state = gr.State("")correct_state = gr.State(0)total_state = gr.State(0)with gr.Row():pdf_input = gr.File(label="Upload course PDF", file_types=[".pdf"])load_btn = gr.Button("Load PDF")language_selector = gr.Radio(["English", "Français"], value="English", label="Language")with gr.Row():load_status = gr.Textbox(label="Status", interactive=False, scale=4)score_box = gr.Textbox(label="Score", value="Score: —", interactive=False, scale=1)with gr.Row():question_box = gr.Textbox(label="Question", interactive=False, lines=4)7 unmodified linesload_btn.click(load_pdf,inputs=[pdf_input],outputs=[chunks_state, load_status, correct_state, total_state],).then(lambda: "Score: —", outputs=[score_box])new_q_btn.click(new_question,inputs=[chunks_state, language_selector],outputs=[question_box, chunk_state, feedback_box],)submit_btn.click(submit_answer,inputs=[question_box, chunk_state, answer_box, correct_state, total_state, language_selector],outputs=[feedback_box, correct_state, total_state, score_box],)if __name__ == "__main__":
19 unmodified lines20212223242513 unmodified lines39404142434445464748495019 unmodified lines_PROMPT_TEMPLATE = """\You are a patient and constructive university tutor.Source material:{chunk}13 unmodified linesBe encouraging and specific."""def evaluate_answer(question: str, chunk: str, student_answer: str) -> str:"""Return structured feedback for *student_answer* given *question* and *chunk*."""llm = get_llm()prompt = _PROMPT_TEMPLATE.format(chunk=chunk.strip(),question=question.strip(),answer=student_answer.strip(),)return llm.generate(prompt).strip()19 unmodified lines2021222324252613 unmodified lines4041424344454647484950515219 unmodified lines_PROMPT_TEMPLATE = """\You are a patient and constructive university tutor.Write your entire response in {language}.Source material:{chunk}13 unmodified linesBe encouraging and specific."""def evaluate_answer(question: str, chunk: str, student_answer: str, language: str = "English") -> str:"""Return structured feedback for *student_answer* given *question* and *chunk*."""llm = get_llm()prompt = _PROMPT_TEMPLATE.format(chunk=chunk.strip(),question=question.strip(),answer=student_answer.strip(),language=language,)return llm.generate(prompt).strip()
14 unmodified lines1516171819202114 unmodified linesdef extract_text(pdf_path: str) -> str:"""Return the concatenated plain text of every page in *pdf_path*."""doc = fitz.open(pdf_path)pages = [page.get_text() for page in doc]doc.close()return "\n".join(pages)14 unmodified lines15161718192021222324252627282930313214 unmodified linesdef extract_text(pdf_path: str) -> str:"""Return the concatenated plain text of every page in *pdf_path*."""try:doc = fitz.open(pdf_path)except Exception as e:raise ValueError(f"Cannot open PDF: {e}")pages = [page.get_text() for page in doc]doc.close()text = "\n".join(pages)if not text.strip():raise ValueError("No text found in this PDF. It may be a scanned document (image-only). ""Try a PDF with a text layer.")return text
18 unmodified lines1920212223242 unmodified lines272829303132333418 unmodified linesYou are a university professor creating exam questions.Given the following excerpt from a course, write ONE clear, open-ended question \that tests deep understanding of the key concept.Output only the question — no preamble, no numbering.Excerpt:2 unmodified linesQuestion:"""def generate_question(chunk: str) -> str:"""Return a single study question generated from *chunk*."""llm = get_llm()prompt = _PROMPT_TEMPLATE.format(chunk=chunk.strip())return llm.generate(prompt).strip()18 unmodified lines192021222324252 unmodified lines282930313233343518 unmodified linesYou are a university professor creating exam questions.Given the following excerpt from a course, write ONE clear, open-ended question \that tests deep understanding of the key concept.Write the question in {language}.Output only the question — no preamble, no numbering.Excerpt:2 unmodified linesQuestion:"""def generate_question(chunk: str, language: str = "English") -> str:"""Return a single study question generated from *chunk*."""llm = get_llm()prompt = _PROMPT_TEMPLATE.format(chunk=chunk.strip(), language=language)return llm.generate(prompt).strip()
6 unmodified lines789101112131415161718196 unmodified lines262728293031322 unmodified lines35363738394041424344454647484950515253545556576 unmodified linesabout the underlying model loading or tokenisation details.Model choice:openbmb/MiniCPM4-8B — a compact yet capable instruction-tuned modeldesigned for long-context reasoning, making it well suited forquestion generation and answer evaluation over course material.Environment variables:PAPERPROF_MODEL Override the default model ID (useful for testing with asmaller model locally, e.g. "openbmb/MiniCPM3-4B").PAPERPROF_DEVICE "cuda", "mps", or "cpu" (default: auto-detected).Public API:6 unmodified linesfrom functools import lru_cachefrom transformers import AutoTokenizer, AutoModelForCausalLM, pipelineDEFAULT_MODEL_ID = "openbmb/MiniCPM3-4B"DEFAULT_MAX_NEW_TOKENS = 5122 unmodified linesdef __init__(self, model_id: str, device: str):self.model_id = model_idtokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained(model_id,torch_dtype=torch.float16,device_map=device,trust_remote_code=True,)self._pipe = pipeline("text-generation",model=model,tokenizer=tokenizer,)def generate(self, prompt: str, max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS) -> str:"""Run *prompt* through the model and return the generated text only."""output = self._pipe(prompt,max_new_tokens=max_new_tokens,do_sample=False,return_full_text=False,6 unmodified lines789101112131415161718196 unmodified lines262728293031322 unmodified lines3536373839404142434445464748495051525354555657585960616 unmodified linesabout the underlying model loading or tokenisation details.Model choice:openbmb/MiniCPM4-8B — instruction-tuned model with long-context reasoning,well suited for question generation and answer evaluation over course material.Requires transformers >= 4.50.0.Environment variables:PAPERPROF_MODEL Override the default model ID (e.g. "openbmb/MiniCPM3-4B"for a smaller fallback during local testing).PAPERPROF_DEVICE "cuda", "mps", or "cpu" (default: auto-detected).Public API:6 unmodified linesfrom functools import lru_cachefrom transformers import AutoTokenizer, AutoModelForCausalLM, pipelineDEFAULT_MODEL_ID = "openbmb/MiniCPM4-8B"DEFAULT_MAX_NEW_TOKENS = 5122 unmodified linesdef __init__(self, model_id: str, device: str):self.model_id = model_idself._tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained(model_id,dtype=torch.bfloat16,device_map=device,trust_remote_code=True,)self._pipe = pipeline("text-generation",model=model,tokenizer=self._tokenizer,)def generate(self, prompt: str, max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS) -> str:"""Run *prompt* through the model and return the generated text only."""messages = [{"role": "user", "content": prompt}]text = self._tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)output = self._pipe(text,max_new_tokens=max_new_tokens,do_sample=False,return_full_text=False,
5 unmodified lines67891011125 unmodified lines# LLM inferencetorch>=2.3.0transformers==4.44.0accelerate>=0.31.0sentencepiece>=0.2.0protobuf>=4.25.05 unmodified lines67891011125 unmodified lines# LLM inferencetorch>=2.3.0transformers>=4.50.0accelerate>=0.31.0sentencepiece>=0.2.0protobuf>=4.25.0
TASK.md+4-4
app.py+57-19
core/evaluator.py+3-1
core/parser.py+13-2
core/questioner.py+3-2
model/llm.py+14-10
requirements.txt+1-1