Spaces:
Sleeping
Sleeping
Update src/core/QuizEngine.py
Browse files24 unmodified lines2526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818224 unmodified lines}# --- MODE 2: DOCUMENTS (NEW) ---def get_document_context(self, username):"""Picks a random file, reads it, and selects a random segment.Returns the segment to be used as the 'Answer Key'."""user_dir = os.path.join(self.source_dir, username)if not os.path.exists(user_dir):return None# 1. Get list of text/md filesfiles = [f for f in os.listdir(user_dir) if f.lower().endswith(('.txt', '.md'))]if not files:return None# 2. Pick a random fileselected_file = random.choice(files)file_path = os.path.join(user_dir, selected_file)try:with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:text = f.read()# 3. Split into rough paragraphs (double line break)# Filter out short/empty paragraphs to avoid bad questionsparagraphs = [p.strip() for p in text.split('\n\n') if len(p.strip()) > 200]if not paragraphs:return None# 4. Pick a random paragraphselected_context = random.choice(paragraphs)return {"type": "document","source_file": selected_file,"context_text": selected_context}except Exception as e:self.logger.error(f"Error fetching quiz context: {e}")return None# --- PROMPT CONSTRUCTORS ---def construct_question_generation_prompt(self, context_text):"""Asks the LLM to write the question for us."""return (f"Act as a US Navy Engineering Duty Officer Board Examiner.\n"f"Read the following technical excerpt from a Navy reference:\n\n"f"'{context_text}'\n\n"f"TASK: Generate a single, tough, short-answer board question based ONLY on this text.\n"f"The question should test recall of specific details (e.g., 'What are the 3 documents required for...').\n"f"OUTPUT: Just the question text. No preamble.")def construct_grading_prompt(self, question, answer, context_text):24 unmodified lines2526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939424 unmodified lines}# --- MODE 2: DOCUMENTS (NEW) ---# ... inside QuizEngine class ...def get_document_context(self, username):user_dir = os.path.join(self.source_dir, username)if not os.path.exists(user_dir): return None# 1. Get filesfiles = [f for f in os.listdir(user_dir) if f.lower().endswith(('.txt', '.md'))]if not files: return None# Retry Loop: Try up to 5 times to find a "worthy" chunkfor attempt in range(5):selected_file = random.choice(files)try:with open(os.path.join(user_dir, selected_file), 'r', encoding='utf-8', errors='ignore') as f:text = f.read()# DEFENSE 1: Aggressive Heuristic Filtering# Split by double newline (paragraphs)paragraphs = text.split('\n\n')candidates = []for p in paragraphs:p = p.strip()# A. Too short?if len(p) < 250: continue# B. Looks like a list item or table row? (starts with number/bullet)if p[0].isdigit() or p.startswith(('-', '*', '•')): continue# C. Looks like administrative noise?if "intentionally left blank" in p.lower(): continuecandidates.append(p)if not candidates: continue# Pick a random survivorselected_context = random.choice(candidates)return {"type": "document","source_file": selected_file,"context_text": selected_context}except Exception as e:self.logger.error(f"Error fetching context: {e}")continuereturn None # Failed to find good text after 5 triesdef construct_question_generation_prompt(self, context_text):"""DEFENSE 2: Explicit Instructions to Ignore Trivia"""return (f"Act as a US Navy Engineering Duty Officer Board Examiner.\n"f"Review the following source text for suitability:\n"f"'''{context_text}'''\n\n"f"DECISION LOGIC:\n"f"1. Does this text contain a specific Engineering Concept, Responsibility, or Procedural Rule?\n"f"2. Is it free of pure administrative trivia (dates, page numbers, formatting rules)?\n\n"f"IF NO: Output the word 'SKIP'.\n"f"IF YES: Generate a difficult, scenario-based question that tests the candidate's understanding of the concept. "f"Do not ask 'What does the text say?'. Ask 'How would you apply...?' or 'What are the requirements for...?'\n\n"f"OUTPUT: Just the question text.")def construct_grading_prompt(self, question, answer, context_text):
src/core/QuizEngine.py+51-39