Spaces:
Sleeping
Sleeping
Update app.py
Browse files30 unmodified lines313233343536371 unmodified line394041424344456 unmodified lines5253545556575893 unmodified lines15215315415515615715823 unmodified lines18218318418518618718818919019119222 unmodified lines21521621721821922022113 unmodified lines23523623723823924024124224311 unmodified lines25525625725825926026126226326426526626715 unmodified lines2832842852862872882896 unmodified lines29629729829930030130230330430530630730830931031130 unmodified linesexcept Exception as e:return f"Error extracting text: {str(e)}"def chunk_text(text: str, chunk_size: int = 1500) -> List[str]:"""Split text into chunks for processing"""words = text.split()chunks = []1 unmodified linechunks.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")6 unmodified lines]prompt = f"""Generate exactly 10 multiple choice questions from the following text.Each question must have:- A clear, specific question- 4 options labeled A, B, C, D93 unmodified linesprint(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]:"""Main function to process PDF and generate MCQs"""if not api_key:return "❌ Please provide your Gemini API key", None23 unmodified linesfor i, chunk in enumerate(chunks):progress((0.2 + (i / total_chunks) * 0.7), desc=f"Processing chunk {i+1}/{total_chunks}...")chunk_mcqs = generate_mcqs_from_chunk(chunk, api_key)all_mcq_data.extend(chunk_mcqs)# Add small delay to avoid rate limitingtime.sleep(1)progress(0.95, desc="Creating Excel file...")22 unmodified linesprogress(1.0, desc="Complete!")success_message = f"✅ Successfully generated {len(unique_mcq_data)} unique MCQs from {total_chunks} text chunks!"return success_message, temp_file.name13 unmodified lines1. Get your Gemini API key from [Google AI Studio](https://aistudio.google.com/app/apikey)2. Enter your API key below3. Upload your PDF file4. Adjust chunk size if needed (larger = fewer API calls, smaller = more focused questions)5. Click "Generate MCQs" and wait for processing6. Download the generated Excel file with your MCQs""")11 unmodified lines)chunk_size_input = gr.Slider(minimum=500,maximum=3000,value=1500,step=100,label="📝 Chunk Size (words per processing batch)")generate_btn = gr.Button("🚀 Generate MCQs",variant="primary",15 unmodified lines# Event handlersgenerate_btn.click(fn=process_pdf_to_mcqs,inputs=[pdf_input, api_key_input, chunk_size_input],outputs=[status_output, download_file],show_progress=True).then(6 unmodified lines"""## 📋 Features:- **OCR Text Extraction**: Converts PDF pages to images and extracts text- **Smart Chunking**: Breaks large documents into manageable pieces- **Multiple AI Models**: Automatically tries different Gemini models for best results- **Excel Output**: Download MCQs in a formatted Excel file- **Progress Tracking**: Real-time updates on processing status## ⚠️ Notes:- Processing time depends on PDF length and complexity- Large PDFs are processed in chunks to avoid timeouts- Make sure your PDF contains readable text (not just images)- API key is not stored and only used for your session""")30 unmodified lines313233343536371 unmodified line394041424344456 unmodified lines5253545556575893 unmodified lines15215315415515615715823 unmodified lines18218318418518618718818919019119222 unmodified lines21521621721821922022113 unmodified lines23523623723823924024124224324411 unmodified lines25625725825926026126226326426526626726826927027127227327427527615 unmodified lines2922932942952962972986 unmodified lines30530630730830931031131231331431531631731831932032132232330 unmodified linesexcept Exception as e:return f"Error extracting text: {str(e)}"def chunk_text(text: str, chunk_size: int = 500) -> List[str]: # Changed default to 500 for more chunks/MCQs"""Split text into chunks for processing"""words = text.split()chunks = []1 unmodified linechunks.append(' '.join(words[i:i+chunk_size]))return chunksdef generate_mcqs_from_chunk(chunk: str, api_key: str, chunk_number: int = 1, mcqs_per_chunk: int = 20) -> List[List[str]]: # Added mcqs_per_chunk param, default 20"""Generate MCQs from a text chunk using Gemini API"""print(f"\n=== PROCESSING CHUNK {chunk_number} ===")print(f"Chunk length: {len(chunk)} characters")6 unmodified lines]prompt = f"""Generate exactly {mcqs_per_chunk} multiple choice questions from the following text.Each question must have:- A clear, specific question- 4 options labeled A, B, C, D93 unmodified linesprint(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 = 500, mcqs_per_chunk: int = 20, progress=gr.Progress()) -> Tuple[str, str]: # Added mcqs_per_chunk param, default 20"""Main function to process PDF and generate MCQs"""if not api_key:return "❌ Please provide your Gemini API key", None23 unmodified linesfor i, chunk in enumerate(chunks):progress((0.2 + (i / total_chunks) * 0.7), desc=f"Processing chunk {i+1}/{total_chunks}...")chunk_mcqs = generate_mcqs_from_chunk(chunk, api_key, i+1, mcqs_per_chunk)all_mcq_data.extend(chunk_mcqs)# Reduced delay to 0.5s for faster processing (to maximize MCQs, but monitor rate limits)time.sleep(0.5)progress(0.95, desc="Creating Excel file...")22 unmodified linesprogress(1.0, desc="Complete!")success_message = f"✅ Successfully generated {len(unique_mcq_data)} unique MCQs from {total_chunks} text chunks ({mcqs_per_chunk} targeted per chunk)!"return success_message, temp_file.name13 unmodified lines1. Get your Gemini API key from [Google AI Studio](https://aistudio.google.com/app/apikey)2. Enter your API key below3. Upload your PDF file4. Adjust chunk size if needed (smaller = more chunks/MCQs, but slower; default 500 for max MCQs)5. Adjust MCQs per chunk (higher = more MCQs per chunk, but may hit API limits; default 20 for max)6. Click "Generate MCQs" and wait for processing7. Download the generated Excel file with your MCQs""")11 unmodified lines)chunk_size_input = gr.Slider(minimum=300, # Lowered min to allow even smaller chunksmaximum=3000,value=500, # Changed default to 500 for more chunksstep=100,label="📝 Chunk Size (words per processing batch)")mcqs_per_chunk_input = gr.Slider(minimum=5,maximum=50, # Increased max for more MCQs per chunkvalue=20, # New slider for MCQs per chunk, default 20step=5,label="🔢 MCQs per Chunk (higher = more MCQs, but may increase failures)")generate_btn = gr.Button("🚀 Generate MCQs",variant="primary",15 unmodified lines# Event handlersgenerate_btn.click(fn=process_pdf_to_mcqs,inputs=[pdf_input, api_key_input, chunk_size_input, mcqs_per_chunk_input],outputs=[status_output, download_file],show_progress=True).then(6 unmodified lines"""## 📋 Features:- **OCR Text Extraction**: Converts PDF pages to images and extracts text- **Smart Chunking**: Breaks large documents into manageable pieces (smaller chunks = more MCQs)- **Configurable MCQs per Chunk**: Now adjustable up to 50 for maximum generation- **Multiple AI Models**: Automatically tries different Gemini models for best results- **Excel Output**: Download MCQs in a formatted Excel file- **Progress Tracking**: Real-time updates on processing status## ⚠️ Notes:- To maximize MCQs: Use small chunk size (e.g., 300-500) and high MCQs per chunk (e.g., 20-50)- Processing time depends on PDF length and settings (more MCQs = longer time)- Large PDFs are processed in chunks to avoid timeouts- Make sure your PDF contains readable text (not just images)- API key is not stored and only used for your session- Reduced delay between API calls for faster processing, but monitor for rate limits""")
app.py+28-16