Naz786 commited on
Commit
6fd750b
·
verified ·
1 Parent(s): b3d40f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -102
app.py CHANGED
@@ -2,8 +2,10 @@ import streamlit as st
2
  import difflib
3
  import requests
4
  import datetime
 
5
 
6
  # --- CONFIG ---
 
7
  GROQ_API_KEY = st.secrets.get('GROQ_API_KEY', 'YOUR_GROQ_API_KEY')
8
  BLACKBOX_API_KEY = st.secrets.get('BLACKBOX_API_KEY', 'YOUR_BLACKBOX_API_KEY')
9
 
@@ -20,8 +22,9 @@ EXAMPLE_QUESTIONS = [
20
  "How can I make this code more readable?"
21
  ]
22
 
23
- # --- API CALLS ---
24
  def call_groq_api(prompt, model="llama3-70b-8192"):
 
25
  headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
26
  data = {"model": model, "messages": [{"role": "user", "content": prompt}]}
27
  response = requests.post("https://api.groq.com/openai/v1/chat/completions", json=data, headers=headers)
@@ -30,38 +33,32 @@ def call_groq_api(prompt, model="llama3-70b-8192"):
30
  else:
31
  return f"[Groq API Error] {response.text}"
32
 
33
- def call_blackbox_agent(messages, model="gpt-4o"):
34
- """
35
- messages: list of dicts, e.g.
36
- [
37
- {"role": "system", "content": "You are a helpful coding assistant."},
38
- {"role": "user", "content": "Refactor this code: ..."}
39
- ]
40
- """
41
- url = "https://api.blackbox.ai/v1/chat/completions"
42
  headers = {
43
  "Content-Type": "application/json",
44
  "Authorization": f"Bearer {BLACKBOX_API_KEY}"
45
  }
46
  data = {
47
- "model": model,
48
  "messages": messages
49
  }
50
  response = requests.post(url, headers=headers, json=data)
51
  if response.status_code == 200:
52
  return response.json()["choices"][0]["message"]["content"]
53
  else:
 
54
  return call_groq_api(messages[-1]["content"])
55
 
56
-
57
-
58
  # --- UTILS ---
59
  def code_matches_language(code, language):
 
60
  if language.lower() in code.lower():
61
  return True
62
- return True
63
 
64
  def calculate_code_complexity(code):
 
65
  lines = code.count('\n') + 1
66
  return f"{lines} lines"
67
 
@@ -75,23 +72,38 @@ def get_inline_diff(original, modified):
75
  )
76
  return '\n'.join(diff)
77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  # --- STREAMLIT APP ---
79
- st.set_page_config(page_title="Code Workflows", layout="wide")
80
- st.title("CodeGenie")
81
 
82
  # Navigation
83
- page = st.sidebar.radio("Navigate", ["Home", "Code Workflow", "Semantic Search"])
84
 
85
  if page == "Home":
86
- st.header("Welcome to the Code Genie!")
87
  st.markdown("""
88
- - **Full Code Workflow:** Complete code analysis pipeline with explanation, refactoring, review, and testing (powered by Groq/Blackbox)
89
  - **Semantic Search:** Ask natural language questions about your code and get intelligent answers
90
  """)
91
  st.info("Select a feature from the sidebar to get started.")
92
 
93
- elif page == "Code Workflow":
94
- st.header("Full Code Workflow")
95
  code_input = st.text_area("Paste your code here", height=200)
96
  uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"])
97
  if uploaded_file:
@@ -114,13 +126,14 @@ elif page == "Code Workflow":
114
  elif not code_matches_language(code_input, programming_language):
115
  st.error(f"Language mismatch. Please check your code and language selection.")
116
  else:
117
- with st.spinner("Running Code Workflow..."):
 
118
  steps = [
119
  ("Explain", call_groq_api(f"Explain this {programming_language} code for a {skill_level} {user_role} in {explanation_language}:\n{code_input}")),
120
  ("Refactor", call_blackbox_agent([
121
- {"role": "system", "content": "You are a helpful coding assistant."},
122
- {"role": "user", "content": f"Refactor this {programming_language} code: {code_input}"}
123
- ])),
124
  ("Review", call_groq_api(f"Review this {programming_language} code for errors and improvements: {code_input}")),
125
  ("ErrorDetection", call_groq_api(f"Find bugs in this {programming_language} code: {code_input}")),
126
  ("TestGeneration", call_groq_api(f"Generate tests for this {programming_language} code: {code_input}")),
@@ -137,7 +150,7 @@ elif page == "Code Workflow":
137
  refactored_code = steps[1][1] # Blackbox agent output
138
  st.code(get_inline_diff(code_input, refactored_code), language=programming_language.lower())
139
  # Download report
140
- report = f"Code Workflow Report\nGenerated on: {datetime.datetime.now()}\nLanguage: {programming_language}\nSkill Level: {skill_level}\nRole: {user_role}\n\n"
141
  for t in timeline:
142
  report += f"## {t['step']}\n{t['output']}\n\n---\n\n"
143
  st.download_button("Download Report", report, file_name="ai_workflow_report.txt")
@@ -158,82 +171,76 @@ elif page == "Semantic Search":
158
  user_role = st.selectbox("Your Role", USER_ROLES, key="sem_role")
159
  with col4:
160
  explanation_language = st.selectbox("Explanation Language", EXPLANATION_LANGUAGES, key="sem_expl")
161
- import streamlit.components.v1 as components
162
-
163
- # Initialize session state variables
164
- if "voice_question" not in st.session_state:
165
- st.session_state.voice_question = ""
166
- if "auto_run_search" not in st.session_state:
167
- st.session_state.auto_run_search = False
168
-
169
- # Layout: question input and mic button side by side
170
- col_question, col_mic = st.columns([9,1])
171
- with col_question:
172
- question = st.text_input("Ask a question about your code", value=st.session_state.voice_question, key="question_input")
173
- with col_mic:
174
- # Microphone button and JS for voice recognition embedded via components.html
175
- components.html(
176
- """
177
- <button id="mic-btn" style="height:38px; width:38px; font-size:20px;">🎤</button>
178
- <script>
179
- const micBtn = document.getElementById('mic-btn');
180
- const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
181
- if (!SpeechRecognition) {
182
- alert("Speech Recognition not supported in this browser.");
183
- micBtn.disabled = true;
184
- } else {
185
- const recognition = new SpeechRecognition();
186
- recognition.lang = 'en-US';
187
- recognition.interimResults = false;
188
- recognition.maxAlternatives = 1;
189
-
190
- micBtn.onclick = () => {
191
- recognition.start();
192
- micBtn.textContent = '🎙️';
193
- };
194
-
195
- recognition.onresult = (event) => {
196
- const transcript = event.results[0][0].transcript;
197
- // Send transcript to Streamlit by updating the input field
198
- const inputBox = window.parent.document.querySelector('input[data-key="question_input"]');
199
- if (inputBox) {
200
- inputBox.value = transcript;
201
- inputBox.dispatchEvent(new Event('input', { bubbles: true }));
202
- }
203
- micBtn.textContent = '🎤';
204
- };
205
-
206
- recognition.onerror = (event) => {
207
- console.error('Speech recognition error', event.error);
208
- micBtn.textContent = '🎤';
209
- };
210
- }
211
- </script>
212
- """,
213
- height=50,
214
- scrolling=False,
215
- )
216
-
217
- # Update session state voice_question if question input changed manually or by voice
218
- if question != st.session_state.voice_question:
219
- st.session_state.voice_question = question
220
- st.session_state.auto_run_search = True
221
-
222
- # Automatically run semantic search if flag is set
223
- if st.session_state.auto_run_search:
224
- st.session_state.auto_run_search = False
225
- if not code_input.strip() or not st.session_state.voice_question.strip():
226
- st.error("Both code and question are required.")
227
- elif not code_matches_language(code_input, programming_language):
228
- st.error(f"Language mismatch. Please check your code and language selection.")
229
- else:
230
- with st.spinner("Running Semantic Search..."):
231
- answer = call_groq_api(f"{st.session_state.voice_question}\n\nCode:\n{code_input}")
232
- st.success("Answer:")
233
- st.write(answer)
234
 
235
- # Manual button fallback
236
- if st.button("Run Semantic Search"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  if not code_input.strip() or not question.strip():
238
  st.error("Both code and question are required.")
239
  elif not code_matches_language(code_input, programming_language):
@@ -242,4 +249,4 @@ elif page == "Semantic Search":
242
  with st.spinner("Running Semantic Search..."):
243
  answer = call_groq_api(f"{question}\n\nCode:\n{code_input}")
244
  st.success("Answer:")
245
- st.write(answer)
 
2
  import difflib
3
  import requests
4
  import datetime
5
+ import streamlit.components.v1 as components
6
 
7
  # --- CONFIG ---
8
+ # Place your API keys here
9
  GROQ_API_KEY = st.secrets.get('GROQ_API_KEY', 'YOUR_GROQ_API_KEY')
10
  BLACKBOX_API_KEY = st.secrets.get('BLACKBOX_API_KEY', 'YOUR_BLACKBOX_API_KEY')
11
 
 
22
  "How can I make this code more readable?"
23
  ]
24
 
25
+ # --- API STUBS ---
26
  def call_groq_api(prompt, model="llama3-70b-8192"):
27
+ # Replace with actual Groq API call
28
  headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
29
  data = {"model": model, "messages": [{"role": "user", "content": prompt}]}
30
  response = requests.post("https://api.groq.com/openai/v1/chat/completions", json=data, headers=headers)
 
33
  else:
34
  return f"[Groq API Error] {response.text}"
35
 
36
+ def call_blackbox_agent(messages):
37
+ url = "https://api.code.blackbox.ai/v1/chat/completions"
 
 
 
 
 
 
 
38
  headers = {
39
  "Content-Type": "application/json",
40
  "Authorization": f"Bearer {BLACKBOX_API_KEY}"
41
  }
42
  data = {
43
+ "model": "code-chat",
44
  "messages": messages
45
  }
46
  response = requests.post(url, headers=headers, json=data)
47
  if response.status_code == 200:
48
  return response.json()["choices"][0]["message"]["content"]
49
  else:
50
+ # fallback to Groq if Blackbox fails
51
  return call_groq_api(messages[-1]["content"])
52
 
 
 
53
  # --- UTILS ---
54
  def code_matches_language(code, language):
55
+ # Simple heuristic, can be improved
56
  if language.lower() in code.lower():
57
  return True
58
+ return True # For demo, always True
59
 
60
  def calculate_code_complexity(code):
61
+ # Dummy complexity metric
62
  lines = code.count('\n') + 1
63
  return f"{lines} lines"
64
 
 
72
  )
73
  return '\n'.join(diff)
74
 
75
+ def is_coding_question(question):
76
+ """
77
+ Uses Blackbox AI agent to check if the question is about programming/code.
78
+ Returns True if yes, False otherwise.
79
+ """
80
+ messages = [
81
+ {"role": "system", "content": "You are a helpful coding assistant."},
82
+ {"role": "user", "content": f"Is the following question about programming or code? Answer only 'yes' or 'no'. Question: {question}"}
83
+ ]
84
+ try:
85
+ response = call_blackbox_agent(messages)
86
+ return 'yes' in response.lower()
87
+ except Exception:
88
+ return False
89
+
90
  # --- STREAMLIT APP ---
91
+ st.set_page_config(page_title="AI Workflow App", layout="wide")
92
+ st.title("AI Assistant with Workflow (Streamlit Edition)")
93
 
94
  # Navigation
95
+ page = st.sidebar.radio("Navigate", ["Home", "AI Workflow", "Semantic Search"])
96
 
97
  if page == "Home":
98
+ st.header("Welcome to the AI Assistant!")
99
  st.markdown("""
100
+ - **Full AI Workflow:** Complete code analysis pipeline with explanation, refactoring, review, and testing (powered by Groq/Blackbox)
101
  - **Semantic Search:** Ask natural language questions about your code and get intelligent answers
102
  """)
103
  st.info("Select a feature from the sidebar to get started.")
104
 
105
+ elif page == "AI Workflow":
106
+ st.header("Full AI Workflow")
107
  code_input = st.text_area("Paste your code here", height=200)
108
  uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"])
109
  if uploaded_file:
 
126
  elif not code_matches_language(code_input, programming_language):
127
  st.error(f"Language mismatch. Please check your code and language selection.")
128
  else:
129
+ with st.spinner("Running AI Workflow..."):
130
+ # Simulate workflow steps
131
  steps = [
132
  ("Explain", call_groq_api(f"Explain this {programming_language} code for a {skill_level} {user_role} in {explanation_language}:\n{code_input}")),
133
  ("Refactor", call_blackbox_agent([
134
+ {"role": "system", "content": "You are a helpful coding assistant."},
135
+ {"role": "user", "content": f"Refactor this {programming_language} code: {code_input}"}
136
+ ])),
137
  ("Review", call_groq_api(f"Review this {programming_language} code for errors and improvements: {code_input}")),
138
  ("ErrorDetection", call_groq_api(f"Find bugs in this {programming_language} code: {code_input}")),
139
  ("TestGeneration", call_groq_api(f"Generate tests for this {programming_language} code: {code_input}")),
 
150
  refactored_code = steps[1][1] # Blackbox agent output
151
  st.code(get_inline_diff(code_input, refactored_code), language=programming_language.lower())
152
  # Download report
153
+ report = f"AI Workflow Report\nGenerated on: {datetime.datetime.now()}\nLanguage: {programming_language}\nSkill Level: {skill_level}\nRole: {user_role}\n\n"
154
  for t in timeline:
155
  report += f"## {t['step']}\n{t['output']}\n\n---\n\n"
156
  st.download_button("Download Report", report, file_name="ai_workflow_report.txt")
 
171
  user_role = st.selectbox("Your Role", USER_ROLES, key="sem_role")
172
  with col4:
173
  explanation_language = st.selectbox("Explanation Language", EXPLANATION_LANGUAGES, key="sem_expl")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
+ st.caption("Example questions:")
176
+ st.write(", ".join(EXAMPLE_QUESTIONS))
177
+
178
+ # Session state for question and trigger
179
+ if 'voice_question' not in st.session_state:
180
+ st.session_state['voice_question'] = ''
181
+ if 'run_semantic_search' not in st.session_state:
182
+ st.session_state['run_semantic_search'] = False
183
+
184
+ # Voice input widget (Web Speech API)
185
+ components.html('''
186
+ <button id="voice-btn" style="margin-bottom:8px;">🎤 Speak your question</button>
187
+ <span id="voice-status" style="margin-left:8px;"></span>
188
+ <script>
189
+ const btn = document.getElementById('voice-btn');
190
+ const status = document.getElementById('voice-status');
191
+ let recognition;
192
+ if ('webkitSpeechRecognition' in window) {
193
+ recognition = new webkitSpeechRecognition();
194
+ recognition.lang = 'en-US';
195
+ recognition.continuous = false;
196
+ recognition.interimResults = false;
197
+ btn.onclick = function() {
198
+ recognition.start();
199
+ status.textContent = 'Listening...';
200
+ };
201
+ recognition.onresult = function(event) {
202
+ const transcript = event.results[0][0].transcript;
203
+ window.parent.postMessage({isStreamlitMessage: true, type: 'streamlit:setComponentValue', value: transcript}, '*');
204
+ status.textContent = 'Heard: ' + transcript;
205
+ };
206
+ recognition.onerror = function() {
207
+ status.textContent = 'Voice error';
208
+ };
209
+ recognition.onend = function() {
210
+ if (status.textContent === 'Listening...') status.textContent = '';
211
+ };
212
+ } else {
213
+ btn.disabled = true;
214
+ status.textContent = 'Voice not supported';
215
+ }
216
+ </script>
217
+ ''', height=60)
218
+
219
+ # --- Main question input ---
220
+ question = st.text_input("Ask a question about your code", value=st.session_state.get('voice_question', ''), key="sem_question")
221
+
222
+ # If voice input is received, validate and set question
223
+ # NOTE: Streamlit's JS->Python communication for custom components is limited.
224
+ # For a production app, use a robust Streamlit component for voice input.
225
+ # Here, we simulate the process using session_state for demonstration.
226
+ # You may need to use streamlit_js_eval or a similar package for real-time JS->Python value passing.
227
+
228
+ # Simulate voice input: check if the question was updated by voice
229
+ if st.session_state.get('voice_question', '') and not st.session_state.get('run_semantic_search', False):
230
+ voice_input = st.session_state['voice_question']
231
+ if is_coding_question(voice_input):
232
+ st.session_state['run_semantic_search'] = True
233
+ st.success(f"Question recognized: {voice_input}")
234
+ else:
235
+ st.warning("Please ask a relevant question.")
236
+ st.session_state['voice_question'] = '' # reset
237
+
238
+ # Run Semantic Search button
239
+ run_btn = st.button("Run Semantic Search")
240
+ # If triggered by voice or button
241
+ run_search = run_btn or st.session_state.get('run_semantic_search', False)
242
+ if run_search:
243
+ st.session_state['run_semantic_search'] = False # reset trigger
244
  if not code_input.strip() or not question.strip():
245
  st.error("Both code and question are required.")
246
  elif not code_matches_language(code_input, programming_language):
 
249
  with st.spinner("Running Semantic Search..."):
250
  answer = call_groq_api(f"{question}\n\nCode:\n{code_input}")
251
  st.success("Answer:")
252
+ st.write(answer)