Spaces:
Sleeping
Sleeping
Update app.py
Browse files14 unmodified lines1516171819202122232425262728293031323334353637383984 unmodified lines12412512612712812913013113213313413513613713813914014114214314414514614714811 unmodified lines1601611621631641651661671681691701711721731741751761771781791801812 unmodified lines18418518618718818919060 unmodified lines25125225325425525625714 unmodified linesgenai.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)}"84 unmodified linesdef 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 = []11 unmodified linesprogress(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!")2 unmodified linesreturn success_message, temp_file.nameexcept Exception as e:return f"❌ Error processing PDF: {str(e)}", ""# Create Gradio interfacedef create_interface():60 unmodified linesoutputs=[status_output, download_file],show_progress=True).then(fn=lambda x: gr.update(visible=bool(x)),inputs=[download_file],outputs=[download_file])14 unmodified lines151617181920212223242526272829303184 unmodified lines11611711811912012112212312412512612712812913013113213313413513613713813914011 unmodified lines1521531541551561571581591601611621631641651661671681692 unmodified lines17217317417517617717860 unmodified lines23924024124224324424514 unmodified linesgenai.configure(api_key=api_key)return "✅ API Key configured successfully!"def extract_text_from_pdf(pdf_file_path: str) -> str:"""Extract text from PDF using OCR"""try:# Convert PDF to imagespages = convert_from_path(pdf_file_path)all_text = ""for i, page in enumerate(pages):text = pytesseract.image_to_string(page)all_text += text + "\n"return all_textexcept Exception as e:return f"Error extracting text: {str(e)}"84 unmodified linesdef 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", Noneif not pdf_file:return "❌ Please upload a PDF file", Nonetry:# Extract text from PDFprogress(0.1, desc="Extracting text from PDF...")extracted_text = extract_text_from_pdf(pdf_file.name)if extracted_text.startswith("Error"):return extracted_text, None# 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", None# Generate MCQs from each chunkall_mcq_data = []11 unmodified linesprogress(0.95, desc="Creating Excel file...")if not all_mcq_data:return "❌ No MCQs could be generated from the PDF content", None# Create DataFramedf = pd.DataFrame(all_mcq_data, columns=['Question', 'OptionA', 'OptionB', 'OptionC', 'OptionD', 'CorrectAnswer'])# Create temporary Excel file for downloadtemp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx', mode='wb')temp_file.close() # Close to allow pandas to write to it# Write Excel filewith pd.ExcelWriter(temp_file.name, engine='openpyxl') as writer:df.to_excel(writer, index=False, sheet_name='MCQs')progress(1.0, desc="Complete!")2 unmodified linesreturn success_message, temp_file.nameexcept Exception as e:return f"❌ Error processing PDF: {str(e)}", None# Create Gradio interfacedef create_interface():60 unmodified linesoutputs=[status_output, download_file],show_progress=True).then(fn=lambda file_path: gr.update(visible=bool(file_path)) if file_path else gr.update(visible=False),inputs=[download_file],outputs=[download_file])
app.py+16-28