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"""

🎓 DouEssayEnhancer

Elevating Essays to Ontario Level 4+ Standards

Created by changcheng967, part of the DouEssay project

Supported by Doulet Media © 2024

{result["level4_score"]}/100
{result["achievement_level"].split('(')[0].strip()}
{result["achievement_level"].split('(')[1].replace(')', '').strip()}
Word Count: {result["original_word_count"]} → {result["enhanced_word_count"]}

✨ Improvements Applied:

    {''.join([f'
  • {improvement}
  • ' for improvement in result["improvements_applied"]])}
""" 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)