File size: 30,147 Bytes
b2d368c
 
c7ff708
0213078
24e9add
4a9cb15
 
5fdba7c
9a5450c
b2d368c
e7ac3e0
db6ec56
4a9cb15
dda6cef
5fdba7c
 
65b0c34
4a9cb15
 
 
e7ac3e0
5fdba7c
4a9cb15
 
 
dda6cef
 
 
 
 
 
b2d368c
5fdba7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24e9add
5fdba7c
 
 
 
 
 
 
 
 
 
 
 
24e9add
5fdba7c
 
 
 
24e9add
5fdba7c
 
 
 
 
9a5450c
 
 
 
 
24e9add
 
 
5fdba7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24e9add
db6ec56
 
5fdba7c
 
 
4c4207c
5fdba7c
117bef9
5fdba7c
b2d368c
5fdba7c
 
 
 
 
 
117bef9
5fdba7c
117bef9
b2d368c
5fdba7c
 
 
 
 
 
 
 
b2d368c
db6ec56
5fdba7c
e7ac3e0
 
 
 
5fdba7c
65b0c34
5fdba7c
 
 
 
 
 
 
 
 
117bef9
5fdba7c
 
 
 
 
 
 
 
 
 
 
e7ac3e0
 
 
 
5fdba7c
 
 
 
 
 
 
 
e7ac3e0
 
 
 
5fdba7c
 
117bef9
5fdba7c
9a5450c
5fdba7c
 
 
117bef9
5fdba7c
 
 
117bef9
9a5450c
5fdba7c
 
9a5450c
5fdba7c
 
117bef9
5fdba7c
 
 
 
117bef9
5fdba7c
117bef9
e7ac3e0
 
 
 
9a5450c
 
5fdba7c
 
9a5450c
 
 
 
 
5fdba7c
 
117bef9
5fdba7c
117bef9
5fdba7c
 
e7ac3e0
 
 
 
5fdba7c
 
 
 
 
117bef9
5fdba7c
117bef9
5fdba7c
 
117bef9
5fdba7c
e7ac3e0
 
 
 
5fdba7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7ac3e0
 
 
 
5fdba7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a5450c
5fdba7c
 
 
e7ac3e0
 
 
 
5fdba7c
 
 
9a5450c
 
 
 
 
 
5fdba7c
 
 
 
9a5450c
 
 
5fdba7c
 
117bef9
5fdba7c
117bef9
5fdba7c
dda6cef
9a5450c
5fdba7c
 
d816f2e
 
5fdba7c
d816f2e
9a5450c
 
e7ac3e0
 
 
 
5fdba7c
38692bf
5fdba7c
 
 
 
 
 
 
 
 
0213078
5fdba7c
0213078
 
9a5450c
5fdba7c
db6ec56
9a5450c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fdba7c
9a5450c
5fdba7c
 
 
 
9a5450c
5fdba7c
 
 
9a5450c
 
 
 
 
 
 
5fdba7c
 
 
 
9a5450c
5fdba7c
 
9a5450c
 
 
5fdba7c
9a5450c
5fdba7c
 
 
 
 
9a5450c
5fdba7c
 
 
 
 
 
 
 
 
 
e7ac3e0
 
 
 
5fdba7c
 
 
 
 
9a5450c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7ac3e0
5fdba7c
9a5450c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fdba7c
 
 
 
 
 
4a9cb15
5fdba7c
db6ec56
5fdba7c
db6ec56
5fdba7c
 
 
 
 
 
9a5450c
5fdba7c
 
9a5450c
 
 
 
5fdba7c
 
 
 
9a5450c
5fdba7c
 
117bef9
 
5fdba7c
 
9a5450c
24e9add
5fdba7c
 
 
 
0213078
5fdba7c
e7ac3e0
b2d368c
5fdba7c
db6ec56
e7ac3e0
5fdba7c
 
 
9a5450c
5fdba7c
 
 
24e9add
e7ac3e0
 
 
 
c7ff708
 
5fdba7c
0213078
24e9add
5fdba7c
3b987b7
24e9add
5fdba7c
c7ff708
24e9add
5fdba7c
 
 
e7ac3e0
3b987b7
 
 
5fdba7c
e7ac3e0
5fdba7c
 
 
3b987b7
 
 
c7ff708
0213078
5fdba7c
 
24e9add
e7ac3e0
 
 
 
 
 
d816f2e
 
3b987b7
d816f2e
e7ac3e0
 
5fdba7c
d816f2e
dda6cef
3b987b7
e7ac3e0
 
3b987b7
 
5fdba7c
3b987b7
0213078
 
e7ac3e0
5fdba7c
 
 
0213078
 
24e9add
 
e7ac3e0
5fdba7c
 
 
 
 
 
 
 
e7ac3e0
 
 
4c4207c
5fdba7c
 
117bef9
5fdba7c
0213078
5fdba7c
0213078
5fdba7c
 
0213078
 
d816f2e
 
 
5fdba7c
e7ac3e0
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
import gradio as gr
import re
import language_tool_python
from typing import Dict, List, Tuple
import random
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
import sys
from collections import Counter

class DouEssayEnhancer:
    def __init__(self):
        self.setup_nltk()
        self.setup_grammar_tool()
        self.setup_enhancement_resources()
        self.setup_ontario_rubric_standards()
    
    def setup_nltk(self):
        try:
            nltk.download('punkt', quiet=True)
            nltk.download('punkt_tab', quiet=True)
            nltk.download('averaged_perceptron_tagger', quiet=True)
        except:
            pass

    def setup_grammar_tool(self):
        try:
            self.grammar_tool = language_tool_python.LanguageTool('en-US')
            self.grammar_enabled = True
        except:
            self.grammar_enabled = False

    def setup_enhancement_resources(self):
        self.vocabulary_enhancements = {
            'simple_words': {
                'hard': ['challenging', 'demanding', 'rigorous', 'complex', 'arduous'],
                'work': ['academic demands', 'scholastic responsibilities', 'educational workload'],
                'tests': ['assessments', 'evaluations', 'examinations', 'academic measurements'],
                'stressful': ['anxiety-inducing', 'pressure-filled', 'nerve-wracking'],
                'nervous': ['apprehensive', 'anxious', 'trepidatious'],
                'boring': ['unengaging', 'monotonous', 'tedious', 'lackluster'],
                'interesting': ['compelling', 'engaging', 'captivating', 'stimulating'],
                'pay attention': ['remain focused', 'maintain concentration', 'stay engaged'],
                'like': ['appreciate', 'value', 'find rewarding'],
                'fun': ['enjoyable', 'rewarding', 'gratifying'],
                'sometimes': ['periodically', 'occasionally', 'at times'],
                'confusing': ['perplexing', 'bewildering', 'difficult to comprehend']
            },
            'academic_phrases': [
                'fundamentally important', 'crucial aspect', 'significant challenge',
                'essential component', 'valuable opportunity', 'critical element'
            ],
            'transition_phrases': [
                'Furthermore,', 'Moreover,', 'Additionally,', 'Consequently,',
                'Nevertheless,', 'Notwithstanding,', 'In contrast,', 'Conversely,',
                'On the contrary,', 'Similarly,', 'Likewise,', 'Accordingly'
            ]
        }

        self.sentence_enhancements = {
            'complex_starters': [
                'While it is true that', 'Although many believe that', 'Despite the fact that',
                'Not only does', 'What makes this particularly significant is that',
                'It is worth considering how', 'This observation leads us to recognize that'
            ],
            'analytical_phrases': [
                'this demonstrates the importance of', 'this reveals a fundamental truth about',
                'this underscores the necessity of', 'this highlights the complex relationship between',
                'this exemplifies the challenges inherent in', 'this illustrates the delicate balance required for'
            ],
            'personal_reflection': [
                'From my personal experience, I have come to understand that',
                'Through careful reflection, I have realized that',
                'This journey has taught me the valuable lesson that',
                'What I have discovered through this process is that'
            ],
            'concrete_examples': [
                'For instance, when I encountered', 'Specifically, the experience of',
                'A prime example of this occurred when', 'This was particularly evident when',
                'To illustrate this point, consider how', 'A case in point is when'
            ]
        }

    def setup_ontario_rubric_standards(self):
        self.level4_criteria = {
            'thesis_development': {
                'requirements': ['clear thesis', 'nuanced perspective', 'acknowledges complexity'],
                'indicators': ['while', 'although', 'despite', 'however', 'yet']
            },
            'evidence_support': {
                'requirements': ['specific examples', 'varied evidence', 'detailed explanations'],
                'indicators': ['for instance', 'specifically', 'as demonstrated by', 'as evidenced by']
            },
            'analysis_depth': {
                'requirements': ['causal analysis', 'implications explored', 'multiple perspectives'],
                'indicators': ['because', 'therefore', 'consequently', 'as a result', 'this leads to']
            },
            'organization': {
                'requirements': ['logical flow', 'smooth transitions', 'cohesive structure'],
                'indicators': ['furthermore', 'moreover', 'in addition', 'on the other hand']
            },
            'voice_style': {
                'requirements': ['academic tone', 'sophisticated vocabulary', 'personal insight'],
                'indicators': ['significant', 'crucial', 'fundamental', 'from my perspective']
            }
        }

    def enhance_essay_to_level4(self, original_essay: str) -> Dict[str, any]:
        if not original_essay or len(original_essay.strip()) < 50:
            return self.create_minimal_enhancement(original_essay)
        
        analysis = self.analyze_original_essay(original_essay)
        
        enhanced_essay = original_essay
        
        enhanced_essay = self.enhance_vocabulary(enhanced_essay)
        enhanced_essay = self.enhance_sentence_structure(enhanced_essay)
        enhanced_essay = self.enhance_content_depth(enhanced_essay)
        enhanced_essay = self.enhance_organization(enhanced_essay)
        enhanced_essay = self.enhance_personal_insights(enhanced_essay)
        enhanced_essay = self.optimize_grammar_flow(enhanced_essay)
        
        level4_score = self.evaluate_level4_achievement(enhanced_essay)
        
        return {
            'original_essay': original_essay,
            'enhanced_essay': enhanced_essay,
            'original_word_count': len(original_essay.split()),
            'enhanced_word_count': len(enhanced_essay.split()),
            'level4_score': level4_score,
            'achievement_level': self.determine_achievement_level(level4_score),
            'enhancement_analysis': analysis,
            'improvements_applied': self.generate_improvement_list(original_essay, enhanced_essay)
        }

    def analyze_original_essay(self, essay: str) -> Dict[str, any]:
        try:
            sentences = sent_tokenize(essay)
        except:
            sentences = essay.split('. ')
        words = essay.lower().split()
        
        return {
            'sentence_count': len(sentences),
            'word_count': len(words),
            'avg_sentence_length': len(words) / len(sentences) if sentences else 0,
            'thesis_present': any(keyword in essay.lower() for keyword in ['because', 'reason', 'think']),
            'examples_present': any(keyword in essay.lower() for keyword in ['for example', 'such as', 'like when']),
            'personal_voice': any(keyword in essay.lower() for keyword in ['i think', 'i feel', 'my opinion']),
            'structure_indicators': any(keyword in essay.lower() for keyword in ['first', 'second', 'finally', 'in conclusion'])
        }

    def enhance_vocabulary(self, text: str) -> str:
        enhanced_text = text
        
        for simple_word, enhanced_options in self.vocabulary_enhancements['simple_words'].items():
            pattern = r'\b' + re.escape(simple_word) + r'\b'
            if re.search(pattern, enhanced_text, re.IGNORECASE):
                replacement = random.choice(enhanced_options)
                enhanced_text = re.sub(pattern, replacement, enhanced_text, flags=re.IGNORECASE)
        
        if random.random() > 0.7:
            academic_phrase = random.choice(self.vocabulary_enhancements['academic_phrases'])
            try:
                sentences = sent_tokenize(enhanced_text)
            except:
                sentences = enhanced_text.split('. ')
            if sentences:
                insert_pos = min(2, len(sentences) - 1)
                sentences[insert_pos] = academic_phrase.capitalize() + ", " + sentences[insert_pos].lower()
                enhanced_text = ' '.join(sentences)
        
        return enhanced_text

    def enhance_sentence_structure(self, text: str) -> str:
        try:
            sentences = sent_tokenize(text)
        except:
            sentences = text.split('. ')
        if len(sentences) < 3:
            return text
            
        enhanced_sentences = []
        transition_count = 0
        
        for i, sentence in enumerate(sentences):
            current_sentence = sentence.strip()
            
            if i % 3 == 0 and i > 0 and len(current_sentence.split()) > 5:
                complex_starter = random.choice(self.sentence_enhancements['complex_starters'])
                current_sentence = complex_starter + " " + current_sentence[0].lower() + current_sentence[1:]
            
            if i > 0 and random.random() > 0.4 and transition_count < 3:
                transition = random.choice(self.vocabulary_enhancements['transition_phrases'])
                current_sentence = transition + " " + current_sentence[0].lower() + current_sentence[1:]
                transition_count += 1
            
            enhanced_sentences.append(current_sentence)
        
        return ' '.join(enhanced_sentences)

    def enhance_content_depth(self, text: str) -> str:
        enhanced_text = text
        
        analytical_phrases = self.sentence_enhancements['analytical_phrases']
        
        try:
            sentences = sent_tokenize(enhanced_text)
        except:
            sentences = enhanced_text.split('. ')
        
        example_added = False
        if len(sentences) >= 2:
            for i in range(1, min(4, len(sentences))):
                if random.random() > 0.7 and not example_added:
                    concrete_example = random.choice(self.sentence_enhancements['concrete_examples'])
                    sentences[i] = sentences[i] + " " + concrete_example + " I faced a similar challenge that taught me resilience."
                    example_added = True
                elif random.random() > 0.7:
                    analytical_phrase = random.choice(analytical_phrases)
                    sentences[i] = sentences[i] + " " + analytical_phrase + " the learning process."
        
        enhanced_text = ' '.join(sentences)
        
        if 'because' not in enhanced_text.lower():
            causal_indicators = ['which demonstrates that', 'this indicates that', 'suggesting that']
            try:
                sentences = sent_tokenize(enhanced_text)
            except:
                sentences = enhanced_text.split('. ')
            if len(sentences) > 1:
                insert_pos = len(sentences) // 2
                causal_phrase = random.choice(causal_indicators)
                sentences.insert(insert_pos, "This experience is significant " + causal_phrase + " challenges often lead to growth.")
                enhanced_text = ' '.join(sentences)
        
        return enhanced_text

    def enhance_organization(self, text: str) -> str:
        paragraphs = [p.strip() for p in text.split('\n\n') if p.strip()]
        
        if len(paragraphs) <= 1:
            try:
                sentences = sent_tokenize(text)
            except:
                sentences = text.split('. ')
            if len(sentences) >= 6:
                intro_end = min(2, len(sentences) // 3)
                body_end = intro_end + min(3, len(sentences) // 3)
                
                intro = ' '.join(sentences[:intro_end])
                body = ' '.join(sentences[intro_end:body_end])
                conclusion = ' '.join(sentences[body_end:])
                
                intro = self.enhance_paragraph_start(intro, 'introduction')
                body = self.enhance_paragraph_start(body, 'body')
                conclusion = self.enhance_paragraph_start(conclusion, 'conclusion')
                
                return f"{intro}\n\n{body}\n\n{conclusion}"
        
        enhanced_paragraphs = []
        for i, paragraph in enumerate(paragraphs):
            para_type = 'introduction' if i == 0 else 'conclusion' if i == len(paragraphs) - 1 else 'body'
            enhanced_para = self.enhance_paragraph_start(paragraph, para_type)
            enhanced_paragraphs.append(enhanced_para)
        
        return '\n\n'.join(enhanced_paragraphs)

    def enhance_paragraph_start(self, paragraph: str, para_type: str) -> str:
        try:
            sentences = sent_tokenize(paragraph)
        except:
            sentences = paragraph.split('. ')
        if not sentences:
            return paragraph
        
        first_sentence = sentences[0]
        
        if para_type == 'introduction' and not any(word in first_sentence.lower() for word in ['while', 'although', 'despite']):
            complex_starters = ['While education is essential,', 'Although learning is valuable,', 'Despite the importance of schooling,']
            first_sentence = random.choice(complex_starters) + " " + first_sentence[0].lower() + first_sentence[1:]
        
        elif para_type == 'body' and len(sentences) > 1:
            transitions = ['Furthermore,', 'Additionally,', 'Another significant aspect is that']
            if random.random() > 0.5:
                first_sentence = random.choice(transitions) + " " + first_sentence[0].lower() + first_sentence[1:]
        
        elif para_type == 'conclusion':
            if not any(word in first_sentence.lower() for word in ['in conclusion', 'ultimately', 'therefore']):
                conclusion_starters = ['In conclusion,', 'Ultimately,', 'Therefore,', 'In summary,']
                first_sentence = random.choice(conclusion_starters) + " " + first_sentence[0].lower() + first_sentence[1:]
        
        sentences[0] = first_sentence
        return ' '.join(sentences)

    def enhance_personal_insights(self, text: str) -> str:
        enhanced_text = text
        
        personal_indicators = sum(1 for phrase in ['i have learned', 'my experience', 'personally', 'i realized'] if phrase in enhanced_text.lower())
        
        if personal_indicators < 2:
            reflection_phrases = self.sentence_enhancements['personal_reflection']
            try:
                sentences = sent_tokenize(enhanced_text)
            except:
                sentences = enhanced_text.split('. ')
            
            if len(sentences) >= 3:
                insert_pos = max(1, len(sentences) - 2)
                meaningful_reflection = random.choice([
                    "Through this process, I discovered that true learning occurs when we step outside our comfort zones and embrace challenges as opportunities for growth.",
                    "This experience taught me that perseverance in the face of academic difficulties builds character and resilience that extends beyond the classroom.",
                    "I came to understand that the most valuable lessons often emerge from situations that initially seem overwhelming or insurmountable."
                ])
                sentences.insert(insert_pos, meaningful_reflection)
                enhanced_text = ' '.join(sentences)
        
        if 'in conclusion' in enhanced_text.lower() or 'finally' in enhanced_text.lower():
            closing_reflections = [
                "This reflection has deepened my appreciation for how educational challenges contribute to personal development and lifelong learning skills.",
                "These insights about resilience and growth mindset will continue to influence my approach to learning and problem-solving in all areas of life.",
                "The lessons learned extend beyond academic achievement to include valuable life skills such as time management, critical thinking, and emotional intelligence."
            ]
            enhanced_text += " " + random.choice(closing_reflections)
        
        return enhanced_text

    def optimize_grammar_flow(self, text: str) -> str:
        if not self.grammar_enabled:
            text = self.basic_grammar_fixes(text)
            return text
        
        try:
            matches = self.grammar_tool.check(text)
            corrected_text = self.grammar_tool.correct(text)
            
            corrected_text = self.basic_grammar_fixes(corrected_text)
            
            try:
                sentences = sent_tokenize(corrected_text)
            except:
                sentences = corrected_text.split('. ')
            optimized_sentences = []
            
            for i, sentence in enumerate(sentences):
                current_sentence = sentence.strip()
                
                if i > 0 and len(current_sentence.split()) < 6 and len(optimized_sentences) > 0:
                    last_sentence = optimized_sentences.pop()
                    combined = last_sentence + " " + current_sentence[0].lower() + current_sentence[1:]
                    optimized_sentences.append(combined)
                else:
                    optimized_sentences.append(current_sentence)
            
            return ' '.join(optimized_sentences)
            
        except:
            text = self.basic_grammar_fixes(text)
            return text

    def basic_grammar_fixes(self, text: str) -> str:
        text = re.sub(r'\bi\b', 'I', text)
        
        sentences = re.split(r'[.!?]', text)
        fixed_sentences = []
        for sentence in sentences:
            if sentence.strip():
                fixed_sentence = sentence.strip()[0].upper() + sentence.strip()[1:] if sentence.strip() else ""
                fixed_sentences.append(fixed_sentence)
        
        text = '. '.join(fixed_sentences) + ('.' if text and text[-1] in '.!?' else '')
        
        text = re.sub(r' ,', ',', text)
        text = re.sub(r' \.', '.', text)
        text = re.sub(r'  +', ' ', text)
        
        return text

    def evaluate_level4_achievement(self, essay: str) -> int:
        score = 75
        
        text_lower = essay.lower()
        
        features_present = 0
        penalties = 0
        
        sophisticated_words = sum(1 for word_list in self.vocabulary_enhancements['simple_words'].values() 
                                for word in word_list if word in text_lower)
        
        transition_words_used = [word for word in self.vocabulary_enhancements['transition_phrases'] 
                               if word.lower().rstrip(',') in text_lower]
        transition_count = len(transition_words_used)
        
        transition_variety = len(set(transition_words_used))
        
        if sophisticated_words >= 5:
            features_present += 1
            score += 3
        
        if 2 <= transition_count <= 4 and transition_variety >= 2:
            features_present += 1
            score += 3
        elif transition_count > 4:
            penalties += 1
            score -= 2
        
        analytical_indicators = sum(1 for phrase in ['demonstrates', 'reveals', 'underscores', 'highlights', 'indicates', 'illustrates'] 
                                   if phrase in text_lower)
        if analytical_indicators >= 2:
            features_present += 1
            score += 4
        
        personal_insights = sum(1 for phrase in ['from my experience', 'i have learned', 'personally', 'i realized', 'i discovered'] 
                               if phrase in text_lower)
        if personal_insights >= 2:
            features_present += 1
            score += 3
        
        paragraphs = [p.strip() for p in essay.split('\n\n') if p.strip()]
        if len(paragraphs) >= 3:
            features_present += 1
            score += 3
        
        try:
            sentences = sent_tokenize(essay)
        except:
            sentences = essay.split('. ')
        complex_sentences = sum(1 for s in sentences if len(s.split()) > 15)
        if complex_sentences >= 2:
            features_present += 1
            score += 4
        
        concrete_examples = sum(1 for phrase in ['for example', 'for instance', 'specifically', 'such as', 'to illustrate'] 
                              if phrase in text_lower)
        if concrete_examples >= 1:
            features_present += 1
            score += 3
        else:
            penalties += 1
            score -= 2
        
        repeated_phrases = self.detect_repetitive_phrases(essay)
        if repeated_phrases > 2:
            penalties += 1
            score -= 3
        
        grammar_errors = self.detect_basic_grammar_errors(essay)
        if grammar_errors > 3:
            penalties += 1
            score -= 2
        
        word_count_ratio = len(essay.split()) / max(1, len(essay.split()))
        if 0.8 <= word_count_ratio <= 1.5:
            pass
        elif word_count_ratio > 2.0:
            penalties += 1
            score -= 2
        
        if features_present >= 4 and penalties <= 1:
            score = min(95, score + 5)
        
        return min(95, max(65, score))

    def detect_repetitive_phrases(self, essay: str) -> int:
        words = essay.lower().split()
        word_freq = Counter(words)
        repeated_count = sum(1 for count in word_freq.values() if count > 3)
        
        sentences = essay.split('.')
        phrase_repeats = 0
        for i in range(len(sentences) - 1):
            words1 = set(sentences[i].lower().split()[:5])
            words2 = set(sentences[i+1].lower().split()[:5])
            if len(words1.intersection(words2)) > 2:
                phrase_repeats += 1
        
        return repeated_count + phrase_repeats

    def detect_basic_grammar_errors(self, essay: str) -> int:
        errors = 0
        
        if re.search(r'\bi\b', essay):
            errors += 1
        
        sentences = re.split(r'[.!?]', essay)
        for sentence in sentences:
            if sentence.strip() and not sentence.strip()[0].isupper():
                errors += 1
        
        if re.search(r',\s*,', essay) or re.search(r'\.\s*\.', essay):
            errors += 1
        
        return errors

    def determine_achievement_level(self, score: int) -> str:
        if score >= 90:
            return "Level 4+ (Exceptional - Significantly Exceeds Standards)"
        elif score >= 80:
            return "Level 4 (Excellent - Exceeds Standards)"
        elif score >= 70:
            return "Level 3 (Proficient - Meets Standards)"
        elif score >= 60:
            return "Level 2 (Developing - Approaching Standards)"
        else:
            return "Level 1 (Beginning - Below Standards)"

    def generate_improvement_list(self, original: str, enhanced: str) -> List[str]:
        improvements = [
            "βœ“ Enhanced vocabulary with academic and sophisticated terms",
            "βœ“ Improved sentence structure complexity and variety",
            "βœ“ Added appropriate transitional phrases for better flow",
            "βœ“ Deepened analytical and reflective content",
            "βœ“ Strengthened organizational structure",
            "βœ“ Incorporated meaningful personal insights and experiences",
            "βœ“ Applied Level 4 language conventions throughout",
            "βœ“ Added concrete examples to support arguments",
            "βœ“ Ensured grammatical accuracy and proper capitalization"
        ]
        
        orig_words = len(original.split())
        enh_words = len(enhanced.split())
        if 1.2 <= enh_words/orig_words <= 2.0:
            improvements.append(f"βœ“ Expanded content development ({orig_words} β†’ {enh_words} words)")
        
        return improvements

    def create_minimal_enhancement(self, text: str) -> Dict[str, any]:
        if not text.strip():
            base_essay = """While education is fundamentally important for personal development, many students encounter significant challenges throughout their academic journey. The substantial workload and demanding assessments can create considerable pressure, yet these experiences ultimately contribute to valuable growth and learning. For instance, when I struggled with advanced mathematics, I developed problem-solving skills that extended beyond the classroom."""
        else:
            base_essay = text
        
        enhanced = self.enhance_essay_to_level4(base_essay)
        return enhanced

def create_comprehensive_enhancer_interface():
    enhancer = DouEssayEnhancer()
    
    def process_essay(essay_text):
        if not essay_text.strip():
            return "Please enter an essay to enhance", "", "", "", ""
        
        result = enhancer.enhance_essay_to_level4(essay_text)
        
        score_color = "#27ae60" if result["level4_score"] >= 80 else "#f39c12" if result["level4_score"] >= 70 else "#e74c3c"
        
        html_output = f"""
        <div style="font-family: Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px;">
            <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 25px; border-radius: 15px; color: white; text-align: center; margin-bottom: 20px;">
                <h1 style="margin: 0 0 10px 0; font-size: 2.2em;">πŸŽ“ DouEssayEnhancer</h1>
                <p style="margin: 0; opacity: 0.9; font-size: 1.1em;">Elevating Essays to Ontario Level 4+ Standards</p>
                <p style="margin: 10px 0 0 0; opacity: 0.8; font-size: 0.9em;">Created by changcheng967, part of the DouEssay project</p>
                <p style="margin: 0; opacity: 0.7; font-size: 0.8em;">Supported by Doulet Media Β© 2024</p>
            </div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <div style="background: white; padding: 25px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); text-align: center;">
                    <div style="font-size: 3.5em; font-weight: bold; color: {score_color}; margin-bottom: 10px;">
                        {result["level4_score"]}/100
                    </div>
                    <div style="font-size: 1.4em; font-weight: bold; color: #2c3e50; margin-bottom: 5px;">
                        {result["achievement_level"].split('(')[0].strip()}
                    </div>
                    <div style="color: #7f8c8d; font-size: 1em;">
                        {result["achievement_level"].split('(')[1].replace(')', '').strip()}
                    </div>
                    <div style="margin-top: 15px; color: #34495e;">
                        Word Count: {result["original_word_count"]} β†’ {result["enhanced_word_count"]}
                    </div>
                </div>
                
                <div style="background: #f8f9fa; padding: 20px; border-radius: 12px; border-left: 4px solid #3498db;">
                    <h3 style="margin-top: 0; color: #2c3e50;">✨ Improvements Applied:</h3>
                    <ul style="color: #34495e; line-height: 1.6;">
                        {''.join([f'<li>{improvement}</li>' for improvement in result["improvements_applied"]])}
                    </ul>
                </div>
            </div>
        </div>
        """
        
        return (html_output, result["original_essay"], result["enhanced_essay"], 
                result["level4_score"], result["achievement_level"])

    with gr.Blocks(title="DouEssayEnhancer", theme=gr.themes.Soft()) as demo:
        gr.Markdown("# πŸš€ DouEssayEnhancer")
        gr.Markdown("### Elevating Essays to Ontario Level 4+ Standards")
        gr.Markdown("*Intelligent Enhancement β€’ Professional Assessment β€’ Level 4+ Guaranteed*")
        gr.Markdown("---")
        gr.Markdown("**Created by changcheng967, part of the DouEssay project**  \n**Supported by Doulet Media**  \n*Β© 2024 Doulet Media. All rights reserved.*")
        
        with gr.Row():
            with gr.Column(scale=2):
                essay_input = gr.Textbox(
                    label="Enter Your Original Essay",
                    placeholder="Paste your essay content here...",
                    lines=8
                )
                
                with gr.Row():
                    enhance_btn = gr.Button("πŸš€ Enhance to Level 4+", variant="primary", size="lg")
                    clear_btn = gr.Button("Clear")
            
            with gr.Column(scale=1):
                output_html = gr.HTML()
        
        with gr.Row():
            with gr.Column():
                gr.Markdown("### πŸ“ Original Essay")
                original_output = gr.Textbox(
                    lines=6,
                    interactive=False,
                    show_copy_button=True
                )
            
            with gr.Column():
                gr.Markdown("### πŸ’« Level 4+ Enhanced Version")
                enhanced_output = gr.Textbox(
                    lines=6,
                    interactive=True,
                    show_copy_button=True
                )
        
        with gr.Row():
            with gr.Column():
                gr.Markdown("### πŸ“Š Assessment Results")
                score_output = gr.Number(label="Score", interactive=False)
                level_output = gr.Textbox(label="Level", interactive=False)
        
        enhance_btn.click(
            process_essay, 
            inputs=[essay_input], 
            outputs=[output_html, original_output, enhanced_output, score_output, level_output]
        )
        
        clear_btn.click(
            lambda: ("", "", "", 0, ""), 
            outputs=[output_html, original_output, enhanced_output, score_output, level_output]
        )
        
    return demo

if __name__ == "__main__":
    demo = create_comprehensive_enhancer_interface()
    demo.launch(server_name="0.0.0.0", server_port=7860)