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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -212
app.py CHANGED
@@ -2,19 +2,38 @@ 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 = []
20
  if "debug_chat" not in st.session_state:
@@ -22,218 +41,126 @@ if "debug_chat" not in st.session_state:
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;
81
- padding: 10px 14px;
82
- border-radius: 18px;
83
- margin: 8px 0;
84
- max-width: 86%;
85
- margin-left: auto;
86
- word-break: break-word;
87
- }
88
- .msg-ai {
89
- background: transparent;
90
- color: #d0d0d0;
91
- padding: 10px 14px;
92
- border-radius: 12px;
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;
121
- width: 48px;
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;
135
- font-size: 14px;
136
- color: #9aa0a6;
137
- background: transparent;
138
- z-index: 999;
139
- }
140
- </style>
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)
 
2
  from groq import Groq
3
  import requests
4
 
5
+ # =======================
6
+ # API Clients
7
+ # =======================
8
+ client = Groq(api_key=st.secrets["GROQ_API_KEY"])
 
 
9
  HF_API_KEY = st.secrets["HF_API_KEY"]
10
 
11
+ # =======================
12
+ # Sidebar Settings
13
+ # =======================
14
+ st.sidebar.title("βš™οΈ Settings")
15
+ provider_choice = st.sidebar.radio(
16
+ "Choose Provider",
17
+ ["Groq", "Hugging Face"]
18
+ )
19
+
20
+ # Model selector depends on provider
21
+ if provider_choice == "Groq":
22
+ model_choice = st.sidebar.selectbox(
23
+ "Groq Model",
24
+ ["llama-3.1-8b-instant", "llama-3.1-70b-versatile", "mixtral-8x7b-32768"]
25
+ )
26
+ else:
27
+ model_choice = st.sidebar.selectbox(
28
+ "HF Model",
29
+ ["mistralai/Mixtral-8x7B-Instruct-v0.1", "tiiuae/falcon-7b-instruct"]
30
+ )
31
+
32
+ st.title("πŸ€– CodeCraft AI - Mini Copilot (Chat Edition)")
33
+
34
+ # =======================
35
+ # Session State for Chats
36
+ # =======================
37
  if "generate_chat" not in st.session_state:
38
  st.session_state.generate_chat = []
39
  if "debug_chat" not in st.session_state:
 
41
  if "explain_chat" not in st.session_state:
42
  st.session_state.explain_chat = []
43
 
44
+
45
+ # =======================
46
  # Helper Functions
47
+ # =======================
48
+ def call_groq(chat_history, system_prompt):
49
+ response = client.chat.completions.create(
50
+ model=model_choice,
51
+ messages=[{"role": "system", "content": system_prompt}]
52
+ + [{"role": role, "content": msg} for role, msg in chat_history],
53
+ temperature=0.4
54
+ )
55
+ return response.choices[0].message.content
56
+
57
+
58
+ def call_hf(prompt):
59
+ headers = {"Authorization": f"Bearer {HF_API_KEY}"}
60
+ payload = {"inputs": prompt}
61
+ response = requests.post(
62
+ f"https://api-inference.huggingface.co/models/{model_choice}",
63
+ headers=headers,
64
+ json=payload,
65
+ timeout=60
66
+ )
67
+ if response.status_code == 200:
68
+ result = response.json()
69
+ if isinstance(result, list) and "generated_text" in result[0]:
70
+ return result[0]["generated_text"]
71
  else:
72
+ return str(result)
73
+ return f"⚠️ HF Error: {response.text}"
74
+
75
+
76
+ def get_ai_response(chat_history, system_prompt):
77
+ if provider_choice == "Groq":
78
+ return call_groq(chat_history, system_prompt)
79
+ else:
80
+ # Convert history into prompt text
81
+ prompt = system_prompt + "\n\n"
82
+ for role, msg in chat_history:
83
+ prompt += f"{role.upper()}: {msg}\n"
84
+ return call_hf(prompt)
85
+
86
+
87
+ # =======================
88
+ # Chat UI
89
+ # =======================
90
+ def chat_ui(tab_name, chat_history, system_prompt, input_key):
91
+ st.subheader(tab_name)
92
+
93
+ # --- Chat history display ---
94
+ chat_container = st.container()
95
+ with chat_container:
96
+ for role, msg in chat_history:
97
+ if role == "user":
98
+ with st.chat_message("user"):
99
+ st.write(msg)
100
+ else:
101
+ with st.chat_message("assistant"):
102
+ if "```" in msg: # detect code blocks
103
+ parts = msg.split("```")
104
+ for i, part in enumerate(parts):
105
+ if i % 2 == 1: # inside code block
106
+ lang, *code_lines = part.split("\n")
107
+ code = "\n".join(code_lines)
108
+ st.code(code, language=lang if lang else "python")
109
+ else:
110
+ st.write(part)
111
+ else:
112
+ st.write(msg)
113
+
114
+ # --- Fixed input bar ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  col1, col2 = st.columns([10, 1])
116
  with col1:
117
+ user_input = st.text_input("Type your message...", key=input_key, label_visibility="collapsed")
118
  with col2:
119
+ send_btn = st.button("➀", key=input_key + "_send")
120
+
121
+ # --- Handle input ---
122
+ if send_btn and user_input.strip():
123
+ chat_history.append(("user", user_input.strip()))
124
 
 
 
125
  with st.spinner("Thinking..."):
126
+ ai_msg = get_ai_response(chat_history, system_prompt)
127
+
128
+ chat_history.append(("assistant", ai_msg))
129
+ st.session_state[input_key] = "" # Clear input
 
 
130
  st.rerun()
131
 
 
 
 
 
 
 
 
 
132
 
133
+ # =======================
134
+ # Tabs
135
+ # =======================
136
+ tab1, tab2, tab3 = st.tabs(["πŸ’‘ Generate Code", "πŸ›  Debug Code", "πŸ“˜ Explain Code"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
+ with tab1:
139
+ chat_ui(
140
+ "πŸ’‘ Generate Code",
141
+ st.session_state.generate_chat,
142
+ "You are a helpful coding assistant. Generate correct code first, then a short simple explanation.",
143
+ input_key="generate_input"
144
+ )
 
145
 
146
+ with tab2:
147
+ chat_ui(
148
+ "πŸ›  Debug Code",
149
+ st.session_state.debug_chat,
150
+ "You are an expert code debugger. Fix errors and give corrected code, then explain what changed and why.",
151
+ input_key="debug_input"
152
+ )
 
 
 
 
 
 
 
 
 
 
 
153
 
154
+ with tab3:
155
+ chat_ui(
156
+ "πŸ“˜ Explain Code",
157
+ st.session_state.explain_chat,
158
+ "You are a teacher that explains code in simple words. The user pastes code, and you explain step by step.",
159
+ input_key="explain_input"
160
+ )
161
+
162
+ # =======================
163
  # Footer
164
+ # =======================
165
+ st.markdown("---")
166
+ st.caption("πŸš€ Built with Streamlit Β· Groq ⚑ + Hugging Face πŸ€—")