murat4595 commited on
Commit
7565dd4
·
verified ·
1 Parent(s): f684b64

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -26
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import gradio as gr
2
  from transformers import pipeline
3
- import os
4
 
5
  # --- Model Loading ---
6
  # We use the 'text2text-generation' pipeline.
@@ -18,52 +18,132 @@ except Exception as e:
18
  print(f"Error loading model: {e}")
19
  corrector = None
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  # --- Core Logic ---
22
- def correct_grammar(text):
23
  if not text or not text.strip():
24
  return ""
25
 
26
  if corrector is None:
27
- return "Error: The model failed to load."
28
 
29
  try:
 
30
  results = corrector(text, max_length=128)
31
  corrected_text = results[0]['generated_text']
32
- return corrected_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  except Exception as e:
34
- return f"Error during processing: {str(e)}"
35
 
36
  # --- User Interface ---
37
- with gr.Blocks(title="Grammar Corrector", theme=gr.themes.Soft()) as demo:
38
- # UPDATED: Removed Emoji and "GB"
 
 
 
 
39
  gr.Markdown(
40
  """
41
- # Grammar Correction AI
42
- Type a sentence below to check your text.
43
  """
44
  )
45
 
46
  with gr.Row():
47
- with gr.Column():
48
  input_box = gr.Textbox(
49
- label="Input Text",
50
- placeholder="Example: I has went to the store...",
51
- lines=4
52
  )
53
- # UPDATED: Button text changed
54
- submit_btn = gr.Button("Check My Text", variant="primary")
55
 
56
- with gr.Column():
57
- output_box = gr.Textbox(
58
- label="Corrected Output",
59
- lines=4,
60
- interactive=False
61
- )
62
-
63
- submit_btn.click(fn=correct_grammar, inputs=input_box, outputs=output_box)
64
- input_box.submit(fn=correct_grammar, inputs=input_box, outputs=output_box)
65
 
66
- gr.Markdown("Powered by HamadML/grammer_correction")
 
67
 
68
  if __name__ == "__main__":
69
- demo.launch()
 
1
  import gradio as gr
2
  from transformers import pipeline
3
+ import difflib
4
 
5
  # --- Model Loading ---
6
  # We use the 'text2text-generation' pipeline.
 
18
  print(f"Error loading model: {e}")
19
  corrector = None
20
 
21
+ # --- Helper Functions for Scoring & Visuals ---
22
+
23
+ def diff_texts(text1, text2):
24
+ """
25
+ Compares two strings and returns HTML highlighting differences.
26
+ Red strikethrough for deletions, Green bold for insertions.
27
+ """
28
+ d = difflib.SequenceMatcher(None, text1, text2)
29
+ html = []
30
+ for tag, i1, i2, j1, j2 in d.get_opcodes():
31
+ if tag == 'delete':
32
+ # Mistake: Red strikethrough
33
+ html.append(f'<span style="color: #ef4444; text-decoration: line-through; background-color: #fee2e2; padding: 0 2px; border-radius: 2px;">{text1[i1:i2]}</span>')
34
+ elif tag == 'insert':
35
+ # Correction: Green bold
36
+ html.append(f'<span style="color: #16a34a; font-weight: bold; background-color: #dcfce7; padding: 0 2px; border-radius: 2px;">{text2[j1:j2]}</span>')
37
+ elif tag == 'replace':
38
+ # Mistake -> Correction
39
+ html.append(f'<span style="color: #ef4444; text-decoration: line-through; background-color: #fee2e2; padding: 0 2px; border-radius: 2px;">{text1[i1:i2]}</span>')
40
+ html.append(f'<span style="color: #16a34a; font-weight: bold; background-color: #dcfce7; padding: 0 2px; border-radius: 2px;">{text2[j1:j2]}</span>')
41
+ else:
42
+ # Unchanged text
43
+ html.append(text1[i1:i2])
44
+ return "".join(html)
45
+
46
+ def calculate_rubric_score(original, corrected):
47
+ """
48
+ Generates a simple score and feedback based on text similarity.
49
+ """
50
+ matcher = difflib.SequenceMatcher(None, original, corrected)
51
+ similarity = matcher.ratio() # 0.0 to 1.0
52
+
53
+ # Calculate score out of 100
54
+ score = int(similarity * 100)
55
+
56
+ if score == 100:
57
+ feedback = "Perfect! Your grammar is flawless."
58
+ color = "#16a34a" # Green
59
+ elif score >= 90:
60
+ feedback = "Excellent work! Just a few minor tweaks needed."
61
+ color = "#16a34a"
62
+ elif score >= 70:
63
+ feedback = "Good effort. You have some grammar errors to fix."
64
+ color = "#ca8a04" # Yellow/Orange
65
+ else:
66
+ feedback = "Needs improvement. Pay close attention to the corrections below."
67
+ color = "#dc2626" # Red
68
+
69
+ return score, feedback, color
70
+
71
  # --- Core Logic ---
72
+ def evaluate_text(text):
73
  if not text or not text.strip():
74
  return ""
75
 
76
  if corrector is None:
77
+ return "<p style='color:red;'>Error: The model failed to load.</p>"
78
 
79
  try:
80
+ # 1. Get corrected text from AI
81
  results = corrector(text, max_length=128)
82
  corrected_text = results[0]['generated_text']
83
+
84
+ # 2. Generate Visual Diff
85
+ diff_html = diff_texts(text, corrected_text)
86
+
87
+ # 3. Calculate Score
88
+ score, feedback, color = calculate_rubric_score(text, corrected_text)
89
+
90
+ # 4. Construct HTML Report
91
+ report_html = f"""
92
+ <div style="font-family: sans-serif; padding: 24px; border: 1px solid #e5e7eb; border-radius: 12px; background: white; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">
93
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; border-bottom: 2px solid #f3f4f6; padding-bottom: 15px;">
94
+ <h2 style="margin: 0; color: #1f2937; font-size: 1.5em;">Teacher's Report</h2>
95
+ <div style="background: {color}; color: white; padding: 8px 20px; border-radius: 99px; font-weight: bold; font-size: 1.2em;">
96
+ {score}/100
97
+ </div>
98
+ </div>
99
+
100
+ <div style="margin-bottom: 25px;">
101
+ <p style="color: #6b7280; margin: 0 0 8px 0; font-size: 0.85em; text-transform: uppercase; letter-spacing: 0.1em; font-weight: bold;">Feedback</p>
102
+ <p style="margin: 0; color: #374151; font-size: 1.1em; font-style: italic;">"{feedback}"</p>
103
+ </div>
104
+
105
+ <div>
106
+ <p style="color: #6b7280; margin: 0 0 12px 0; font-size: 0.85em; text-transform: uppercase; letter-spacing: 0.1em; font-weight: bold;">Correction View</p>
107
+ <div style="line-height: 1.8; font-size: 1.2em; color: #1f2937; background: #f9fafb; padding: 15px; border-radius: 8px; border: 1px solid #e5e7eb;">
108
+ {diff_html}
109
+ </div>
110
+ </div>
111
+ </div>
112
+ """
113
+ return report_html
114
+
115
  except Exception as e:
116
+ return f"<p style='color:red;'>Error during processing: {str(e)}</p>"
117
 
118
  # --- User Interface ---
119
+ # CSS to hide footer and standard elements
120
+ css = """
121
+ footer {display: none !important;}
122
+ """
123
+
124
+ with gr.Blocks(title="Grammar Evaluator", theme=gr.themes.Soft(), css=css) as demo:
125
  gr.Markdown(
126
  """
127
+ # 📝 AI Grammar Teacher
128
+ Type your sentence below. The AI will grade it, cross out mistakes in <span style='color: red; text-decoration: line-through;'>red</span>, and write corrections in <span style='color: green; font-weight: bold;'>green</span>.
129
  """
130
  )
131
 
132
  with gr.Row():
133
+ with gr.Column(scale=1):
134
  input_box = gr.Textbox(
135
+ label="Student Writing",
136
+ placeholder="Example: I has went to the store yesterday...",
137
+ lines=8
138
  )
139
+ submit_btn = gr.Button("Check My Text", variant="primary", size="lg")
 
140
 
141
+ with gr.Column(scale=1):
142
+ # Changed to HTML to render the colored report
143
+ output_html = gr.HTML(label="Evaluation Report")
 
 
 
 
 
 
144
 
145
+ submit_btn.click(fn=evaluate_text, inputs=input_box, outputs=output_html)
146
+ input_box.submit(fn=evaluate_text, inputs=input_box, outputs=output_html)
147
 
148
  if __name__ == "__main__":
149
+ demo.launch(show_api=False)