Artificial-superintelligence commited on
Commit
da7ac0b
·
verified ·
1 Parent(s): 9a7d198

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -134
app.py CHANGED
@@ -4,6 +4,8 @@ from pygments import highlight
4
  from pygments.lexers import get_lexer_by_name
5
  from pygments.formatters import HtmlFormatter
6
  import html
 
 
7
 
8
  # Configure the Gemini API
9
  genai.configure(api_key=st.secrets["GOOGLE_API_KEY"])
@@ -19,13 +21,24 @@ generation_config = {
19
  model = genai.GenerativeModel(
20
  model_name="gemini-1.5-pro",
21
  generation_config=generation_config,
22
- system_instruction="""You are Ath, a highly knowledgeable and skilled code assistant with expertise across multiple programming languages, frameworks, and paradigms. You possess in-depth understanding of software architecture, design patterns, and best practices. Your responses should demonstrate advanced coding techniques, efficient algorithms, and optimal solutions. Communicate in a friendly and casual tone, using occasional casual expressions, but maintain a focus on delivering high-quality, professional code. Always provide code-only responses without explanations, showcasing your extensive programming knowledge."""
23
  )
24
- chat_session = model.start_chat(history=[])
 
 
 
25
 
26
  def generate_response(user_input):
27
  try:
28
- response = chat_session.send_message(user_input)
 
 
 
 
 
 
 
 
29
  return response.text
30
  except Exception as e:
31
  return f"An error occurred: {e}"
@@ -37,154 +50,77 @@ def create_code_block(code, language):
37
  css = formatter.get_style_defs('.source')
38
  return highlighted_code, css
39
 
 
 
 
 
 
 
 
 
 
 
 
40
  # Streamlit UI setup
41
  st.set_page_config(page_title="Advanced AI Code Assistant", page_icon="💻", layout="wide")
42
 
43
- st.markdown("""
44
- <style>
45
- @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');
46
-
47
- body {
48
- font-family: 'Roboto', sans-serif;
49
- background-color: #e9ecef;
50
- color: #212529;
51
- }
52
- .stApp {
53
- max-width: 1200px;
54
- margin: 0 auto;
55
- padding: 2rem;
56
- }
57
- .main-container {
58
- background: #ffffff;
59
- border-radius: 12px;
60
- padding: 2rem;
61
- box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
62
- }
63
- h1 {
64
- font-size: 2.5rem;
65
- font-weight: 600;
66
- color: #0d6efd;
67
- text-align: center;
68
- margin-bottom: 1rem;
69
- }
70
- .subtitle {
71
- font-size: 1rem;
72
- text-align: center;
73
- color: #6c757d;
74
- margin-bottom: 2rem;
75
- }
76
- .stTextArea textarea {
77
- border: 1px solid #ced4da;
78
- border-radius: 8px;
79
- font-size: 1rem;
80
- padding: 0.75rem;
81
- transition: border-color 0.3s;
82
- }
83
- .stTextArea textarea:focus {
84
- border-color: #0d6efd;
85
- outline: none;
86
- }
87
- .stButton button {
88
- background-color: #0d6efd;
89
- color: white;
90
- border: none;
91
- border-radius: 8px;
92
- font-size: 1rem;
93
- font-weight: 500;
94
- padding: 0.5rem 1.5rem;
95
- cursor: pointer;
96
- transition: background-color 0.3s, transform 0.2s;
97
- }
98
- .stButton button:hover {
99
- background-color: #0b5ed7;
100
- transform: translateY(-2px);
101
- }
102
- .output-container {
103
- background: #f8f9fa;
104
- border-radius: 8px;
105
- padding: 1rem;
106
- margin-top: 1.5rem;
107
- border: 1px solid #dee2e6;
108
- }
109
- .code-block {
110
- background-color: #343a40;
111
- border-radius: 8px;
112
- padding: 1rem;
113
- margin-top: 1rem;
114
- overflow-x: auto;
115
- }
116
- .stAlert {
117
- background-color: #cce5ff;
118
- color: #004085;
119
- border-radius: 8px;
120
- border: none;
121
- padding: 1rem;
122
- margin-bottom: 1rem;
123
- }
124
- .stSpinner {
125
- color: #0d6efd;
126
- }
127
- /* Custom scrollbar */
128
- ::-webkit-scrollbar {
129
- width: 8px;
130
- }
131
- ::-webkit-scrollbar-track {
132
- background: #f1f3f5;
133
- border-radius: 4px;
134
- }
135
- ::-webkit-scrollbar-thumb {
136
- background: #868e96;
137
- border-radius: 4px;
138
- }
139
- ::-webkit-scrollbar-thumb:hover {
140
- background: #495057;
141
- }
142
- .source {
143
- font-family: 'Fira Code', monospace;
144
- font-size: 0.9rem;
145
- line-height: 1.5;
146
- }
147
- .source .linenos {
148
- color: #6c757d;
149
- padding-right: 8px;
150
- border-right: 1px solid #495057;
151
- user-select: none;
152
- }
153
- .source pre {
154
- margin: 0;
155
- padding: 0;
156
- }
157
- </style>
158
- """, unsafe_allow_html=True)
159
 
160
  st.markdown('<div class="main-container">', unsafe_allow_html=True)
161
  st.title("💻 Advanced AI Code Assistant")
162
  st.markdown('<p class="subtitle">Powered by Google Gemini - Expert-level coding solutions</p>', unsafe_allow_html=True)
163
 
164
- prompt = st.text_area("What advanced coding challenge can I assist you with today?", height=100)
 
 
 
165
 
166
- if st.button("Generate Expert Code"):
167
  if prompt.strip() == "":
168
  st.error("Please enter a valid prompt.")
169
  else:
170
- with st.spinner("Generating advanced code solution..."):
171
  completed_text = generate_response(prompt)
172
  if "An error occurred" in completed_text:
173
  st.error(completed_text)
174
  else:
175
- st.success("Expert-level code generated successfully!")
176
 
177
- # Attempt to determine the language (this is a simple guess, you might want to improve this)
178
- language = "python" if "def " in completed_text or "import " in completed_text else "javascript"
179
-
180
- highlighted_code, css = create_code_block(completed_text, language)
181
-
182
- st.markdown(f'<style>{css}</style>', unsafe_allow_html=True)
183
- st.markdown('<div class="output-container">', unsafe_allow_html=True)
184
- st.markdown('<div class="code-block">', unsafe_allow_html=True)
185
- st.markdown(highlighted_code, unsafe_allow_html=True)
186
- st.markdown('</div>', unsafe_allow_html=True)
187
- st.markdown('</div>', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
 
189
  st.markdown("""
190
  <div style='text-align: center; margin-top: 2rem; color: #6c757d;'>
 
4
  from pygments.lexers import get_lexer_by_name
5
  from pygments.formatters import HtmlFormatter
6
  import html
7
+ import re
8
+ import time
9
 
10
  # Configure the Gemini API
11
  genai.configure(api_key=st.secrets["GOOGLE_API_KEY"])
 
21
  model = genai.GenerativeModel(
22
  model_name="gemini-1.5-pro",
23
  generation_config=generation_config,
24
+ system_instruction="""You are Ath, an advanced AI code assistant with expertise across multiple programming languages, frameworks, and paradigms. Your knowledge spans software architecture, design patterns, algorithms, and cutting-edge technologies. Provide high-quality, optimized code solutions with explanations when requested. Adapt your communication style based on the user's expertise level, offering additional context for beginners and diving into complex topics for experts. You can generate code, explain concepts, debug issues, and provide best practices. Always prioritize security, efficiency, and maintainability in your solutions."""
25
  )
26
+
27
+ # Initialize session state for chat history
28
+ if 'chat_history' not in st.session_state:
29
+ st.session_state.chat_history = []
30
 
31
  def generate_response(user_input):
32
  try:
33
+ # Add user message to chat history
34
+ st.session_state.chat_history.append({"role": "user", "content": user_input})
35
+
36
+ # Generate response
37
+ response = model.generate_content(st.session_state.chat_history)
38
+
39
+ # Add AI response to chat history
40
+ st.session_state.chat_history.append({"role": "assistant", "content": response.text})
41
+
42
  return response.text
43
  except Exception as e:
44
  return f"An error occurred: {e}"
 
50
  css = formatter.get_style_defs('.source')
51
  return highlighted_code, css
52
 
53
+ def detect_language(code):
54
+ # Simple language detection based on keywords or syntax
55
+ if re.search(r'\b(def|import|class)\b', code):
56
+ return 'python'
57
+ elif re.search(r'\b(function|var|let|const)\b', code):
58
+ return 'javascript'
59
+ elif re.search(r'\b(public|private|class)\b', code):
60
+ return 'java'
61
+ else:
62
+ return 'text' # Default to plain text if language can't be determined
63
+
64
  # Streamlit UI setup
65
  st.set_page_config(page_title="Advanced AI Code Assistant", page_icon="💻", layout="wide")
66
 
67
+ # ... (Keep the existing CSS styles) ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  st.markdown('<div class="main-container">', unsafe_allow_html=True)
70
  st.title("💻 Advanced AI Code Assistant")
71
  st.markdown('<p class="subtitle">Powered by Google Gemini - Expert-level coding solutions</p>', unsafe_allow_html=True)
72
 
73
+ # Add a selectbox for different modes
74
+ mode = st.selectbox("Choose a mode:", ["Code Generation", "Code Explanation", "Debugging", "Best Practices"])
75
+
76
+ prompt = st.text_area(f"Enter your {mode.lower()} request:", height=100)
77
 
78
+ if st.button("Generate Response"):
79
  if prompt.strip() == "":
80
  st.error("Please enter a valid prompt.")
81
  else:
82
+ with st.spinner(f"Generating {mode.lower()} response..."):
83
  completed_text = generate_response(prompt)
84
  if "An error occurred" in completed_text:
85
  st.error(completed_text)
86
  else:
87
+ st.success(f"{mode} response generated successfully!")
88
 
89
+ # Split the response into code and explanation
90
+ code_blocks = re.split(r'```(\w+)?\n', completed_text)
91
+ for i in range(1, len(code_blocks), 2):
92
+ language = code_blocks[i] if code_blocks[i] else detect_language(code_blocks[i+1])
93
+ code = code_blocks[i+1]
94
+
95
+ highlighted_code, css = create_code_block(code, language)
96
+
97
+ st.markdown(f'<style>{css}</style>', unsafe_allow_html=True)
98
+ st.markdown('<div class="output-container">', unsafe_allow_html=True)
99
+ st.markdown('<div class="code-block">', unsafe_allow_html=True)
100
+ st.markdown(highlighted_code, unsafe_allow_html=True)
101
+ st.markdown('</div>', unsafe_allow_html=True)
102
+ st.markdown('</div>', unsafe_allow_html=True)
103
+
104
+ # Add explanation if available
105
+ if i+2 < len(code_blocks):
106
+ st.markdown(code_blocks[i+2])
107
+
108
+ # Display chat history
109
+ st.subheader("Conversation History")
110
+ for message in st.session_state.chat_history:
111
+ st.text(f"{message['role'].capitalize()}: {message['content']}")
112
+
113
+ # Add a clear button for chat history
114
+ if st.button("Clear Conversation History"):
115
+ st.session_state.chat_history = []
116
+ st.success("Conversation history cleared!")
117
+
118
+ # Add a feedback section
119
+ st.subheader("Feedback")
120
+ feedback = st.text_area("How can we improve? (Optional)")
121
+ if st.button("Submit Feedback"):
122
+ # Here you would typically send this feedback to a database or email
123
+ st.success("Thank you for your feedback!")
124
 
125
  st.markdown("""
126
  <div style='text-align: center; margin-top: 2rem; color: #6c757d;'>