Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116import gradio as grimport pandas as pdfrom pdf2image import convert_from_pathimport pytesseractimport google.generativeai as genaifrom io import BytesIO
# Function: Extract text from PDFdef 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. Each question must have: - Question - 4 Options (A-D) - Correct Answer Return in CSV format: Question,OptionA,OptionB,OptionC,OptionD,CorrectAnswer. Text:\n{chunk} """
response = None for model_name in models_to_try: try: model = genai.GenerativeModel(model_name) response = model.generate_content(prompt) if response.text: break except Exception: continue
if response and response.text: output = response.text.strip() for line in output.splitlines(): parts = line.split(",") if len(parts) >= 6 and parts[0]: mcq_data.append(parts)
filtered_mcq_data = [row for row in mcq_data if len(row) == 6] if not filtered_mcq_data: return None, None
df = pd.DataFrame(filtered_mcq_data, columns=["Question", "OptionA", "OptionB", "OptionC", "OptionD", "CorrectAnswer"]) return df, df.head(10).to_markdown() # Show preview
# Gradio pipelinedef process_pdf(pdf_file, api_key): if not api_key: return "❌ Please enter your Gemini API key.", None
try: 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 Excel in memory output_file = BytesIO() df.to_excel(output_file, index=False) output_file.seek(0)
return preview, output_file except 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()app.pyAdded+116