Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345128910345612137891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465151617181967686970717220212223747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222324252627282930313233343536373839404142434445464748495051525354555657582252262272282292305960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104233234235236237238239240241242105"""Main Gradio application optimized for Hugging Face Spaces"""
import gradio as grimport osimport tempfileimport jsonfrom multi_agent import MultiAgentSystemfrom docx_builder import generate_all_documentsfrom pathlib import Pathimport gradio as grfrom pypdf import PdfReader
# Initialize the multi-agent systemagent_system = MultiAgentSystem()from agents import GroqClient, SerpClientfrom multi_agent import MultiAgentOrchestratorfrom docx_builder import ( build_question_paper_docx, build_answers_docx, build_obe_docx,)
def generate_exam_package(subject, stream, part_a_count, part_b_count, part_c_count, syllabus_file, reference_file): """Main function called by Gradio interface""" try: # Convert counts to integers part_a_count = int(part_a_count) if part_a_count else 5 part_b_count = int(part_b_count) if part_b_count else 5 part_c_count = int(part_c_count) if part_c_count else 1 # Validate inputs if not subject or not syllabus_file: return None, None, None, "β Please provide subject name and syllabus PDF" # Generate exam package final_output, status = agent_system.generate_exam_package( subject=subject, stream=stream, part_a_count=part_a_count, part_b_count=part_b_count, part_c_count=part_c_count, syllabus_file=syllabus_file, reference_file=reference_file ) if status != "Success": return None, None, None, f"β {status}" # Create temporary directory for outputs with tempfile.TemporaryDirectory() as temp_dir: # Generate DOCX files files = generate_all_documents(final_output, subject, stream, temp_dir) # Return file paths return files["question_paper"], files["answer_key"], files["obe_summary"], "β
Generation completed successfully!" except Exception as e: error_msg = f"β Error: {str(e)}" print(error_msg) return None, None, None, error_msg
def update_progress_ui(): """Update progress in UI""" progress = agent_system.get_progress() return f"π {progress['stage'].upper()}: {progress['message']} ({progress['percentage']}%)"
def validate_inputs(subject, part_a_count, part_b_count, part_c_count): """Validate user inputs""" errors = [] if not subject: errors.append("Subject name is required") # ---------------------------# Utility: Extract PDF text# ---------------------------def extract_text_from_pdf(file_obj) -> str: try: if part_a_count and int(part_a_count) <= 0: errors.append("Part A count must be positive") if part_b_count and int(part_b_count) <= 0: errors.append("Part B count must be positive") if part_c_count and int(part_c_count) <= 0: errors.append("Part C count must be positive") reader = PdfReader(file_obj.name) pages = [p.extract_text() or "" for p in reader.pages] return "\n".join(pages) except: errors.append("Question counts must be numbers") return errors
# Gradio interfacewith gr.Blocks(title="AI Exam Generator", theme=gr.themes.Soft()) as demo: gr.Markdown(""" # π AI-Powered Question Paper Generator *Generate complete exam packages with OBE compliance using multi-agent AI system* """) with gr.Row(): with gr.Column(scale=1): # Input section gr.Markdown("### π Exam Configuration") subject_name = gr.Textbox( label="Subject Name", placeholder="e.g., Data Structures, Algorithms, Database Systems", value="Data Structures" ) stream = gr.Dropdown( choices=["CSE", "Non-CSE"], label="Engineering Stream", value="CSE", info="CSE: Company tags | Non-CSE: GATE patterns" ) with gr.Row(): part_a_count = gr.Number( label="Part A Questions", value=5, minimum=1, maximum=20, info="2 marks each" ) part_b_count = gr.Number( label="Part B Questions", value=5, minimum=1, maximum=10, info="13 marks each" ) part_c_count = gr.Number( label="Part C Questions", value=1, minimum=1, maximum=3, info="14 marks each" ) syllabus_pdf = gr.File( label="Upload Syllabus PDF", file_types=[".pdf"], type="filepath", file_count="single" ) reference_qp = gr.File( label="Reference Question Paper (Optional)", file_types=[".pdf"], type="filepath", file_count="single" ) generate_btn = gr.Button("π― Generate Exam Package", variant="primary", size="lg") with gr.Column(scale=1): # Output section gr.Markdown("### π€ Generated Outputs") status_display = gr.Textbox( label="Status", value="π’ Ready to generate exam package", interactive=False, lines=2 ) with gr.Group(): gr.Markdown("#### π Download Files") with gr.Row(): qp_download = gr.File( label="Question Paper", file_types=[".docx"], interactive=False, visible=False ) answers_download = gr.File( label="Answer Key", file_types=[".docx"], interactive=False, visible=False ) obe_download = gr.File( label="OBE Summary", file_types=[".docx"], interactive=False, visible=False ) # Progress section gr.Markdown("### π Generation Progress") progress_text = gr.Textbox( label="Real-time Progress", value="π’ System initialized and ready", interactive=False, every=1 ) # Instructions gr.Markdown(""" ## π How to Use This System 1. **Enter Subject Details**: Provide the subject name and select engineering stream 2. **Configure Questions**: Set the number of questions for each part (A, B, C) 3. **Upload Syllabus**: PDF file containing course syllabus and learning outcomes 4. **Optional Reference**: Upload previous question papers for style reference 5. **Generate**: Click the button to create your complete exam package 6. **Download**: Get all three DOCX files (Question Paper, Answer Key, OBE Summary) ## π― Features - **π€ Multi-Agent AI**: Three specialized agents for generation, verification, and formatting - **π OBE Compliant**: Automatic Outcome-Based Education reporting - **π Real-time Updates**: Incorporates recent developments in the field - **π Stream-specific**: CSE (company tags) vs Non-CSE (GATE patterns) - **β
Quality Verified**: Automated validation of standards and requirements - **π Professional Output**: Ready-to-use DOCX files with proper formatting ## β οΈ Important Notes - Ensure your syllabus PDF is readable and contains clear learning outcomes - For best results, provide a descriptive subject name - The system works without API keys but with enhanced capabilities when configured - Generation may take 1-2 minutes depending on complexity """) # Event handlers generate_btn.click( fn=generate_exam_package, inputs=[subject_name, stream, part_a_count, part_b_count, part_c_count, syllabus_pdf, reference_qp], outputs=[qp_download, answers_download, obe_download, status_display] ).then( fn=lambda: (gr.File(visible=True), gr.File(visible=True), gr.File(visible=True)), outputs=[qp_download, answers_download, obe_download] return ""
# ---------------------------# Initialize Clients# ---------------------------def init_clients(): groq_key = os.getenv("GROQ_API_KEY") serp_key = os.getenv("SERPAPI_KEY") groq = GroqClient(api_key=groq_key) serp = SerpClient(api_key=serp_key) return groq, serp
groq_client, serp_client = init_clients()orchestrator = MultiAgentOrchestrator(groq_client, serp_client)
# ---------------------------# Main Pipeline Trigger# ---------------------------def run_system(subject, stream, partA, partB, partC, syl_file, ref_file):
if syl_file is None: return None, None, None, "Upload syllabus first."
syllabus_text = extract_text_from_pdf(syl_file) ref_text = extract_text_from_pdf(ref_file) if ref_file else ""
output = orchestrator.run_pipeline( subject=subject, stream=stream, partA=int(partA), partB=int(partB), partC=int(partC), syllabus_text=syllabus_text, ref_qp_text=ref_text, ) # Progress updates progress_text.change( fn=update_progress_ui, inputs=[], outputs=[progress_text]
final_json = output.get("final", {}) generator_raw = output.get("generator_raw", "")
tmpdir = Path(tempfile.mkdtemp()) qp_path = tmpdir / f"{subject}_QP.docx" ans_path = tmpdir / f"{subject}_Answers.docx" obe_path = tmpdir / f"{subject}_OBE.docx"
build_question_paper_docx(qp_path, final_json, generator_raw, subject) build_answers_docx(ans_path, final_json, subject) build_obe_docx(obe_path, final_json, subject)
return qp_path, ans_path, obe_path, "Done!"
# ---------------------------# Gradio UI# ---------------------------with gr.Blocks() as app: gr.Markdown("# Multi-Agent Question Paper Generator (Groq + SerpAPI)")
with gr.Row(): subject = gr.Textbox(label="Subject Name") stream = gr.Dropdown(["CSE", "Non-CSE"], value="CSE", label="Stream")
with gr.Row(): partA = gr.Number(value=10, precision=0, label="Part A Count") partB = gr.Number(value=5, precision=0, label="Part B Count") partC = gr.Number(value=1, precision=0, label="Part C Count")
syllabus = gr.File(label="Upload Syllabus PDF") ref_qp = gr.File(label="Upload Reference QP (Optional)")
btn = gr.Button("Generate Question Paper")
qp_file = gr.File(label="Question Paper") ans_file = gr.File(label="Answer Key") obe_file = gr.File(label="OBE Summary") status = gr.Markdown("Status: Idle")
btn.click( run_system, inputs=[subject, stream, partA, partB, partC, syllabus, ref_qp], outputs=[qp_file, ans_file, obe_file, status] )
# Deployment configurationif __name__ == "__main__": # For Hugging Face Spaces demo.queue(concurrency_count=1, max_size=10) demo.launch( server_name="0.0.0.0", server_port=7860, share=False, show_error=True )app.launch()app.py+96-233