ZeeAI1 commited on
Commit
917c41b
·
verified ·
1 Parent(s): 5623a53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -135
app.py CHANGED
@@ -2,162 +2,71 @@ 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")
 
2
  import time
3
  import streamlit as st
4
  import google.generativeai as genai
5
+ from google.auth import default
6
  from dotenv import load_dotenv
7
 
8
+ # Load environment variables
9
  load_dotenv()
 
 
10
 
11
+ # Check for credentials and configure Gemini
12
+ if os.getenv("GOOGLE_APPLICATION_CREDENTIALS"):
13
+ credentials, _ = default()
14
+ genai.configure(credentials=credentials)
15
+ else:
16
+ st.error("❌ GOOGLE_APPLICATION_CREDENTIALS not set in the environment.")
17
+ st.stop()
18
+
19
+ # Initialize the model
20
+ model = genai.GenerativeModel("gemini-2.0-pro")
21
+
22
+ # Custom Streamlit styling (optional)
23
  st.markdown("""
24
  <style>
25
+ body, .stApp { background-color: #121212 !important; color: #e0e0e0 !important; }
26
+ .stChatInput { background: #222 !important; border: 1px solid #555 !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  </style>
28
  """, unsafe_allow_html=True)
29
 
30
+ # App Title
31
+ st.title("📚 Grammar Guardian")
32
+ st.caption("Correct grammar, get explanations, and improve your writing skills!")
33
 
34
  # Initialize session state
35
  if "history" not in st.session_state:
36
  st.session_state.history = []
37
 
38
+ # Display chat history
39
+ for message in st.session_state.history:
40
+ role, content = message["role"], message["content"]
41
+ with st.chat_message(role):
42
+ st.markdown(content)
 
 
 
 
 
 
 
 
 
 
43
 
44
  # Chat input
45
+ prompt = st.chat_input("Write a sentence you'd like to improve...")
46
 
47
  if prompt:
48
+ with st.chat_message("user"):
49
+ st.markdown(prompt)
 
 
 
50
  st.session_state.history.append({"role": "user", "content": prompt})
51
 
 
52
  with st.spinner("Analyzing..."):
53
  try:
54
+ full_prompt = f"""
55
+ You are an advanced grammar assistant. Correct the given sentence and explain the changes clearly.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ Respond in the following format:
58
+ **Correction:** <Corrected Sentence>
59
+ **Explanation:** <Why you corrected it>
60
 
61
+ Sentence: {prompt}
62
+ """
63
+ response = model.generate_content(full_prompt)
64
+ result = response.text
65
+
66
+ st.session_state.history.append({"role": "assistant", "content": result})
67
+
68
+ with st.chat_message("assistant"):
69
+ st.markdown(result)
70
+
71
+ except Exception as e:
72
+ st.error(f"Error: {e}")