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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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"""
            <b>Generated:</b> {lecture_data['metadata']['generated_at']}<br/>
            <b>Style:</b> {lecture_data['metadata']['style'].title()}<br/>
            <b>Duration:</b> ~{lecture_data['metadata']['estimated_duration']} minutes<br/>
            <b>Word Count:</b> {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