Spaces:
Sleeping
Sleeping
Update app.py
Browse files38 unmodified lines394041424344454631 unmodified lines787980818283848586878889909192939495969798991001011021031041051061071081091101112 unmodified lines11411511611711811912012112212312412512612712812938 unmodified lineschunks.append(' '.join(words[i:i+chunk_size]))return chunksdef generate_mcqs_from_chunk(chunk: str, api_key: str) -> List[List[str]]:"""Generate MCQs from a text chunk using Gemini API"""models_to_try = ['gemini-2.0-flash-exp','gemini-1.5-flash',31 unmodified linesfor model_name in models_to_try:try:model = genai.GenerativeModel(model_name)response = model.generate_content(prompt)if response.text:breakexcept Exception as e:print(f"Error with {model_name}: {e}")continueif response and response.text:output = response.text.strip()lines = [line.strip() for line in output.splitlines() if line.strip()]for line in lines:# Skip any header lines that might still appearif ('Question' in line and 'OptionA' in line and 'OptionB' in line) or line.startswith('Question,'):continue# Skip empty lines or lines that don't look like MCQsif not line or line.count(',') < 5:continue# Parse CSV line using proper CSV parsingimport csvtry:# Use StringIO to parse the line as CSVcsv_reader = csv.reader([line])parts = next(csv_reader)# Ensure we have exactly 6 parts and the question is not emptyif len(parts) >= 6 and parts[0].strip() and not parts[0].lower().startswith('question'):2 unmodified lines# Validate that correct answer is A, B, C, or Dif cleaned_parts[5].upper() in ['A', 'B', 'C', 'D']:mcq_data.append(cleaned_parts)except csv.Error:# Fallback to simple split if CSV parsing failsparts = line.split(',')if len(parts) >= 6 and parts[0].strip() and not parts[0].lower().startswith('question'):cleaned_parts = [part.strip().strip('"') for part in parts[:6]]if cleaned_parts[5].upper() in ['A', 'B', 'C', 'D']:mcq_data.append(cleaned_parts)print(f"Generated {len(mcq_data)} MCQs from chunk")return mcq_datadef process_pdf_to_mcqs(pdf_file, api_key: str, chunk_size: int = 1500, progress=gr.Progress()) -> Tuple[str, str]:38 unmodified lines39404142434445464748495031 unmodified lines8283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251262 unmodified lines12913013113213313413513613713813914014114214314414514614714814915015115215315415538 unmodified lineschunks.append(' '.join(words[i:i+chunk_size]))return chunksdef generate_mcqs_from_chunk(chunk: str, api_key: str, chunk_number: int = 1) -> List[List[str]]:"""Generate MCQs from a text chunk using Gemini API"""print(f"\n=== PROCESSING CHUNK {chunk_number} ===")print(f"Chunk length: {len(chunk)} characters")print(f"Chunk preview: {chunk[:200]}...")models_to_try = ['gemini-2.0-flash-exp','gemini-1.5-flash',31 unmodified linesfor model_name in models_to_try:try:print(f"Trying model: {model_name}")model = genai.GenerativeModel(model_name)response = model.generate_content(prompt)if response.text:print(f"✅ Successfully used model: {model_name}")breakexcept Exception as e:print(f"❌ Error with {model_name}: {e}")continueif response and response.text:output = response.text.strip()print(f"\n--- RAW AI RESPONSE FOR CHUNK {chunk_number} ---")print(output)print("--- END RAW RESPONSE ---\n")lines = [line.strip() for line in output.splitlines() if line.strip()]print(f"Total non-empty lines in response: {len(lines)}")for idx, line in enumerate(lines):print(f"Processing line {idx + 1}: {line[:100]}...")# Skip any header lines that might still appearif ('Question' in line and 'OptionA' in line and 'OptionB' in line) or line.startswith('Question,'):print(f"❌ Skipped header line: {line[:50]}...")continue# Skip empty lines or lines that don't look like MCQsif not line or line.count(',') < 5:print(f"❌ Skipped invalid line (comma count: {line.count(',')}): {line[:50]}...")continue# Parse CSV line using proper CSV parsingtry:# Use StringIO to parse the line as CSVcsv_reader = csv.reader([line])parts = next(csv_reader)print(f"Parsed parts: {len(parts)} fields")# Ensure we have exactly 6 parts and the question is not emptyif len(parts) >= 6 and parts[0].strip() and not parts[0].lower().startswith('question'):2 unmodified lines# Validate that correct answer is A, B, C, or Dif cleaned_parts[5].upper() in ['A', 'B', 'C', 'D']:mcq_data.append(cleaned_parts)print(f"✅ Added MCQ: {cleaned_parts[0][:50]}... (Answer: {cleaned_parts[5]})")else:print(f"❌ Invalid answer format: {cleaned_parts[5]}")else:print(f"❌ Invalid parts count or empty question. Parts: {len(parts)}, First part: '{parts[0] if parts else 'N/A'}'")except csv.Error as e:print(f"❌ CSV parsing error: {e}")# Fallback to simple split if CSV parsing failsparts = line.split(',')if len(parts) >= 6 and parts[0].strip() and not parts[0].lower().startswith('question'):cleaned_parts = [part.strip().strip('"') for part in parts[:6]]if cleaned_parts[5].upper() in ['A', 'B', 'C', 'D']:mcq_data.append(cleaned_parts)print(f"✅ Added MCQ (fallback): {cleaned_parts[0][:50]}...")else:print(f"❌ Invalid answer format (fallback): {cleaned_parts[5]}")else:print(f"❌ No response received for chunk {chunk_number}")print(f"Generated {len(mcq_data)} MCQs from chunk {chunk_number}")return mcq_datadef process_pdf_to_mcqs(pdf_file, api_key: str, chunk_size: int = 1500, progress=gr.Progress()) -> Tuple[str, str]:
app.py+32-6