Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242"""Main Gradio application optimized for Hugging Face Spaces"""import gradio as grimport osimport tempfileimport jsonfrom multi_agent import MultiAgentSystemfrom docx_builder import generate_all_documents# Initialize the multi-agent systemagent_system = MultiAgentSystem()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 integerspart_a_count = int(part_a_count) if part_a_count else 5part_b_count = int(part_b_count) if part_b_count else 5part_c_count = int(part_c_count) if part_c_count else 1# Validate inputsif not subject or not syllabus_file:return None, None, None, "❌ Please provide subject name and syllabus PDF"# Generate exam packagefinal_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 outputswith tempfile.TemporaryDirectory() as temp_dir:# Generate DOCX filesfiles = generate_all_documents(final_output, subject, stream, temp_dir)# Return file pathsreturn 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_msgdef 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")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")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 sectiongr.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 sectiongr.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 sectiongr.Markdown("### 🔄 Generation Progress")progress_text = gr.Textbox(label="Real-time Progress",value="🟢 System initialized and ready",interactive=False,every=1)# Instructionsgr.Markdown("""## 📖 How to Use This System1. **Enter Subject Details**: Provide the subject name and select engineering stream2. **Configure Questions**: Set the number of questions for each part (A, B, C)3. **Upload Syllabus**: PDF file containing course syllabus and learning outcomes4. **Optional Reference**: Upload previous question papers for style reference5. **Generate**: Click the button to create your complete exam package6. **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 handlersgenerate_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])# Progress updatesprogress_text.change(fn=update_progress_ui,inputs=[],outputs=[progress_text])# Deployment configurationif __name__ == "__main__":# For Hugging Face Spacesdemo.queue(concurrency_count=1, max_size=10)demo.launch(server_name="0.0.0.0",server_port=7860,share=False,show_error=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105import osimport tempfilefrom pathlib import Pathimport gradio as grfrom pypdf import PdfReaderfrom agents import GroqClient, SerpClientfrom multi_agent import MultiAgentOrchestratorfrom docx_builder import (build_question_paper_docx,build_answers_docx,build_obe_docx,)# ---------------------------# Utility: Extract PDF text# ---------------------------def extract_text_from_pdf(file_obj) -> str:try:reader = PdfReader(file_obj.name)pages = [p.extract_text() or "" for p in reader.pages]return "\n".join(pages)except: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, serpgroq_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,)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])app.launch()
app.py+96-233