import gradio as gr from transformers import pipeline import difflib # --- Model Loading --- # We use the 'text2text-generation' pipeline. # device=-1 forces CPU usage, which is required for the free tier. print("Initializing model...") try: corrector = pipeline( "text2text-generation", model="HamadML/grammer_correction", device=-1 ) print("Model loaded successfully.") except Exception as e: print(f"Error loading model: {e}") corrector = None # --- Helper Functions for Scoring & Visuals --- def diff_texts(text1, text2): """ Compares two strings and returns HTML highlighting differences. Red strikethrough for deletions, Green bold for insertions. """ d = difflib.SequenceMatcher(None, text1, text2) html = [] for tag, i1, i2, j1, j2 in d.get_opcodes(): if tag == 'delete': # Mistake: Red strikethrough html.append(f'{text1[i1:i2]}') elif tag == 'insert': # Correction: Green bold html.append(f'{text2[j1:j2]}') elif tag == 'replace': # Mistake -> Correction html.append(f'{text1[i1:i2]}') html.append(f'{text2[j1:j2]}') else: # Unchanged text html.append(text1[i1:i2]) return "".join(html) def calculate_rubric_score(original, corrected): """ Generates a simple score and feedback based on text similarity. """ matcher = difflib.SequenceMatcher(None, original, corrected) similarity = matcher.ratio() # 0.0 to 1.0 # Calculate score out of 100 score = int(similarity * 100) if score == 100: feedback = "Perfect! Your grammar is flawless." color = "#16a34a" # Green elif score >= 90: feedback = "Excellent work! Just a few minor tweaks needed." color = "#16a34a" elif score >= 70: feedback = "Good effort. You have some grammar errors to fix." color = "#ca8a04" # Yellow/Orange else: feedback = "Needs improvement. Pay close attention to the corrections below." color = "#dc2626" # Red return score, feedback, color # --- Core Logic --- def evaluate_text(text): if not text or not text.strip(): return "" if corrector is None: return "

Error: The model failed to load.

" try: # 1. Get corrected text from AI results = corrector(text, max_length=128) corrected_text = results[0]['generated_text'] # 2. Generate Visual Diff diff_html = diff_texts(text, corrected_text) # 3. Calculate Score score, feedback, color = calculate_rubric_score(text, corrected_text) # 4. Construct HTML Report report_html = f"""

Teacher's Report

{score}/100

Feedback

"{feedback}"

Correction View

{diff_html}
""" return report_html except Exception as e: return f"

Error during processing: {str(e)}

" # --- User Interface --- # CSS to hide footer and API links visually css = """ footer {display: none !important;} .api-link {display: none !important;} """ with gr.Blocks(title="Grammar Evaluator", theme=gr.themes.Soft(), css=css) as demo: gr.Markdown( """ # 📝 AI Grammar Tool (Helper) Type your sentence below. The AI will grade it, cross out mistakes in red, and write corrections in green. """ ) # Vertical Layout input_box = gr.Textbox( label="Student Writing", placeholder="Example: I has went to the store yesterday...", lines=5 ) submit_btn = gr.Button("Check My Text", variant="primary", size="lg") output_html = gr.HTML(label="Evaluation Report") submit_btn.click(fn=evaluate_text, inputs=input_box, outputs=output_html) input_box.submit(fn=evaluate_text, inputs=input_box, outputs=output_html) if __name__ == "__main__": demo.launch()