File size: 29,482 Bytes
7fe0b2b
 
 
 
 
 
 
2809a57
b1ea736
13d28f0
7fe0b2b
2809a57
 
 
 
 
 
 
 
 
13d28f0
 
 
2809a57
 
13d28f0
2809a57
13d28f0
2809a57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fe0b2b
13d28f0
 
 
 
 
 
 
 
 
2809a57
 
 
 
 
 
 
 
 
13d28f0
 
 
 
 
 
 
 
 
 
2809a57
 
 
 
 
 
 
 
13d28f0
 
2809a57
6e6cdfc
13d28f0
 
 
 
 
 
6e6cdfc
 
 
 
 
 
 
13d28f0
 
 
6e6cdfc
13d28f0
 
6e6cdfc
 
 
95e9fbc
6e6cdfc
13d28f0
 
 
 
 
 
6e6cdfc
13d28f0
95e9fbc
6e6cdfc
 
13d28f0
95e9fbc
2809a57
 
 
13d28f0
6e6cdfc
13d28f0
2809a57
 
13d28f0
95e9fbc
2809a57
 
 
 
 
13d28f0
2809a57
 
 
 
 
 
 
 
 
95e9fbc
7fe0b2b
2809a57
 
95e9fbc
2809a57
 
 
 
 
13d28f0
 
5e93724
 
13d28f0
2809a57
95e9fbc
2809a57
ca71860
95e9fbc
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95e9fbc
 
 
 
 
 
ca71860
95e9fbc
 
 
 
 
 
 
 
 
 
 
ca71860
95e9fbc
 
ca71860
 
 
 
 
95e9fbc
 
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95e9fbc
 
 
 
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
2809a57
 
 
5e93724
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2809a57
 
 
 
 
 
5e93724
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2809a57
 
 
 
 
 
5e93724
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2809a57
 
 
 
 
95e9fbc
5e93724
ca71860
 
 
 
95e9fbc
 
 
 
 
 
 
 
 
 
 
 
ca71860
 
2809a57
5e93724
2809a57
 
 
 
 
 
 
 
ca71860
2809a57
 
 
 
 
 
5e93724
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2809a57
 
 
 
 
 
5e93724
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2809a57
 
 
 
 
 
5e93724
2809a57
ca71860
2809a57
ca71860
2809a57
ca71860
 
 
2809a57
ca71860
2809a57
ca71860
2809a57
ca71860
2809a57
ca71860
2809a57
ca71860
2809a57
ca71860
 
2809a57
ca71860
2809a57
ca71860
2809a57
 
7fe0b2b
2809a57
 
 
5e93724
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2809a57
ca71860
 
2809a57
 
7fe0b2b
13d28f0
 
6e6cdfc
13d28f0
6e6cdfc
13d28f0
 
6e6cdfc
 
 
13d28f0
 
 
 
 
 
 
 
7fe0b2b
 
 
 
95e9fbc
7fe0b2b
95e9fbc
 
b1ea736
 
7fe0b2b
 
 
 
 
 
 
 
13d28f0
 
7fe0b2b
 
13d28f0
7fe0b2b
 
 
 
13d28f0
 
7fe0b2b
 
13d28f0
6e6cdfc
13d28f0
 
 
 
 
7fe0b2b
 
 
 
 
 
 
 
 
 
ca71860
7fe0b2b
 
 
 
 
 
 
ca71860
95e9fbc
 
7fe0b2b
ca71860
 
 
 
7fe0b2b
 
 
95e9fbc
13d28f0
95e9fbc
7fe0b2b
95e9fbc
 
b1ea736
13d28f0
95e9fbc
 
7fe0b2b
 
ca71860
 
 
13d28f0
 
 
 
 
7fe0b2b
13d28f0
7fe0b2b
13d28f0
7fe0b2b
 
13d28f0
 
 
6e6cdfc
7fe0b2b
13d28f0
7fe0b2b
6e6cdfc
7fe0b2b
 
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95e9fbc
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fe0b2b
13d28f0
 
6e6cdfc
 
13d28f0
 
6e6cdfc
7fe0b2b
 
 
 
 
13d28f0
 
 
 
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
import gradio as gr
import PyPDF2
import docx
from openai import OpenAI
import io
import json
import time
from typing import List, Dict, Any, Optional
import spaces
import os

# Global variables to store API key and document text
API_KEY = ""
DOCUMENT_TEXT = ""
MODEL = "google/gemma-3-27b-it:free"

def setup_client(api_key: str):
    """Initialize and test API key"""
    global API_KEY
    try:
        if not api_key or api_key.strip() == "":
            return "❌ Please enter a valid API key"
            
        client = OpenAI(
            base_url="https://openrouter.ai/api/v1",
            api_key=api_key.strip(),
        )
        API_KEY = api_key.strip()
        return "βœ… API Key configured successfully!"
    except Exception as e:
        return f"❌ Error configuring API: {str(e)}"

def create_client() -> Optional[OpenAI]:
    """Create OpenAI client with stored API key"""
    if not API_KEY:
        return None
    return OpenAI(
        base_url="https://openrouter.ai/api/v1",
        api_key=API_KEY,
    )

def extract_text_from_pdf(file_path: str) -> str:
    """Extract text from PDF file"""
    try:
        with open(file_path, 'rb') as file:
            pdf_reader = PyPDF2.PdfReader(file)
            text = ""
            for page_num, page in enumerate(pdf_reader.pages):
                try:
                    page_text = page.extract_text()
                    if page_text:
                        text += page_text + "\n"
                except Exception as e:
                    print(f"Error extracting text from page {page_num}: {e}")
                    continue
            return text.strip()
    except Exception as e:
        return f"Error reading PDF: {str(e)}"

def extract_text_from_docx(file_path: str) -> str:
    """Extract text from DOCX file"""
    try:
        doc = docx.Document(file_path)
        text = ""
        for paragraph in doc.paragraphs:
            if paragraph.text.strip():
                text += paragraph.text + "\n"
        
        for table in doc.tables:
            for row in table.rows:
                for cell in row.cells:
                    if cell.text.strip():
                        text += cell.text + "\n"
        
        return text.strip()
    except Exception as e:
        return f"Error reading DOCX: {str(e)}"

def process_document(file):
    """Process uploaded document and extract text"""
    global DOCUMENT_TEXT
    
    if file is None:
        DOCUMENT_TEXT = ""
        return "❌ No file uploaded", "❌ No document loaded"
    
    try:
        file_path = file.name if hasattr(file, 'name') else str(file)
        
        if not os.path.exists(file_path):
            DOCUMENT_TEXT = ""
            return "❌ File not found", "❌ No document loaded"
        
        file_extension = file_path.lower().split('.')[-1]
        
        if file_extension == 'pdf':
            extracted_text = extract_text_from_pdf(file_path)
        elif file_extension in ['docx', 'doc']:
            extracted_text = extract_text_from_docx(file_path)
        else:
            DOCUMENT_TEXT = ""
            return "❌ Unsupported file format. Please upload PDF or DOCX files.", "❌ No document loaded"
        
        if extracted_text.startswith("Error"):
            DOCUMENT_TEXT = ""
            return extracted_text, "❌ No document loaded"
        
        DOCUMENT_TEXT = extracted_text.strip()
        
        if DOCUMENT_TEXT and len(DOCUMENT_TEXT) > 10:
            word_count = len(DOCUMENT_TEXT.split())
            char_count = len(DOCUMENT_TEXT)
            preview = DOCUMENT_TEXT[:300] + "..." if len(DOCUMENT_TEXT) > 300 else DOCUMENT_TEXT
            
            status_msg = f"βœ… Document loaded ({word_count} words, {char_count} characters)"
            process_msg = f"βœ… Document processed successfully!\nπŸ“„ Word count: {word_count}\nπŸ“ Character count: {char_count}\n\nπŸ“– Preview:\n{preview}"
            return process_msg, status_msg
        else:
            DOCUMENT_TEXT = ""
            return "❌ Could not extract meaningful text from the document.", "❌ No document loaded"
            
    except Exception as e:
        DOCUMENT_TEXT = ""
        return f"❌ Error processing document: {str(e)}", "❌ No document loaded"

def generate_content(prompt: str, max_tokens: int = 2000) -> str:
    """Generate content using the AI model"""
    global DOCUMENT_TEXT, API_KEY
    
    if not API_KEY or API_KEY.strip() == "":
        return "❌ Please configure your API key first"
    
    if not DOCUMENT_TEXT or len(DOCUMENT_TEXT.strip()) < 10:
        return "❌ Please upload and process a document first."
    
    try:
        client = create_client()
        if not client:
            return "❌ Failed to create API client"
        
        completion = client.chat.completions.create(
            extra_headers={
                "HTTP-Referer": "https://educational-assistant.app",
                "X-Title": "Educational Content Creator",
            },
            model=MODEL,
            messages=[
                {
                    "role": "system",
                    "content": "You are an expert educational content creator. Create engaging educational materials based on the provided document content. Format your response using proper HTML tags, but do not include <html>, <head>, <body>, or code block markers. Start directly with the content using tags like <h1>, <h2>, <p>, etc."
                },
                {
                    "role": "user",
                    "content": f"Document Content:\n{DOCUMENT_TEXT[:4000]}\n\n{prompt}"
                }
            ],
            max_tokens=max_tokens,
            temperature=0.7
        )
        
        result = completion.choices[0].message.content
        result = result.replace("```html", "").replace("```", "").strip()
        return result
        
    except Exception as e:
        return f"❌ Error generating content: {str(e)}"

def create_download_file(content: str, filename: str) -> str:
    """Create downloadable HTML file with full structure and interactivity"""
    html_template = f"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Educational Content - {filename}</title>
        <style>
            body {{
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                line-height: 1.6;
                margin: 0;
                padding: 20px;
                background-color: #f5f5f5;
            }}
            .container {{
                max-width: 1200px;
                margin: 0 auto;
                background: white;
                padding: 30px;
                border-radius: 10px;
                box-shadow: 0 0 20px rgba(0,0,0,0.1);
            }}
            h1, h2, h3, h4, h5, h6 {{
                color: #2c3e50;
                margin-top: 30px;
                margin-bottom: 15px;
            }}
            .flashcard-slider {{
                width: 100%;
                max-width: 400px;
                margin: 20px auto;
                overflow: hidden;
                position: relative;
                cursor: pointer;
            }}
            .slides {{
                display: flex;
                width: 200%;
                transition: transform 0.3s ease;
            }}
            .slide {{
                width: 50%;
                box-sizing: border-box;
                padding: 30px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border-radius: 15px;
                min-height: 200px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                text-align: center;
            }}
            .showing-answer .slides {{
                transform: translateX(-50%);
            }}
            .quiz-question {{
                background: #f8f9fa;
                border-left: 4px solid #007bff;
                padding: 15px;
                margin: 15px 0;
                border-radius: 5px;
            }}
            .answer-key {{
                background: #d4edda;
                border: 1px solid #c3e6cb;
                padding: 15px;
                border-radius: 5px;
                margin: 10px 0;
            }}
            .concept-box {{
                background: #fff3cd;
                border: 1px solid #ffeaa7;
                border-radius: 8px;
                padding: 20px;
                margin: 15px 0;
            }}
            .mind-map-branch {{
                background: #e3f2fd;
                border-left: 4px solid #2196f3;
                padding: 15px;
                margin: 10px 0;
                border-radius: 5px;
            }}
            .print-btn {{
                position: fixed;
                top: 20px;
                right: 20px;
                background: #007bff;
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: 5px;
                cursor: pointer;
                font-size: 14px;
            }}
            @media print {{
                .print-btn {{ display: none; }}
                body {{ background: white; }}
                .container {{ box-shadow: none; }}
            }}
        </style>
    </head>
    <body>
        <button class="print-btn" onclick="window.print()">πŸ–¨οΈ Print</button>
        <div class="container">
            {content}
        </div>
        <script>
            function toggleFlashcard(id) {{
                const flashcard = document.getElementById(id);
                if (flashcard) {{
                    flashcard.classList.toggle('showing-answer');
                }}
            }}
        </script>
    </body>
    </html>
    """
    
    temp_filename = f"temp_{filename}.html"
    with open(temp_filename, 'w', encoding='utf-8') as f:
        f.write(html_template)
    
    return temp_filename

@spaces.GPU
def generate_summary():
    """Generate comprehensive summary"""
    prompt = """Create a comprehensive summary of this document with proper HTML formatting. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content using tags like <h1>, <h2>, <p>, etc.
    
    Structure:
    <h1>πŸ“‹ Document Summary</h1>
    
    <h2>🎯 Executive Summary</h2>
    <p>Provide a brief overview in 2-3 sentences.</p>
    
    <h2>πŸ”‘ Key Points</h2>
    <ul>
    <li>List the main concepts, ideas, or arguments presented</li>
    </ul>
    
    <h2>πŸ“š Detailed Summary</h2>
    <p>Provide a thorough summary organized by topics or sections.</p>
    
    <h2>πŸ’‘ Important Takeaways</h2>
    <div class="concept-box">
    <p>Highlight the most crucial information students should remember.</p>
    </div>
    """
    return generate_content(prompt)

@spaces.GPU
def generate_study_notes():
    """Generate structured study notes"""
    prompt = """Create comprehensive study notes from this document using proper HTML formatting. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content.
    
    Structure:
    <h1>πŸ“– Study Notes</h1>
    
    <h2>πŸ”‘ Key Concepts</h2>
    <div class="concept-box">
    Define important terms and concepts with their significance
    </div>
    
    <h2>πŸ“Š Main Topics</h2>
    Organize content into clear sections with topic headings, key points, and supporting details
    
    <h2>🧠 Memory Aids</h2>
    <ul>
    <li>Mnemonics for complex information</li>
    <li>Visualization techniques</li>
    <li>Connection points between concepts</li>
    </ul>
    
    <h2>⚑ Quick Review Points</h2>
    <ul>
    <li>Essential facts and figures for rapid review</li>
    </ul>
    """
    return generate_content(prompt)

@spaces.GPU
def generate_quiz():
    """Generate quiz questions"""
    prompt = """Create a comprehensive quiz based on this document using HTML formatting. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content.
    
    <h1>πŸ“ Quiz Questions</h1>
    
    <h2>Multiple Choice Questions</h2>
    For each question, use this format:
    <div class="quiz-question">
    <h3>Question 1:</h3>
    <p>[Question text]</p>
    <ol type="A">
    <li>Option A</li>
    <li>Option B</li>
    <li>Option C</li>
    <li>Option D</li>
    </ol>
    </div>
    
    <h2>Short Answer Questions</h2>
    <div class="quiz-question">
    Questions requiring 2-3 sentence answers covering key concepts
    </div>
    
    <h2>Essay Questions</h2>
    <div class="quiz-question">
    Thought-provoking questions requiring detailed responses
    </div>
    
    <h2>πŸ“š Answer Key</h2>
    <div class="answer-key">
    <h3>Multiple Choice Answers:</h3>
    <p>Provide all correct answers with explanations</p>
    </div>
    
    Create 5 multiple choice, 5 short answer, and 2 essay questions.
    """
    return generate_content(prompt, max_tokens=3000)

@spaces.GPU
def generate_flashcards():
    """Generate interactive flashcards with slider functionality"""
    prompt = """Create 15-20 interactive flashcards based on this document. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content.
    
    Format each flashcard using this exact HTML structure:
    
    <h1>🎴 Interactive Flashcards</h1>
    <p><em>Click on a card to slide between question and answer!</em></p>
    
    <div class="flashcard-slider" id="card1" onclick="toggleFlashcard('card1')">
        <div class="slides">
            <div class="slide question">
                <h3>Card 1</h3>
                <p><strong>[Question/Term]</strong></p>
            </div>
            <div class="slide answer">
                <h3>Answer</h3>
                <p>[Answer/Definition/Explanation]</p>
            </div>
        </div>
    </div>
    
    Continue this pattern for each flashcard, incrementing the card numbers (card2, card3, etc.).
    
    Include flashcards for:
    - Key terms and definitions
    - Important concepts
    - Facts and figures
    - Cause and effect relationships
    - Applications and examples
    
    Make questions clear and answers comprehensive but concise. Use proper HTML formatting throughout.
    """
    return generate_content(prompt, max_tokens=2500)

@spaces.GPU
def generate_mind_map():
    """Generate mind map structure"""
    prompt = """Create a detailed mind map structure for this document using HTML. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content.
    
    <h1>🧠 Mind Map Structure</h1>
    
    <div class="concept-box">
    <h2>Central Topic:</h2>
    <p><strong>[Main subject of the document]</strong></p>
    </div>
    
    <h2>Primary Branches:</h2>
    
    For each main topic, create branches using this structure:
    <div class="mind-map-branch">
    <h3>Branch 1: [Topic Name]</h3>
    <ul>
    <li><strong>Sub-branch 1.1:</strong> [Subtopic]
        <ul>
        <li>Detail 1.1.1</li>
        <li>Detail 1.1.2</li>
        </ul>
    </li>
    </ul>
    </div>
    
    <h2>πŸ”— Connections</h2>
    <div class="concept-box">
    <ul>
    <li>Relationships between different branches</li>
    <li>Cross-references and dependencies</li>
    <li>Cause-effect relationships</li>
    </ul>
    </div>
    
    <h2>🎨 Visual Elements Suggestions</h2>
    <ul>
    <li>Color coding recommendations</li>
    <li>Symbol suggestions for different types of information</li>
    <li>Emphasis techniques for key concepts</li>
    </ul>
    """
    return generate_content(prompt)

@spaces.GPU
def generate_lesson_plan():
    """Generate lesson plan"""
    prompt = """Create a detailed lesson plan based on this document using HTML formatting. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content.
    
    <h1>πŸ“š Lesson Plan</h1>
    
    <h2>🎯 Learning Objectives</h2>
    <p>By the end of this lesson, students will be able to:</p>
    <ul>
    <li>[Specific, measurable objectives]</li>
    </ul>
    
    <h2>πŸ“‹ Prerequisites</h2>
    <div class="concept-box">
    <ul>
    <li>Required background knowledge</li>
    <li>Recommended prior reading</li>
    </ul>
    </div>
    
    <h2>⏰ Lesson Structure (60 minutes)</h2>
    
    <h3>Introduction (10 minutes)</h3>
    <ul>
    <li>Hook/attention grabber</li>
    <li>Learning objectives overview</li>
    </ul>
    
    <h3>Main Content (35 minutes)</h3>
    <ul>
    <li>Key concepts presentation</li>
    <li>Activities and examples</li>
    <li>Discussion points</li>
    </ul>
    
    <h3>Practice & Application (10 minutes)</h3>
    <ul>
    <li>Practice exercises</li>
    <li>Real-world applications</li>
    </ul>
    
    <h3>Wrap-up & Assessment (5 minutes)</h3>
    <ul>
    <li>Summary of key points</li>
    <li>Quick assessment questions</li>
    </ul>
    
    <h2>πŸ“¦ Materials Needed</h2>
    <ul>
    <li>List of required resources</li>
    </ul>
    
    <h2>πŸ“Š Assessment Methods</h2>
    <div class="answer-key">
    <p>How to evaluate student understanding</p>
    </div>
    
    <h2>πŸ“ Homework/Extension Activities</h2>
    <ul>
    <li>Additional practice opportunities</li>
    </ul>
    """
    return generate_content(prompt, max_tokens=2500)

@spaces.GPU
def generate_concept_explanations():
    """Generate detailed concept explanations"""
    prompt = """Provide detailed explanations of key concepts from this document using HTML. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content.
    
    <h1>πŸ” Concept Deep Dive</h1>
    
    For each major concept, use this structure:
    
    <div class="concept-box">
    <h2>[Concept Name]</h2>
    <p><strong>Definition:</strong> Clear, precise definition</p>
    
    <p><strong>Explanation:</strong> Detailed explanation in simple terms</p>
    
    <p><strong>Examples:</strong> Real-world examples and applications</p>
    
    <p><strong>Analogies:</strong> Helpful comparisons to familiar concepts</p>
    
    <p><strong>Common Misconceptions:</strong> What students often get wrong</p>
    
    <p><strong>Connection to Other Concepts:</strong> How it relates to other topics</p>
    
    <p><strong>Practice Application:</strong> Simple exercise or question</p>
    </div>
    
    <hr>
    
    Repeat this structure for all major concepts in the document using proper HTML formatting.
    """
    return generate_content(prompt, max_tokens=3000)

@spaces.GPU
def generate_practice_problems():
    """Generate practice problems"""
    prompt = """Create practice problems based on this document using HTML formatting. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content.
    
    <h1>πŸ’ͺ Practice Problems</h1>
    
    <h2>🟒 Beginner Level</h2>
    <div class="quiz-question">
    <h3>Problem 1:</h3>
    <p>[Problem statement]</p>
    <div class="answer-key">
    <p><strong>Solution:</strong> Step-by-step solution provided</p>
    </div>
    </div>
    
    <h2>🟑 Intermediate Level</h2>
    <div class="quiz-question">
    <h3>Problem 1:</h3>
    <p>[Multi-step problem requiring understanding of relationships]</p>
    <div class="answer-key">
    <p><strong>Solution:</strong> Guided solutions with explanations</p>
    </div>
    </div>
    
    <h2>πŸ”΄ Advanced Level</h2>
    <div class="quiz-question">
    <h3>Problem 1:</h3>
    <p>[Complex scenarios requiring analysis and synthesis]</p>
    <div class="answer-key">
    <p><strong>Solution:</strong> Detailed solution strategies</p>
    </div>
    </div>
    
    <h2>πŸ† Challenge Problems</h2>
    <div class="concept-box">
    <h3>Challenge 1:</h3>
    <p>[Extension beyond document content with creative application]</p>
    <div class="answer-key">
    <p><strong>Multiple Solution Approaches:</strong> Various ways to solve</p>
    </div>
    </div>
    
    For each problem, include:
    - Clear problem statement with HTML formatting
    - Required formulas/concepts in <strong> tags
    - Step-by-step solution in answer-key divs
    - Common mistakes to avoid
    
    Create 5 beginner, 5 intermediate, 3 advanced, and 2 challenge problems.
    """
    return generate_content(prompt, max_tokens=3500)

def get_document_status():
    """Get current document status"""
    global DOCUMENT_TEXT
    if DOCUMENT_TEXT and len(DOCUMENT_TEXT.strip()) > 10:
        word_count = len(DOCUMENT_TEXT.split())
        char_count = len(DOCUMENT_TEXT)
        return f"βœ… Document loaded ({word_count} words, {char_count} characters)"
    else:
        return "❌ No document loaded"

def get_api_status():
    """Get current API status"""
    global API_KEY
    if API_KEY and API_KEY.strip():
        return "βœ… API Key configured"
    else:
        return "❌ API Key not configured"

def create_interface():
    with gr.Blocks(title="πŸ“š Educational Content Creator Assistant", theme=gr.themes.Soft()) as app:
        gr.Markdown("""
        # πŸ“š Educational Content Creator Assistant
        Transform your documents into comprehensive educational materials using AI!
        
        **New Feature:** 
        - 🎴 Interactive Flashcards now work like an image sliderβ€”click to slide between question and answer!
        
        *Powered by ZeroGPU for enhanced performance*
        """)
        
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("### πŸ”‘ Setup")
                api_key = gr.Textbox(
                    label="OpenRouter API Key",
                    type="password",
                    placeholder="Enter your OpenRouter API key...",
                    info="Get your API key from https://openrouter.ai/"
                )
                setup_btn = gr.Button("πŸ”§ Configure API", variant="primary")
                setup_status = gr.Textbox(label="API Status", value=get_api_status(), interactive=False)
                
                gr.Markdown("### πŸ“„ Document Upload")
                file_upload = gr.File(
                    label="Upload Document (PDF or DOCX)",
                    file_types=[".pdf", ".docx", ".doc"],
                    type="filepath"
                )
                process_btn = gr.Button("πŸ”„ Process Document", variant="secondary")
                process_status = gr.Textbox(label="Processing Status", interactive=False, lines=4)
                
                doc_status = gr.Textbox(
                    label="Document Status", 
                    value=get_document_status(), 
                    interactive=False
                )
            
            with gr.Column(scale=2):
                gr.Markdown("### 🎯 Generate Educational Content")
                
                with gr.Row():
                    summary_btn = gr.Button("πŸ“‹ Generate Summary", variant="primary")
                    notes_btn = gr.Button("πŸ“– Study Notes", variant="primary")
                    quiz_btn = gr.Button("πŸ“ Create Quiz", variant="primary")
                
                with gr.Row():
                    flashcards_btn = gr.Button("🎴 Interactive Flashcards", variant="secondary")
                    mindmap_btn = gr.Button("🧠 Mind Map", variant="secondary")
                    lesson_btn = gr.Button("πŸ“š Lesson Plan", variant="secondary")
                
                with gr.Row():
                    concepts_btn = gr.Button("πŸ” Concept Explanations", variant="secondary")
                    problems_btn = gr.Button("πŸ’ͺ Practice Problems", variant="secondary")
                
                output = gr.HTML(
                    label="Generated Content",
                    value="<p>Generated content will appear here...</p>"
                )
                
                with gr.Row():
                    download_file = gr.File(label="πŸ“₯ Download Content", visible=False)
                    download_btn = gr.Button("πŸ’Ύ Prepare Download", variant="secondary", visible=False)
        
        gr.Markdown("""
        ### πŸ“‹ How to Use:
        1. **Get API Key:** Sign up at [OpenRouter](https://openrouter.ai/)
        2. **Configure:** Enter your API key and click "Configure API" 
        3. **Upload:** Upload a PDF or DOCX document
        4. **Process:** Click "Process Document" to extract text
        5. **Generate:** Choose a content type to generate
        6. **Download:** Download the HTML file to see interactive flashcards
        
        ### πŸ’‘ Tips:
        - Flashcards slide between question and answer when clicked (in the downloaded file).
        - Use the downloaded HTML file in a browser for full interactivity.
        """)
        
        last_content = gr.State("")
        last_content_type = gr.State("")
        
        def setup_api_and_update_status(api_key):
            result = setup_client(api_key)
            status = get_api_status()
            return result, status
        
        setup_btn.click(
            setup_api_and_update_status,
            inputs=[api_key],
            outputs=[setup_status, setup_status]
        )
        
        def process_and_update_all_status(file):
            process_result, doc_status_result = process_document(file)
            return process_result, doc_status_result
        
        process_btn.click(
            process_and_update_all_status,
            inputs=[file_upload],
            outputs=[process_status, doc_status]
        )
        
        def generate_and_display_summary():
            content = generate_summary()
            return content, content, "summary", gr.update(visible=True)
        
        def generate_and_display_notes():
            content = generate_study_notes()
            return content, content, "study_notes", gr.update(visible=True)
        
        def generate_and_display_quiz():
            content = generate_quiz()
            return content, content, "quiz", gr.update(visible=True)
        
        def generate_and_display_flashcards():
            content = generate_flashcards()
            return content, content, "flashcards", gr.update(visible=True)
        
        def generate_and_display_mindmap():
            content = generate_mind_map()
            return content, content, "mind_map", gr.update(visible=True)
        
        def generate_and_display_lesson():
            content = generate_lesson_plan()
            return content, content, "lesson_plan", gr.update(visible=True)
        
        def generate_and_display_concepts():
            content = generate_concept_explanations()
            return content, content, "concept_explanations", gr.update(visible=True)
        
        def generate_and_display_problems():
            content = generate_practice_problems()
            return content, content, "practice_problems", gr.update(visible=True)
        
        def prepare_download(content, content_type):
            if not content or content.startswith("❌"):
                return None
            temp_file = create_download_file(content, content_type)
            return temp_file
        
        summary_btn.click(
            generate_and_display_summary,
            outputs=[output, last_content, last_content_type, download_btn]
        )
        
        notes_btn.click(
            generate_and_display_notes,
            outputs=[output, last_content, last_content_type, download_btn]
        )
        
        quiz_btn.click(
            generate_and_display_quiz,
            outputs=[output, last_content, last_content_type, download_btn]
        )
        
        flashcards_btn.click(
            generate_and_display_flashcards,
            outputs=[output, last_content, last_content_type, download_btn]
        )
        
        mindmap_btn.click(
            generate_and_display_mindmap,
            outputs=[output, last_content, last_content_type, download_btn]
        )
        
        lesson_btn.click(
            generate_and_display_lesson,
            outputs=[output, last_content, last_content_type, download_btn]
        )
        
        concepts_btn.click(
            generate_and_display_concepts,
            outputs=[output, last_content, last_content_type, download_btn]
        )
        
        problems_btn.click(
            generate_and_display_problems,
            outputs=[output, last_content, last_content_type, download_btn]
        )
        
        def handle_download(content, content_type):
            if content and not content.startswith("❌"):
                temp_file = prepare_download(content, content_type)
                return temp_file, gr.update(visible=True)
            return None, gr.update(visible=False)
        
        download_btn.click(
            handle_download,
            inputs=[last_content, last_content_type],
            outputs=[download_file, download_file]
        )
        
        def update_initial_status():
            return get_api_status(), get_document_status()
        
        app.load(
            update_initial_status,
            outputs=[setup_status, doc_status]
        )
    
    return app

if __name__ == "__main__":
    app = create_interface()
    app.launch(
        debug=True,
        share=False
    )