from langgraph.graph import Graph, START, END from langgraph.graph.message import add_messages from typing_extensions import TypedDict, Annotated from typing import Dict, List, Any, Optional import openai import os import logging from datetime import datetime from reportlab.lib.pagesizes import letter, A4 from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import inch from reportlab.lib.colors import HexColor logger = logging.getLogger(__name__) # Set up OpenAI client openai.api_key = None # Placeholder, should be set externally class LectureState(TypedDict): pdf_content: str style: str include_examples: bool learning_objectives: str analysis: Dict[str, Any] outline: Dict[str, Any] sections: List[Dict[str, Any]] lecture_content: str title: str metadata: Dict[str, Any] messages: Annotated[list, add_messages] class LectureGenerator: """AI agent for converting PDF content into structured lectures using LangGraph""" def __init__(self): self.client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY", "")) self.graph = self._build_graph() def _build_graph(self) -> Graph: """Build the LangGraph workflow for lecture generation""" workflow = Graph() # Add nodes workflow.add_node("analyze_content", self._analyze_content) workflow.add_node("create_outline", self._create_outline) workflow.add_node("generate_sections", self._generate_sections) workflow.add_node("compile_lecture", self._compile_lecture) workflow.add_node("finalize_output", self._finalize_output) # Add edges workflow.add_edge(START, "analyze_content") workflow.add_edge("analyze_content", "create_outline") workflow.add_edge("create_outline", "generate_sections") workflow.add_edge("generate_sections", "compile_lecture") workflow.add_edge("compile_lecture", "finalize_output") workflow.add_edge("finalize_output", END) return workflow.compile() def generate_lecture(self, pdf_content: str, style: str = "academic", include_examples: bool = True, learning_objectives: str = "") -> Dict[str, Any]: """Generate a structured lecture from PDF content""" try: initial_state = LectureState( pdf_content=pdf_content, style=style, include_examples=include_examples, learning_objectives=learning_objectives, analysis={}, outline={}, sections=[], lecture_content="", title="", metadata={}, messages=[] ) # Run the graph result = self.graph.invoke(initial_state) return { 'success': True, 'title': result['title'], 'content': result['lecture_content'], 'sections': result['sections'], 'metadata': result['metadata'], 'word_count': len(result['lecture_content'].split()), 'estimated_duration': self._estimate_duration(result['lecture_content']) } except Exception as e: logger.error(f"Lecture generation failed: {str(e)}") return { 'success': False, 'error': str(e), 'title': '', 'content': '', 'sections': [], 'metadata': {}, 'word_count': 0, 'estimated_duration': 0 } def _analyze_content(self, state: LectureState) -> LectureState: """Analyze content or learning objectives to understand structure and main topics""" try: if state['pdf_content'].strip(): # PDF-based analysis learning_context = f"\n\nUser Learning Objectives: {state['learning_objectives']}" if state['learning_objectives'].strip() else "" prompt = f""" Analyze the following document content and provide a structured analysis: Content: {state['pdf_content'][:5000]}...{learning_context} Please provide: 1. Main topic/subject 2. Key themes and concepts 3. Document type (research paper, textbook, article, etc.) 4. Complexity level (beginner, intermediate, advanced) 5. Target audience 6. Key learning objectives (consider user's stated objectives if provided) Format your response as a JSON object. """ else: # Learning objectives-based analysis prompt = f""" Create a structured analysis for a lecture based on these learning objectives: Learning Objectives: {state['learning_objectives']} Please provide: 1. Main topic/subject (extracted from learning objectives) 2. Key themes and concepts that should be covered 3. Document type: "educational lecture" 4. Complexity level (beginner, intermediate, advanced) based on objectives 5. Target audience (inferred from objectives) 6. Detailed learning objectives breakdown Format your response as a JSON object. """ response = self.client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}], temperature=0.3 ) # Parse the analysis import json try: analysis = json.loads(response.choices[0].message.content) except: # Fallback parsing if JSON parsing fails if state['learning_objectives'].strip(): # Extract topic from learning objectives topic = state['learning_objectives'].split('.')[0].split(',')[0][:50] main_topic = topic if topic else "Educational Lecture" else: main_topic = "Document Analysis" analysis = { "main_topic": main_topic, "key_themes": ["Content Summary"], "document_type": "Document", "complexity_level": "intermediate", "target_audience": "General", "learning_objectives": ["Understand main concepts"] } state['analysis'] = analysis return state except Exception as e: logger.error(f"Content analysis failed: {str(e)}") if state['learning_objectives'].strip(): # Extract topic from learning objectives for fallback topic = state['learning_objectives'].split('.')[0].split(',')[0][:50] main_topic = topic if topic else "Educational Lecture" else: main_topic = "Document Analysis" state['analysis'] = { "main_topic": main_topic, "key_themes": ["Content Summary"], "document_type": "Document", "complexity_level": "intermediate", "target_audience": "General", "learning_objectives": ["Understand main concepts"] } return state def _create_outline(self, state: LectureState) -> LectureState: """Create a detailed lecture outline based on analysis""" try: analysis = state['analysis'] style = state['style'] learning_context = f"\n\nUser Learning Objectives: {state['learning_objectives']}" if state['learning_objectives'].strip() else "" prompt = f""" Based on this analysis, create a detailed lecture outline: Analysis: {analysis} Style: {style} Include Examples: {state['include_examples']}{learning_context} Create an outline with: 1. Engaging title that reflects user's learning goals 2. Introduction section 3. 3-5 main sections with subsections (prioritize user's stated learning objectives) 4. Conclusion section 5. Estimated time for each section Format as JSON with sections array containing title, subsections, and duration. """ response = self.client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}], temperature=0.4 ) import json try: outline = json.loads(response.choices[0].message.content) except: # Fallback outline with proper title title = analysis.get("main_topic", "Educational Lecture") if state['learning_objectives'].strip() and not state['pdf_content'].strip(): # For learning objectives only, create a more descriptive title objectives_words = state['learning_objectives'].split()[:5] # First 5 words title = " ".join(objectives_words).title() outline = { "title": title, "sections": [ {"title": "Introduction", "subsections": ["Overview"], "duration": 5}, {"title": "Core Concepts", "subsections": ["Key Points"], "duration": 15}, {"title": "Conclusion", "subsections": ["Summary"], "duration": 5} ] } state['outline'] = outline state['title'] = outline.get('title', 'Generated Lecture') return state except Exception as e: logger.error(f"Outline creation failed: {str(e)}") # Generate appropriate fallback title based on learning objectives if state['learning_objectives'].strip(): objectives_words = state['learning_objectives'].split()[:5] title = " ".join(objectives_words).title() if objectives_words else "Educational Lecture" else: title = "Generated Lecture" state['outline'] = { "title": title, "sections": [ {"title": "Introduction", "subsections": ["Overview"], "duration": 5}, {"title": "Core Concepts", "subsections": ["Key Points"], "duration": 15}, {"title": "Conclusion", "subsections": ["Summary"], "duration": 5} ] } state['title'] = title return state def _generate_sections(self, state: LectureState) -> LectureState: """Generate detailed content for each section""" try: sections = [] outline = state['outline'] pdf_content = state['pdf_content'] style = state['style'] for section in outline.get('sections', []): learning_context = f"\n\nUser Learning Objectives: {state['learning_objectives']}" if state['learning_objectives'].strip() else "" if pdf_content.strip(): # PDF-based section generation section_prompt = f""" Generate detailed content for this lecture section: Section Title: {section['title']} Subsections: {section.get('subsections', [])} Style: {style} Include Examples: {state['include_examples']}{learning_context} Source Material: {pdf_content[:3000]}... Create engaging, educational content that: 1. Explains concepts clearly (focus on user's learning objectives if provided) 2. Includes relevant examples if requested 3. Uses appropriate tone for {style} style 4. Builds logically on previous sections 5. Addresses the user's specific learning goals Format with clear headings and structured paragraphs. """ else: # Learning objectives-based section generation section_prompt = f""" Generate comprehensive educational content for this lecture section: Section Title: {section['title']} Subsections: {section.get('subsections', [])} Style: {style} Include Examples: {state['include_examples']} Learning Objectives: {state['learning_objectives']} Create engaging, educational content that: 1. Thoroughly explains concepts related to the learning objectives 2. Includes practical examples and real-world applications if requested 3. Uses appropriate {style} tone and language 4. Builds logically on previous sections 5. Directly addresses the stated learning objectives 6. Provides comprehensive coverage of the topic Format with clear headings and structured paragraphs. """ response = self.client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": section_prompt}], temperature=0.5 ) section_content = response.choices[0].message.content sections.append({ 'title': section['title'], 'content': section_content, 'duration': section.get('duration', 10), 'subsections': section.get('subsections', []) }) state['sections'] = sections return state except Exception as e: logger.error(f"Section generation failed: {str(e)}") # Create basic fallback sections state['sections'] = [ { 'title': 'Introduction', 'content': 'Welcome to this lecture based on the provided document.', 'duration': 5, 'subsections': ['Overview'] }, { 'title': 'Main Content', 'content': 'Here are the key points from the document.', 'duration': 15, 'subsections': ['Key Points'] } ] return state def _compile_lecture(self, state: LectureState) -> LectureState: """Compile all sections into a cohesive lecture""" try: title = state['title'] sections = state['sections'] # Create dynamic introduction based on content type if state['pdf_content'].strip(): # PDF-based lecture introduction intro = f"""# {title} Welcome to this comprehensive lecture on {title}. This presentation has been crafted from your uploaded document to provide you with a thorough understanding of the key concepts and insights. ## Learning Objectives By the end of this lecture, you will be able to: - Understand the main concepts presented in the source material - Apply the knowledge to practical situations - Engage in meaningful discussions about the topic --- """ else: # Topic-based lecture introduction learning_goals = state['learning_objectives'][:200] + "..." if len(state['learning_objectives']) > 200 else state['learning_objectives'] intro = f"""# {title} Welcome to this comprehensive lecture on {title}. This presentation has been crafted to address your specific learning objectives and provide you with a thorough understanding of the topic. ## Your Learning Goals {learning_goals} ## What You'll Learn By the end of this lecture, you will be able to: - Master the concepts you've requested to learn - Apply this knowledge to real-world scenarios - Build upon these foundations for further learning --- """ # Compile all sections compiled_content = intro for i, section in enumerate(sections, 1): compiled_content += f"\n## {i}. {section['title']}\n\n" compiled_content += section['content'] compiled_content += "\n\n---\n" # Add conclusion compiled_content += """ ## Conclusion Thank you for joining this lecture. We've covered the essential concepts and insights from the source material. Remember to review the key points and consider how they apply to your understanding of the subject. ### Key Takeaways - Review the main concepts discussed - Consider practical applications - Engage with additional resources for deeper learning --- *This lecture was generated using AI to transform written content into an engaging educational experience.* """ state['lecture_content'] = compiled_content return state except Exception as e: logger.error(f"Lecture compilation failed: {str(e)}") state['lecture_content'] = f"# {state['title']}\n\nThis is a generated lecture based on the provided document." return state def _finalize_output(self, state: LectureState) -> LectureState: """Finalize the output with metadata""" try: word_count = len(state['lecture_content'].split()) state['metadata'] = { 'generated_at': datetime.now().isoformat(), 'style': state['style'], 'include_examples': state['include_examples'], 'word_count': word_count, 'estimated_duration': self._estimate_duration(state['lecture_content']), 'sections_count': len(state['sections']), 'analysis': state['analysis'] } return state except Exception as e: logger.error(f"Output finalization failed: {str(e)}") state['metadata'] = { 'generated_at': datetime.now().isoformat(), 'style': state['style'], 'include_examples': state['include_examples'], 'word_count': 0, 'estimated_duration': 0, 'sections_count': 0, 'analysis': {} } return state def _estimate_duration(self, content: str) -> int: """Estimate lecture duration in minutes based on word count""" word_count = len(content.split()) # Assume average speaking rate of 150 words per minute return max(1, round(word_count / 150)) def generate_pdf(self, lecture_data: Dict[str, Any], output_path: str) -> bool: """Generate PDF version of the lecture""" try: doc = SimpleDocTemplate(output_path, pagesize=A4) styles = getSampleStyleSheet() # Custom styles title_style = ParagraphStyle( 'CustomTitle', parent=styles['Heading1'], fontSize=24, spaceAfter=30, textColor=HexColor('#2C3E50'), alignment=1 # Center alignment ) heading_style = ParagraphStyle( 'CustomHeading', parent=styles['Heading2'], fontSize=18, spaceAfter=20, spaceBefore=20, textColor=HexColor('#34495E') ) content = [] # Title content.append(Paragraph(lecture_data['title'], title_style)) content.append(Spacer(1, 20)) # Metadata metadata_text = f""" Generated: {lecture_data['metadata']['generated_at']}
Style: {lecture_data['metadata']['style'].title()}
Duration: ~{lecture_data['metadata']['estimated_duration']} minutes
Word Count: {lecture_data['metadata']['word_count']} """ content.append(Paragraph(metadata_text, styles['Normal'])) content.append(Spacer(1, 30)) # Process lecture content lecture_lines = lecture_data['content'].split('\n') for line in lecture_lines: line = line.strip() if not line: content.append(Spacer(1, 12)) elif line.startswith('# '): # Main title (already added) continue elif line.startswith('## '): # Section heading content.append(Paragraph(line[3:], heading_style)) elif line.startswith('---'): # Section separator content.append(Spacer(1, 20)) else: # Regular content content.append(Paragraph(line, styles['Normal'])) content.append(Spacer(1, 6)) doc.build(content) return True except Exception as e: logger.error(f"PDF generation failed: {str(e)}") return False