Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import gradio as grimport pandas as pdfrom pdf2image import convert_from_pathimport pytesseractimport google.generativeai as genaiimport tempfileimport csvfrom io import StringIO# Function: Extract text from PDF using OCRdef extract_text_from_pdf(pdf_file):pages = convert_from_path(pdf_file)all_text = ""for page in pages:text = pytesseract.image_to_string(page)all_text += text + "\n"return all_text.strip()# Function: Chunk textdef chunk_text(text, chunk_size=1500):words = text.split()for i in range(0, len(words), chunk_size):yield " ".join(words[i:i+chunk_size])# Models to try (fallbacks)models_to_try = ["gemini-2.5-flash-lite","gemini-2.5-flash","gemini-2.5-pro","gemini-2.0-flash-lite","gemini-2.0-flash","gemini-1.5-flash","gemini-1.5-pro",]# Function: Generate MCQsdef generate_mcqs(text, api_key):genai.configure(api_key=api_key)chunks = list(chunk_text(text, 1500))mcq_data = []for i, chunk in enumerate(chunks, start=1):prompt = f"""Generate 10 MCQs from the following text.Return ONLY valid CSV rows with exactly 6 columns:Question,OptionA,OptionB,OptionC,OptionD,CorrectAnswerRules:- Do NOT add numbering, quotes, or explanations.- Do NOT add headers.- Do NOT add extra commas inside cells.- Exactly 10 rows per chunk.Text:\n{chunk}"""response = Nonefor model_name in models_to_try:try:model = genai.GenerativeModel(model_name)response = model.generate_content(prompt)if response.text:breakexcept Exception:continueif response and response.text:output = response.text.strip()try:reader = csv.reader(StringIO(output))for row in reader:if len(row) >= 6 and row[0]:mcq_data.append(row[:6]) # keep only first 6 colsexcept Exception:continueif not mcq_data:return None, Nonedf = pd.DataFrame(mcq_data,columns=["Question", "OptionA", "OptionB", "OptionC", "OptionD", "CorrectAnswer"],)return df, df.head(10).to_string(index=False)# Gradio pipelinedef process_pdf(pdf_file, api_key):if not api_key:return "β Please enter your Gemini API key.", Nonetry:text = extract_text_from_pdf(pdf_file.name)df, preview = generate_mcqs(text, api_key)if df is None:return "β No valid MCQs generated.", None# Save to a temporary Excel filetmp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")df.to_excel(tmp_file.name, index=False)return preview, tmp_file.nameexcept Exception as e:return f"Error: {str(e)}", None# Gradio UIwith gr.Blocks() as demo:gr.Markdown("## π PDF to MCQ Generator (Gemini AI)")gr.Markdown("Upload a PDF, enter your Gemini API key, extract text with OCR, and generate MCQs saved as Excel.")api_key = gr.Textbox(label="Enter your Gemini API Key", type="password")pdf_input = gr.File(label="Upload PDF", file_types=[".pdf"])generate_btn = gr.Button("Generate MCQs")preview_output = gr.Textbox(label="Preview (First 10 MCQs)", lines=15)excel_output = gr.File(label="Download Excel (.xlsx)")generate_btn.click(fn=process_pdf,inputs=[pdf_input, api_key],outputs=[preview_output, excel_output],)# Run appif __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281import osimport pandas as pdfrom pdf2image import convert_from_pathimport pytesseractimport tempfileimport ioimport gradio as grimport google.generativeai as genaifrom typing import List, Tupleimport time# Configure Gemini APIdef configure_gemini_api(api_key: str):"""Configure the Gemini API with the provided key"""genai.configure(api_key=api_key)return "β API Key configured successfully!"def extract_text_from_pdf(pdf_file) -> str:"""Extract text from PDF using OCR"""try:# Create temporary filewith tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:tmp_file.write(pdf_file)tmp_path = tmp_file.name# Convert PDF to imagespages = convert_from_path(tmp_path)all_text = ""for i, page in enumerate(pages):text = pytesseract.image_to_string(page)all_text += text + "\n"# Clean up temporary fileos.unlink(tmp_path)return all_textexcept 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 = []for i in range(0, len(words), chunk_size):chunks.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','gemini-1.5-pro']prompt = f"""Generate 10 multiple choice questions from the following text.Each question must have:- A clear, specific question- 4 options labeled A, B, C, D- One correct answer (A, B, C, or D)Format your response as CSV with headers: Question,OptionA,OptionB,OptionC,OptionD,CorrectAnswerImportant formatting rules:- Use commas only as field separators- If any field contains a comma, wrap it in double quotes- Each row should be on a new line- Make questions specific and clear- Ensure options are distinct and plausibleText to analyze:{chunk}"""# Configure APIgenai.configure(api_key=api_key)mcq_data = []response = Nonefor 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 = output.splitlines()# Skip header if presentfor line in lines[1:] if lines and 'Question' in lines[0] else lines:if line.strip():# Simple CSV parsing (you might want to use csv module for better handling)parts = []current_part = ""in_quotes = Falsefor char in line:if char == '"':in_quotes = not in_quoteselif char == ',' and not in_quotes:parts.append(current_part.strip().strip('"'))current_part = ""else:current_part += char# Add the last partif current_part:parts.append(current_part.strip().strip('"'))if len(parts) >= 6 and parts[0].strip():mcq_data.append(parts[:6])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", ""if not pdf_file:return "β Please upload a PDF file", ""try:# Extract text from PDFprogress(0.1, desc="Extracting text from PDF...")extracted_text = extract_text_from_pdf(pdf_file)if extracted_text.startswith("Error"):return extracted_text, ""# Chunk the textprogress(0.2, desc="Chunking text...")chunks = chunk_text(extracted_text, chunk_size)if not chunks:return "β No text could be extracted from the PDF", ""# Generate MCQs from each chunkall_mcq_data = []total_chunks = len(chunks)for 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...")if not all_mcq_data:return "β No MCQs could be generated from the PDF content", ""# Create DataFramedf = pd.DataFrame(all_mcq_data, columns=['Question', 'OptionA', 'OptionB', 'OptionC', 'OptionD', 'CorrectAnswer'])# Create Excel file in memoryoutput = io.BytesIO()with pd.ExcelWriter(output, engine='openpyxl') as writer:df.to_excel(writer, index=False, sheet_name='MCQs')output.seek(0)# Save to temporary file for downloadtemp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx')temp_file.write(output.getvalue())temp_file.close()progress(1.0, desc="Complete!")success_message = f"β Successfully generated {len(all_mcq_data)} MCQs from {total_chunks} text chunks!"return success_message, temp_file.nameexcept Exception as e:return f"β Error processing PDF: {str(e)}", ""# Create Gradio interfacedef create_interface():with gr.Blocks(title="PDF to MCQ Generator", theme=gr.themes.Soft()) as demo:gr.Markdown("""# π PDF to MCQ GeneratorUpload a PDF document and generate multiple choice questions automatically using Google's Gemini AI.## How to use:1. 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""")with gr.Row():with gr.Column(scale=2):api_key_input = gr.Textbox(label="π Gemini API Key",placeholder="Enter your Gemini API key here...",type="password")pdf_input = gr.File(label="π Upload PDF File",file_types=[".pdf"])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",size="lg")with gr.Column(scale=1):status_output = gr.Textbox(label="π Status",placeholder="Status updates will appear here...",lines=10)download_file = gr.File(label="β¬οΈ Download MCQs Excel File",visible=False)# 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(fn=lambda x: gr.update(visible=bool(x)),inputs=[download_file],outputs=[download_file])gr.Markdown("""## π 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""")return demo# Launch the appif __name__ == "__main__":demo = create_interface()demo.launch(server_name="0.0.0.0", server_port=7860)
app.py+263-110