Engr-Usman-Ali commited on
Commit
fbe04e6
Β·
verified Β·
1 Parent(s): 7c9c132

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -85
app.py CHANGED
@@ -1,24 +1,19 @@
1
  import streamlit as st
2
  from groq import Groq
 
3
 
4
- st.set_page_config(page_title="CodeCraft AI", layout="wide", initial_sidebar_state="expanded")
5
 
6
  # ========================
7
- # Groq Client
8
  # ========================
9
- client = Groq(api_key=st.secrets["GROQ_API_KEY"])
 
10
 
11
- # Sidebar model selector
12
- st.sidebar.title("βš™οΈ Settings")
13
- model_choice = st.sidebar.selectbox(
14
- "Choose AI Model",
15
- ["llama-3.1-8b-instant", "llama-3.1-70b-versatile", "mixtral-8x7b-32768"]
16
- )
17
-
18
- st.title("πŸ€– CodeCraft AI - Mini Copilot (Chat Edition)")
19
 
20
  # ========================
21
- # Session State
22
  # ========================
23
  if "generate_chat" not in st.session_state:
24
  st.session_state.generate_chat = []
@@ -27,16 +22,59 @@ if "debug_chat" not in st.session_state:
27
  if "explain_chat" not in st.session_state:
28
  st.session_state.explain_chat = []
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  # ========================
31
  # CSS
32
  # ========================
33
  st.markdown("""
34
  <style>
35
  .block-container {
36
- padding-bottom: 130px; /* leave space for input+footer */
37
  }
38
-
39
- /* Chat bubbles */
40
  .msg-user {
41
  background: #2b2f35;
42
  color: #fff;
@@ -45,7 +83,6 @@ st.markdown("""
45
  margin: 8px 0;
46
  max-width: 86%;
47
  margin-left: auto;
48
- text-align: left;
49
  word-break: break-word;
50
  }
51
  .msg-ai {
@@ -56,38 +93,28 @@ st.markdown("""
56
  margin: 8px 0;
57
  max-width: 86%;
58
  margin-right: auto;
59
- text-align: left;
60
  word-break: break-word;
61
  }
62
 
63
- /* Fixed input wrapper (row layout) */
64
- .fixed-input {
65
  position: fixed;
66
- bottom: 50px; /* leave room for footer */
67
  left: 0;
68
  right: 0;
69
  z-index: 1000;
70
- display: flex;
71
- align-items: center;
72
- gap: 8px;
73
- padding: 8px 12px;
74
  background: transparent;
75
  }
76
-
77
- /* Style for text input */
78
- .fixed-input input {
79
- flex: 1;
80
  background: #232428 !important;
81
  color: #fff !important;
82
  border-radius: 25px !important;
83
  border: none !important;
84
  padding: 12px 16px !important;
85
  font-size: 15px;
86
- outline: none !important;
87
  }
88
-
89
- /* Send button (same row) */
90
- .fixed-input button {
91
  background: #4b5563 !important;
92
  color: #fff !important;
93
  border-radius: 50% !important;
@@ -95,16 +122,13 @@ st.markdown("""
95
  height: 48px;
96
  border: none !important;
97
  font-size: 20px;
98
- cursor: pointer;
99
  }
100
-
101
- /* Footer */
102
  .fixed-footer {
103
  position: fixed;
104
  bottom: 0;
105
  left: 0;
106
  right: 0;
107
- height: 50px;
108
  display: flex;
109
  align-items: center;
110
  justify-content: center;
@@ -117,70 +141,99 @@ st.markdown("""
117
  """, unsafe_allow_html=True)
118
 
119
  # ========================
120
- # Helper: Render chat
121
- # ========================
122
- def render_chat(chat_history):
123
- for role, msg in chat_history:
124
- if role == "user":
125
- st.markdown(f'<div class="msg-user">{msg}</div>', unsafe_allow_html=True)
126
- else:
127
- st.markdown(f'<div class="msg-ai">{msg}</div>', unsafe_allow_html=True)
128
-
129
- # ========================
130
- # Chat UI
131
  # ========================
132
- def chat_ui(chat_key, system_prompt):
133
- render_chat(st.session_state[chat_key])
134
-
135
- # Fixed input row
136
- input_key = f"{chat_key}_input"
137
- send_key = f"{chat_key}_send"
138
 
139
- st.markdown('<div class="fixed-input">', unsafe_allow_html=True)
140
- user_msg = st.text_input("", key=input_key, label_visibility="collapsed", placeholder="Type your message...")
141
- send = st.button("➀", key=send_key)
 
 
 
 
 
 
 
 
 
 
 
 
142
  st.markdown('</div>', unsafe_allow_html=True)
143
 
144
- if send and user_msg.strip():
145
- # Save user message
146
- st.session_state[chat_key].append(("user", user_msg.strip()))
147
-
148
- # AI response
149
  with st.spinner("Thinking..."):
150
- try:
151
- response = client.chat.completions.create(
152
- model=model_choice,
153
- messages=[{"role": "system", "content": system_prompt}]
154
- + [{"role": role, "content": msg} for role, msg in st.session_state[chat_key]],
155
- temperature=0.4
156
- )
157
- ai_msg = response.choices[0].message.content
158
- except Exception as e:
159
- ai_msg = f"⚠️ Error: {e}"
160
-
161
- st.session_state[chat_key].append(("assistant", ai_msg))
162
- st.session_state[input_key] = ""
163
  st.rerun()
164
 
165
- # ========================
166
- # Tabs
167
- # ========================
168
- tab1, tab2, tab3 = st.tabs(["πŸ’‘ Generate Code", "πŸ›  Debug Code", "πŸ“˜ Explain Code"])
169
-
170
- with tab1:
171
- chat_ui("generate_chat", "You are a helpful coding assistant.")
172
-
173
  with tab2:
174
- chat_ui("debug_chat", "You are an expert code debugger.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
 
 
 
176
  with tab3:
177
- chat_ui("explain_chat", "You are a teacher who explains code simply.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
  # ========================
180
  # Footer
181
  # ========================
182
  st.markdown("""
183
  <div class="fixed-footer">
184
- πŸš€ CodeCraft Β· Your Partner in Coding Excellence
185
  </div>
186
  """, unsafe_allow_html=True)
 
1
  import streamlit as st
2
  from groq import Groq
3
+ import requests
4
 
5
+ st.set_page_config(page_title="CodeCraft AI", layout="wide")
6
 
7
  # ========================
8
+ # API KEYS
9
  # ========================
10
+ GROQ_API_KEY = st.secrets["GROQ_API_KEY"]
11
+ HF_API_KEY = st.secrets["HF_API_KEY"]
12
 
13
+ client = Groq(api_key=GROQ_API_KEY)
 
 
 
 
 
 
 
14
 
15
  # ========================
16
+ # Session State per tab
17
  # ========================
18
  if "generate_chat" not in st.session_state:
19
  st.session_state.generate_chat = []
 
22
  if "explain_chat" not in st.session_state:
23
  st.session_state.explain_chat = []
24
 
25
+ # ========================
26
+ # Helper Functions
27
+ # ========================
28
+ def call_groq(messages, model="llama-3.1-8b-instant"):
29
+ try:
30
+ response = client.chat.completions.create(
31
+ model=model,
32
+ messages=messages,
33
+ temperature=0.4
34
+ )
35
+ return response.choices[0].message.content
36
+ except Exception as e:
37
+ return None
38
+
39
+ def call_hf(prompt, model="mistralai/Mixtral-8x7B-Instruct-v0.1"):
40
+ try:
41
+ headers = {"Authorization": f"Bearer {HF_API_KEY}"}
42
+ payload = {"inputs": prompt}
43
+ response = requests.post(
44
+ f"https://api-inference.huggingface.co/models/{model}",
45
+ headers=headers,
46
+ json=payload,
47
+ timeout=60
48
+ )
49
+ if response.status_code == 200:
50
+ return response.json()[0]["generated_text"]
51
+ else:
52
+ return f"⚠️ HuggingFace API error: {response.text}"
53
+ except Exception as e:
54
+ return f"⚠️ HuggingFace Exception: {str(e)}"
55
+
56
+ def get_ai_response(chat_history, system_prompt, model_choice="llama-3.1-8b-instant"):
57
+ messages = [{"role": "system", "content": system_prompt}] + [
58
+ {"role": role, "content": msg} for role, msg in chat_history
59
+ ]
60
+
61
+ # Try Groq first
62
+ reply = call_groq(messages, model=model_choice)
63
+ if reply:
64
+ return reply
65
+
66
+ # Fallback: Hugging Face
67
+ prompt = "\n".join([f"{role}: {msg}" for role, msg in chat_history])
68
+ return call_hf(prompt)
69
+
70
  # ========================
71
  # CSS
72
  # ========================
73
  st.markdown("""
74
  <style>
75
  .block-container {
76
+ padding-bottom: 120px; /* space for input+footer */
77
  }
 
 
78
  .msg-user {
79
  background: #2b2f35;
80
  color: #fff;
 
83
  margin: 8px 0;
84
  max-width: 86%;
85
  margin-left: auto;
 
86
  word-break: break-word;
87
  }
88
  .msg-ai {
 
93
  margin: 8px 0;
94
  max-width: 86%;
95
  margin-right: auto;
 
96
  word-break: break-word;
97
  }
98
 
99
+ /* Fixed bottom row */
100
+ .fixed-row {
101
  position: fixed;
102
+ bottom: 50px;
103
  left: 0;
104
  right: 0;
105
  z-index: 1000;
106
+ padding: 6px 10px;
 
 
 
107
  background: transparent;
108
  }
109
+ .stTextInput > div > div > input {
 
 
 
110
  background: #232428 !important;
111
  color: #fff !important;
112
  border-radius: 25px !important;
113
  border: none !important;
114
  padding: 12px 16px !important;
115
  font-size: 15px;
 
116
  }
117
+ .stButton button {
 
 
118
  background: #4b5563 !important;
119
  color: #fff !important;
120
  border-radius: 50% !important;
 
122
  height: 48px;
123
  border: none !important;
124
  font-size: 20px;
 
125
  }
 
 
126
  .fixed-footer {
127
  position: fixed;
128
  bottom: 0;
129
  left: 0;
130
  right: 0;
131
+ height: 40px;
132
  display: flex;
133
  align-items: center;
134
  justify-content: center;
 
141
  """, unsafe_allow_html=True)
142
 
143
  # ========================
144
+ # Tabs
 
 
 
 
 
 
 
 
 
 
145
  # ========================
146
+ tab1, tab2, tab3 = st.tabs(["πŸ’‘ Generate Code", "πŸ›  Debug Code", "πŸ“˜ Explain Code"])
 
 
 
 
 
147
 
148
+ # ------------------------
149
+ # Generate Code Tab
150
+ # ------------------------
151
+ with tab1:
152
+ st.subheader("πŸ’‘ Generate Code")
153
+ for role, msg in st.session_state.generate_chat:
154
+ css_class = "msg-user" if role == "user" else "msg-ai"
155
+ st.markdown(f'<div class="{css_class}">{msg}</div>', unsafe_allow_html=True)
156
+
157
+ st.markdown('<div class="fixed-row">', unsafe_allow_html=True)
158
+ col1, col2 = st.columns([10, 1])
159
+ with col1:
160
+ gen_msg = st.text_input("Type your message...", key="gen_input", label_visibility="collapsed")
161
+ with col2:
162
+ gen_send = st.button("➀", key="gen_send")
163
  st.markdown('</div>', unsafe_allow_html=True)
164
 
165
+ if gen_send and gen_msg.strip():
166
+ st.session_state.generate_chat.append(("user", gen_msg.strip()))
 
 
 
167
  with st.spinner("Thinking..."):
168
+ ai_reply = get_ai_response(
169
+ st.session_state.generate_chat,
170
+ "You are a helpful coding assistant. Generate correct code first, then a short simple explanation."
171
+ )
172
+ st.session_state.generate_chat.append(("assistant", ai_reply))
173
+ st.session_state.gen_input = ""
 
 
 
 
 
 
 
174
  st.rerun()
175
 
176
+ # ------------------------
177
+ # Debug Code Tab
178
+ # ------------------------
 
 
 
 
 
179
  with tab2:
180
+ st.subheader("πŸ›  Debug Code")
181
+ for role, msg in st.session_state.debug_chat:
182
+ css_class = "msg-user" if role == "user" else "msg-ai"
183
+ st.markdown(f'<div class="{css_class}">{msg}</div>', unsafe_allow_html=True)
184
+
185
+ st.markdown('<div class="fixed-row">', unsafe_allow_html=True)
186
+ col1, col2 = st.columns([10, 1])
187
+ with col1:
188
+ debug_msg = st.text_input("Type your message...", key="debug_input", label_visibility="collapsed")
189
+ with col2:
190
+ debug_send = st.button("➀", key="debug_send")
191
+ st.markdown('</div>', unsafe_allow_html=True)
192
+
193
+ if debug_send and debug_msg.strip():
194
+ st.session_state.debug_chat.append(("user", debug_msg.strip()))
195
+ with st.spinner("Debugging..."):
196
+ ai_reply = get_ai_response(
197
+ st.session_state.debug_chat,
198
+ "You are an expert code debugger. Fix errors and give corrected code, then explain what changed and why."
199
+ )
200
+ st.session_state.debug_chat.append(("assistant", ai_reply))
201
+ st.session_state.debug_input = ""
202
+ st.rerun()
203
 
204
+ # ------------------------
205
+ # Explain Code Tab
206
+ # ------------------------
207
  with tab3:
208
+ st.subheader("πŸ“˜ Explain Code")
209
+ for role, msg in st.session_state.explain_chat:
210
+ css_class = "msg-user" if role == "user" else "msg-ai"
211
+ st.markdown(f'<div class="{css_class}">{msg}</div>', unsafe_allow_html=True)
212
+
213
+ st.markdown('<div class="fixed-row">', unsafe_allow_html=True)
214
+ col1, col2 = st.columns([10, 1])
215
+ with col1:
216
+ explain_msg = st.text_input("Type your message...", key="explain_input", label_visibility="collapsed")
217
+ with col2:
218
+ explain_send = st.button("➀", key="explain_send")
219
+ st.markdown('</div>', unsafe_allow_html=True)
220
+
221
+ if explain_send and explain_msg.strip():
222
+ st.session_state.explain_chat.append(("user", explain_msg.strip()))
223
+ with st.spinner("Explaining..."):
224
+ ai_reply = get_ai_response(
225
+ st.session_state.explain_chat,
226
+ "You are a teacher that explains code step by step in simple words."
227
+ )
228
+ st.session_state.explain_chat.append(("assistant", ai_reply))
229
+ st.session_state.explain_input = ""
230
+ st.rerun()
231
 
232
  # ========================
233
  # Footer
234
  # ========================
235
  st.markdown("""
236
  <div class="fixed-footer">
237
+ πŸš€ CodeCraft Β· Powered by Groq ⚑ + HuggingFace πŸ€—
238
  </div>
239
  """, unsafe_allow_html=True)