ZeeAI1 commited on
Commit
5623a53
Β·
verified Β·
1 Parent(s): 1cd4447

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -14
app.py CHANGED
@@ -1,20 +1,163 @@
1
- from transformers import pipeline
 
2
  import streamlit as st
 
 
3
 
4
- # Load grammar correction pipeline
5
- @st.cache_resource
6
- def load_model():
7
- return pipeline("text2text-generation", model="vennify/t5-base-grammar-correction")
8
 
9
- corrector = load_model()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- # Streamlit UI
12
- st.title("Grammar Correction Assistant")
 
13
 
14
- user_input = st.text_area("Enter a sentence to correct:", "She don't like going to the gym because it make her tired.")
 
 
15
 
16
- if st.button("Correct Sentence"):
17
- with st.spinner("Correcting..."):
18
- result = corrector(user_input, max_length=100, clean_up_tokenization_spaces=True)
19
- corrected_sentence = result[0]['generated_text']
20
- st.markdown(f"**Corrected Sentence:** {corrected_sentence}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
  import streamlit as st
4
+ import google.generativeai as genai
5
+ from dotenv import load_dotenv
6
 
7
+ # Configuration
8
+ load_dotenv()
9
+ genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
10
+ model = genai.GenerativeModel('gemini-2.0-flash')
11
 
12
+ # Custom CSS for Chainlit-like appearance
13
+ st.markdown("""
14
+ <style>
15
+ /* Ensures proper contrast in dark mode */
16
+ body, .stApp {
17
+ background-color: #121212 !important;
18
+ color: #e0e0e0 !important;
19
+ }
20
+ /* Chat messages */
21
+ [data-testid="stChatMessage"] {
22
+ padding: 1rem;
23
+ border-radius: 15px;
24
+ margin: 1rem 0;
25
+ box-shadow: 0 2px 8px rgba(255,255,255,0.1);
26
+ }
27
+ /* User message */
28
+ .user-message {
29
+ background: #1e1e1e !important;
30
+ border: 1px solid #333 !important;
31
+ color: #ffffff !important;
32
+ }
33
+ /* Assistant message */
34
+ .assistant-message {
35
+ background: #2a2a2a !important;
36
+ border: 1px solid #444 !important;
37
+ color: #ffffff !important;
38
+ }
39
+ /* Chat input */
40
+ .stChatInput {
41
+ position: fixed;
42
+ bottom: 2rem;
43
+ width: 75%;
44
+ left: 50%;
45
+ transform: translateX(-50%);
46
+ background: #222 !important;
47
+ color: #fff !important;
48
+ border: 1px solid #555 !important;
49
+ }
50
+ /* Fix for buttons */
51
+ .stButton>button {
52
+ background-color: #333 !important;
53
+ color: white !important;
54
+ border: 1px solid #555 !important;
55
+ }
56
+ </style>
57
+ """, unsafe_allow_html=True)
58
 
59
+ # App header
60
+ st.title("πŸ“ Grammar Guardian")
61
+ st.caption("Hello, I'm the F&F Developers Grammatical Correction Agent. How may I help you today?")
62
 
63
+ # Initialize session state
64
+ if "history" not in st.session_state:
65
+ st.session_state.history = []
66
 
67
+ # Chat container
68
+ chat_container = st.container()
69
+
70
+ # Display history
71
+ with chat_container:
72
+ for message in st.session_state.history:
73
+ if message["role"] == "user":
74
+ with st.chat_message("user", avatar="πŸ‘€"):
75
+ st.markdown(f"**You**: {message['content']}")
76
+ else:
77
+ with st.chat_message("assistant", avatar="πŸ€–"):
78
+ st.markdown(f"**Correction**: {message['content']['correction']}")
79
+ st.markdown(f"**Explanation**: {message['content']['explanation']}")
80
+ st.markdown(f"*<small>{message['content']['timestamp']}</small>*",
81
+ unsafe_allow_html=True)
82
+
83
+ # Chat input
84
+ prompt = st.chat_input("Type here!")
85
+
86
+ if prompt:
87
+ # Add user message
88
+ with chat_container:
89
+ with st.chat_message("user", avatar="πŸ‘€"):
90
+ st.markdown(f"**You**: {prompt}")
91
+
92
+ st.session_state.history.append({"role": "user", "content": prompt})
93
+
94
+ # Generate response
95
+ with st.spinner("Analyzing..."):
96
+ try:
97
+ response = model.generate_content(
98
+ f"""You are an advanced grammar correction assistant.
99
+ When a user provides a sentence, first correct the sentence and then
100
+ explain why the correction was necessary. Highlight grammatical mistakes,
101
+ sentence structure issues, and word choice errors in a simple and understandable way.
102
+ Always provide detailed explanations to help the user learn.
103
+
104
+ Please provide the response in the following structured format:
105
+ **Correction:** <Corrected Sentence>
106
+ **Explanation:** <Brief Explanation of Errors>
107
+
108
+ Sentence: {prompt}
109
+ """
110
+ )
111
+
112
+ # Ensure response exists
113
+ response_text = response.text if response and hasattr(response, "text") else "Error in response"
114
+
115
+ # Extract correction and explanation
116
+ correction = ""
117
+ explanation = ""
118
+
119
+ if "**Correction:**" in response_text and "**Explanation:**" in response_text:
120
+ parts = response_text.split("**Explanation:**")
121
+ correction = parts[0].replace("**Correction:**", "").strip()
122
+ explanation = parts[1].strip()
123
+ else:
124
+ # Fallback if formatting isn't followed
125
+ lines = response_text.split("\n")
126
+ if lines:
127
+ correction = lines[0].strip()
128
+ explanation = " ".join(lines[1:]).strip() if len(lines) > 1 else "Explanation not provided by the model."
129
+
130
+ result = {
131
+ "correction": f"✨ {correction}",
132
+ "explanation": f"πŸ“š {explanation}",
133
+ "timestamp": time.strftime("%H:%M:%S")
134
+ }
135
+
136
+ # Add assistant message
137
+ with chat_container:
138
+ with st.chat_message("assistant", avatar="πŸ€–"):
139
+ st.markdown(f"**Correction**: {result['correction']}")
140
+ st.markdown(f"**Explanation**: {result['explanation']}")
141
+ st.markdown(f"*<small>{result['timestamp']}</small>*", unsafe_allow_html=True)
142
+
143
+ st.session_state.history.append({
144
+ "role": "assistant",
145
+ "content": result
146
+ })
147
+
148
+ except Exception as e:
149
+ st.error(f"Error processing request: {str(e)}")
150
+
151
+
152
+ # Sidebar with history controls
153
+ with st.sidebar:
154
+ st.header("Session Info")
155
+ st.write(f"Messages: {len(st.session_state.history)}")
156
+
157
+ if st.button("Clear History"):
158
+ st.session_state.history = []
159
+ st.rerun()
160
+
161
+ st.markdown("---")
162
+ st.markdown("**How to use:**")
163
+ st.markdown("1. Type your sentence\n2. Get instant feedback\n3. Review explanations")