File size: 36,924 Bytes
7fe0b2b
 
 
 
 
 
 
2809a57
b1ea736
13d28f0
beaa443
7fe0b2b
2809a57
 
 
 
 
 
 
 
 
13d28f0
 
 
 
2809a57
 
13d28f0
2809a57
 
13d28f0
2809a57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fe0b2b
13d28f0
 
 
 
 
 
 
 
 
2809a57
 
 
 
 
 
 
 
 
13d28f0
 
 
 
 
 
 
 
 
 
 
2809a57
 
 
 
 
 
 
13d28f0
 
2809a57
13d28f0
 
2809a57
6e6cdfc
13d28f0
 
 
 
 
 
 
 
 
6e6cdfc
13d28f0
6e6cdfc
13d28f0
6e6cdfc
 
 
 
 
13d28f0
 
 
 
6e6cdfc
 
 
13d28f0
 
6e6cdfc
13d28f0
6e6cdfc
 
13d28f0
6e6cdfc
13d28f0
 
 
 
 
 
 
 
6e6cdfc
13d28f0
 
6e6cdfc
 
13d28f0
 
 
 
2809a57
beaa443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2809a57
 
13d28f0
6e6cdfc
13d28f0
 
 
2809a57
 
13d28f0
6e6cdfc
2809a57
 
 
 
 
13d28f0
 
 
2809a57
 
 
 
 
 
 
 
 
beaa443
7fe0b2b
2809a57
 
13d28f0
2809a57
 
 
 
 
13d28f0
 
 
beaa443
 
 
 
13d28f0
2809a57
13d28f0
 
 
2809a57
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beaa443
ca71860
 
 
 
beaa443
 
 
 
 
 
 
 
 
 
ca71860
beaa443
ca71860
 
beaa443
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca71860
 
 
 
 
 
 
 
 
 
 
 
13d28f0
2809a57
 
 
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beaa443
 
2809a57
 
 
 
 
 
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beaa443
 
2809a57
 
 
 
 
 
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beaa443
2809a57
 
 
 
 
ca71860
 
 
 
 
 
beaa443
2809a57
beaa443
 
ca71860
 
 
 
 
 
 
 
 
2809a57
beaa443
 
 
 
 
2809a57
 
 
 
 
 
 
 
ca71860
beaa443
2809a57
 
 
 
 
 
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beaa443
 
2809a57
 
 
 
 
 
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
beaa443
 
2809a57
 
 
 
 
 
ca71860
2809a57
ca71860
2809a57
ca71860
2809a57
ca71860
 
 
2809a57
ca71860
2809a57
ca71860
2809a57
ca71860
2809a57
ca71860
2809a57
ca71860
2809a57
ca71860
 
2809a57
ca71860
2809a57
ca71860
beaa443
2809a57
 
7fe0b2b
2809a57
 
 
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2809a57
ca71860
 
beaa443
2809a57
 
7fe0b2b
13d28f0
 
6e6cdfc
13d28f0
6e6cdfc
13d28f0
 
6e6cdfc
 
 
13d28f0
 
 
 
 
 
 
 
7fe0b2b
 
 
 
 
ca71860
7fe0b2b
ca71860
 
 
 
 
b1ea736
 
7fe0b2b
 
 
 
 
 
 
 
13d28f0
 
7fe0b2b
 
13d28f0
7fe0b2b
 
 
 
13d28f0
 
7fe0b2b
 
13d28f0
6e6cdfc
13d28f0
 
 
 
 
 
7fe0b2b
 
 
 
 
 
 
 
 
 
ca71860
7fe0b2b
 
 
 
 
 
 
ca71860
 
 
 
7fe0b2b
ca71860
 
 
 
 
7fe0b2b
 
 
13d28f0
 
 
7fe0b2b
ca71860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1ea736
13d28f0
 
 
 
ca71860
 
13d28f0
b1ea736
 
7fe0b2b
 
ca71860
 
 
 
7fe0b2b
13d28f0
 
 
 
 
7fe0b2b
13d28f0
7fe0b2b
13d28f0
7fe0b2b
 
13d28f0
 
 
6e6cdfc
7fe0b2b
13d28f0
7fe0b2b
6e6cdfc
7fe0b2b
 
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
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
import re

# 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"
            
        # Test the API key by creating a client
        client = OpenAI(
            base_url="https://openrouter.ai/api/v1",
            api_key=api_key.strip(),
        )
        # Store the API key globally
        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"
        
        # Also extract text from tables
        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
    
    print(f"Processing file: {file}")  # Debug print
    
    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)
        print(f"File path: {file_path}")  # Debug print
        
        # Check if file exists
        if not os.path.exists(file_path):
            DOCUMENT_TEXT = ""
            return "❌ File not found", "❌ No document loaded"
        
        # Get file extension
        file_extension = file_path.lower().split('.')[-1]
        print(f"File extension: {file_extension}")  # Debug print
        
        # Extract text based on file type
        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"
        
        print(f"Extracted text length: {len(extracted_text) if extracted_text else 0}")  # Debug print
        
        # Check if extraction was successful
        if extracted_text.startswith("Error"):
            DOCUMENT_TEXT = ""
            return extracted_text, "❌ No document loaded"
        
        # Clean and set the global variable
        DOCUMENT_TEXT = extracted_text.strip()
        
        if DOCUMENT_TEXT and len(DOCUMENT_TEXT) > 10:  # Minimum length check
            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}"
            
            print(f"Document processed successfully. Word count: {word_count}")  # Debug print
            return process_msg, status_msg
        else:
            DOCUMENT_TEXT = ""
            return "❌ Could not extract meaningful text from the document. The document might be empty, contain only images, or be corrupted.", "❌ No document loaded"
            
    except Exception as e:
        DOCUMENT_TEXT = ""
        error_msg = f"❌ Error processing document: {str(e)}"
        print(f"Error: {error_msg}")  # Debug print
        return error_msg, "❌ No document loaded"

def clean_html_response(content: str) -> str:
    """Clean HTML response by removing markdown code blocks and fixing formatting"""
    if not content:
        return content
    
    # Remove ```html and ``` blocks
    content = re.sub(r'```html\s*', '', content)
    content = re.sub(r'```\s*$', '', content, flags=re.MULTILINE)
    content = re.sub(r'```', '', content)
    
    # Remove any remaining markdown code block indicators
    content = re.sub(r'^```.*?\n', '', content, flags=re.MULTILINE)
    
    # Clean up extra whitespace
    content = re.sub(r'\n\s*\n\s*\n', '\n\n', content)
    
    return content.strip()

def generate_content(prompt: str, max_tokens: int = 2000) -> str:
    """Generate content using the AI model"""
    global DOCUMENT_TEXT, API_KEY
    
    print(f"Generate content called. API_KEY exists: {bool(API_KEY)}, DOCUMENT_TEXT length: {len(DOCUMENT_TEXT) if DOCUMENT_TEXT else 0}")  # Debug print
    
    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. Make sure the document contains readable text."
    
    try:
        client = create_client()
        if not client:
            return "❌ Failed to create API client"
        
        print("Sending request to API...")  # Debug print
        
        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 comprehensive, engaging, and pedagogically sound educational materials based on the provided document content. Format your response using proper HTML tags for better presentation. IMPORTANT: Do not wrap your response in ```html or ``` code blocks. Return clean HTML content only."
                },
                {
                    "role": "user",
                    "content": f"Document Content:\n{DOCUMENT_TEXT[:4000]}\n\n{prompt}"  # Limit document content to avoid token limits
                }
            ],
            max_tokens=max_tokens,
            temperature=0.7
        )
        
        result = completion.choices[0].message.content
        print(f"API response received. Length: {len(result) if result else 0}")  # Debug print
        
        # Clean the HTML response
        cleaned_result = clean_html_response(result)
        return cleaned_result
        
    except Exception as e:
        error_msg = f"❌ Error generating content: {str(e)}"
        print(f"API Error: {error_msg}")  # Debug print
        return error_msg

def create_download_file(content: str, filename: str) -> str:
    """Create downloadable HTML file"""
    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 {{
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                border-radius: 15px;
                padding: 20px;
                margin: 15px;
                box-shadow: 0 8px 25px rgba(0,0,0,0.15);
                cursor: pointer;
                transition: all 0.3s ease;
                color: white;
                position: relative;
                min-height: 150px;
                display: flex;
                flex-direction: column;
                justify-content: center;
            }}
            .flashcard:hover {{
                transform: translateY(-5px);
                box-shadow: 0 12px 35px rgba(0,0,0,0.25);
            }}
            .flashcard-front, .flashcard-back {{
                text-align: center;
            }}
            .flashcard-back {{
                display: none;
            }}
            .play-btn {{
                position: absolute;
                top: 10px;
                right: 15px;
                background: rgba(255,255,255,0.2);
                border: none;
                border-radius: 50%;
                width: 40px;
                height: 40px;
                font-size: 16px;
                color: white;
                cursor: pointer;
                transition: all 0.3s ease;
            }}
            .play-btn:hover {{
                background: rgba(255,255,255,0.3);
                transform: scale(1.1);
            }}
            .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 toggleCard(cardId) {{
                console.log('Toggling card:', cardId);
                const front = document.getElementById(cardId + '-front');
                const back = document.getElementById(cardId + '-back');
                const btn = document.getElementById(cardId + '-btn');
                
                if (front && back && btn) {{
                    if (front.style.display !== 'none') {{
                        front.style.display = 'none';
                        back.style.display = 'block';
                        btn.innerHTML = 'πŸ”„';
                    }} else {{
                        front.style.display = 'block';
                        back.style.display = 'none';
                        btn.innerHTML = '▢️';
                    }}
                }} else {{
                    console.error('Could not find elements for card:', cardId);
                }}
            }}
            
            // Alternative method - listen for clicks on flashcards
            document.addEventListener('DOMContentLoaded', function() {{
                const flashcards = document.querySelectorAll('.flashcard');
                flashcards.forEach(function(card) {{
                    card.addEventListener('click', function(e) {{
                        e.preventDefault();
                        const cardId = this.getAttribute('data-card-id');
                        if (cardId) {{
                            toggleCard(cardId);
                        }}
                    }});
                }});
                
                // Also listen for button clicks
                const playBtns = document.querySelectorAll('.play-btn');
                playBtns.forEach(function(btn) {{
                    btn.addEventListener('click', function(e) {{
                        e.stopPropagation();
                        const cardId = this.getAttribute('data-card-id');
                        if (cardId) {{
                            toggleCard(cardId);
                        }}
                    }});
                }});
            }});
        </script>
    </body>
    </html>
    """
    
    # Save to temporary file
    temp_filename = f"temp_{filename}.html"
    with open(temp_filename, 'w', encoding='utf-8') as f:
        f.write(html_template)
    
    return temp_filename

# Content generation functions with @spaces.GPU decorator
@spaces.GPU
def generate_summary():
    """Generate comprehensive summary"""
    prompt = """Create a comprehensive summary of this document with proper HTML formatting:
    
    Use these HTML tags for structure:
    - <h1> for main title
    - <h2> for section headers (Executive Summary, Key Points, etc.)
    - <h3> for subsections
    - <ul> and <li> for bullet points
    - <p> for paragraphs
    - <strong> for emphasis
    - <div class="concept-box"> for important concepts
    
    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>
    
    Remember: Return only clean HTML content without code block markers.
    """
    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:
    
    Use HTML structure with:
    - <h1> for main title: Study Notes
    - <h2> for major sections
    - <h3> for subsections
    - <ul><li> for lists
    - <div class="concept-box"> for key concepts
    - <strong> for important terms
    
    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>
    
    Remember: Return only clean HTML content without code block markers.
    """
    return generate_content(prompt)

@spaces.GPU
def generate_quiz():
    """Generate quiz questions"""
    prompt = """Create a comprehensive quiz based on this document using HTML formatting:
    
    <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.
    Remember: Return only clean HTML content without code block markers.
    """
    return generate_content(prompt, max_tokens=3000)

@spaces.GPU
def generate_flashcards():
    """Generate interactive flashcards"""
    prompt = """Create 15-20 interactive flashcards based on this document. 
    
    Format each flashcard using this exact HTML structure:
    
    <h1>🎴 Interactive Flashcards</h1>
    <p><em>Click on each card or the play button (▢️) to reveal the answer!</em></p>
    
    <div class="flashcard" data-card-id="card1">
        <button class="play-btn" data-card-id="card1" id="card1-btn">▢️</button>
        <div class="flashcard-front" id="card1-front">
            <h3>Card 1</h3>
            <p><strong>[Question/Term]</strong></p>
        </div>
        <div class="flashcard-back" id="card1-back">
            <h3>Answer</h3>
            <p>[Answer/Definition/Explanation]</p>
        </div>
    </div>
    
    Continue this pattern for each flashcard, ensuring:
    - Each card has a unique data-card-id (card1, card2, card3, etc.)
    - Button has matching data-card-id attribute
    - Front and back divs have correct IDs (card1-front, card1-back, etc.)
    - Button has correct ID (card1-btn, card2-btn, 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.
    Remember: Return only clean HTML content without code block markers.
    """
    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:
    
    <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>
    
    Remember: Return only clean HTML content without code block markers.
    """
    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:
    
    <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>
    
    Remember: Return only clean HTML content without code block markers.
    """
    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:
    
    <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.
    Remember: Return only clean HTML content without code block markers.
    """
    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:
    
    <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.
    Remember: Return only clean HTML content without code block markers.
    """
    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"

# Create Gradio interface
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 with interactive features!
        
        **New Features:** 
        - 🎴 Interactive Flashcards with Play Buttons
        - πŸ“„ HTML Formatted Responses  
        - πŸ’Ύ Download All Content as HTML Files
        - πŸ–¨οΈ Print-Ready Formats
        
        *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)
                
                # Document status indicator
                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")
                
                # HTML output with download capability
                output = gr.HTML(
                    label="Generated Content (Interactive)",
                    value="<p>Generated educational content will appear here with interactive features...</p>"
                )
                
                # Download buttons
                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/) and get your free API key
        2. **Configure:** Enter your API key and click "Configure API" 
        3. **Upload:** Upload a PDF or DOCX document (make sure it contains readable text)
        4. **Process:** Click "Process Document" to extract text
        5. **Generate:** Choose any educational content type to generate interactive HTML content
        6. **Download:** Use the "Prepare Download" button to get an HTML file with all content
        
        ### 🎯 Enhanced Content Types:
        - **πŸ“‹ Summary:** Comprehensive overview with styled HTML sections
        - **πŸ“– Study Notes:** Structured notes with highlighted key concepts
        - **πŸ“ Quiz:** Interactive quiz with styled questions and answer keys
        - **🎴 Interactive Flashcards:** Click-to-flip cards with play buttons!
        - **🧠 Mind Map:** Visual structure with styled branches
        - **πŸ“š Lesson Plan:** Complete teaching plan with time management
        - **πŸ” Concept Explanations:** Deep dive with styled concept boxes
        - **πŸ’ͺ Practice Problems:** Graded exercises with solution reveals
        
        ### ✨ New Interactive Features:
        - **🎴 Flashcards:** Click the play button (▢️) to flip cards and see answers
        - **πŸ“„ HTML Formatting:** All content now uses proper HTML styling
        - **πŸ’Ύ Download:** Get complete HTML files with embedded CSS and JavaScript
        - **πŸ–¨οΈ Print Ready:** Downloaded files include print-optimized styling
        
        ### πŸ’‘ Tips:
        - Make sure your PDF contains selectable text (not just images)
        - For best results, use documents with clear structure and headings
        - The app works with academic papers, textbooks, reports, and study materials
        - Interactive flashcards work best when viewed in the HTML output
        - Downloaded files can be opened in any web browser for offline use
        
        ### ⚑ Performance Note:
        This app uses ZeroGPU for enhanced processing. Functions will automatically utilize GPU resources when needed.
        """)
        
        # Store the last generated content for download
        last_content = gr.State("")
        last_content_type = gr.State("")
        
        # Event handlers
        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]
        )
        
        # Enhanced content generation functions that return HTML and enable download
        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)
        
        # Download preparation function
        def prepare_download(content, content_type):
            if not content or content.startswith("❌"):
                return None
            
            # Create downloadable file
            filename = f"educational_content_{content_type}"
            temp_file = create_download_file(content, filename)
            return temp_file
        
        # Content generation button handlers with download capability
        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]
        )
        
        # Download button handler
        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]
        )
        
        # Update status on app load
        def update_initial_status():
            return get_api_status(), get_document_status()
        
        app.load(
            update_initial_status,
            outputs=[setup_status, doc_status]
        )
    
    return app

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