Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,7 +2,8 @@ import streamlit as st
|
|
2 |
import difflib
|
3 |
import requests
|
4 |
import datetime
|
5 |
-
import
|
|
|
6 |
|
7 |
# --- CONFIG ---
|
8 |
GROQ_API_KEY = st.secrets.get('GROQ_API_KEY', 'YOUR_GROQ_API_KEY')
|
@@ -21,7 +22,7 @@ EXAMPLE_QUESTIONS = [
|
|
21 |
"How can I make this code more readable?"
|
22 |
]
|
23 |
|
24 |
-
# --- API
|
25 |
def call_groq_api(prompt, model="llama3-70b-8192"):
|
26 |
headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
|
27 |
data = {"model": model, "messages": [{"role": "user", "content": prompt}]}
|
@@ -31,14 +32,21 @@ def call_groq_api(prompt, model="llama3-70b-8192"):
|
|
31 |
else:
|
32 |
return f"[Groq API Error] {response.text}"
|
33 |
|
34 |
-
def call_blackbox_agent(messages):
|
35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
headers = {
|
37 |
"Content-Type": "application/json",
|
38 |
"Authorization": f"Bearer {BLACKBOX_API_KEY}"
|
39 |
}
|
40 |
data = {
|
41 |
-
"model":
|
42 |
"messages": messages
|
43 |
}
|
44 |
response = requests.post(url, headers=headers, json=data)
|
@@ -49,14 +57,12 @@ def call_blackbox_agent(messages):
|
|
49 |
|
50 |
# --- UTILS ---
|
51 |
def code_matches_language(code, language):
|
52 |
-
# Simple heuristic, can be improved
|
53 |
if language.lower() in code.lower():
|
54 |
return True
|
55 |
-
return True
|
56 |
|
57 |
def calculate_code_complexity(code):
|
58 |
-
|
59 |
-
lines = code.count('\n') + 1
|
60 |
return f"{lines} lines"
|
61 |
|
62 |
def get_inline_diff(original, modified):
|
@@ -67,36 +73,25 @@ def get_inline_diff(original, modified):
|
|
67 |
fromfile='Original',
|
68 |
tofile='Refactored'
|
69 |
)
|
70 |
-
return '
|
71 |
-
|
72 |
-
def is_coding_question(question):
|
73 |
-
messages = [
|
74 |
-
{"role": "system", "content": "You are a helpful coding assistant."},
|
75 |
-
{"role": "user", "content": f"Is the following question about programming or code? Answer only 'yes' or 'no'. Question: {question}"}
|
76 |
-
]
|
77 |
-
try:
|
78 |
-
response = call_blackbox_agent(messages)
|
79 |
-
return 'yes' in response.lower()
|
80 |
-
except Exception:
|
81 |
-
return False
|
82 |
|
83 |
# --- STREAMLIT APP ---
|
84 |
-
st.set_page_config(page_title="
|
85 |
-
st.title("
|
86 |
|
87 |
# Navigation
|
88 |
-
page = st.sidebar.radio("Navigate", ["Home", "
|
89 |
|
90 |
if page == "Home":
|
91 |
-
st.header("Welcome to the
|
92 |
st.markdown("""
|
93 |
-
- **Full
|
94 |
- **Semantic Search:** Ask natural language questions about your code and get intelligent answers
|
95 |
""")
|
96 |
st.info("Select a feature from the sidebar to get started.")
|
97 |
|
98 |
-
elif page == "
|
99 |
-
st.header("Full
|
100 |
code_input = st.text_area("Paste your code here", height=200)
|
101 |
uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"])
|
102 |
if uploaded_file:
|
@@ -119,7 +114,7 @@ elif page == "AI Workflow":
|
|
119 |
elif not code_matches_language(code_input, programming_language):
|
120 |
st.error(f"Language mismatch. Please check your code and language selection.")
|
121 |
else:
|
122 |
-
with st.spinner("Running
|
123 |
steps = [
|
124 |
("Explain", call_groq_api(f"Explain this {programming_language} code for a {skill_level} {user_role} in {explanation_language}:\n{code_input}")),
|
125 |
("Refactor", call_blackbox_agent([
|
@@ -137,12 +132,14 @@ elif page == "AI Workflow":
|
|
137 |
for t in timeline:
|
138 |
st.subheader(t["step"])
|
139 |
st.write(t["output"])
|
|
|
140 |
st.subheader("Code Diff (Original vs Refactored)")
|
141 |
-
refactored_code = steps[1][1]
|
142 |
st.code(get_inline_diff(code_input, refactored_code), language=programming_language.lower())
|
143 |
-
|
|
|
144 |
for t in timeline:
|
145 |
-
report += f"## {t['step']}
|
146 |
st.download_button("Download Report", report, file_name="ai_workflow_report.txt")
|
147 |
|
148 |
elif page == "Semantic Search":
|
@@ -162,59 +159,29 @@ elif page == "Semantic Search":
|
|
162 |
with col4:
|
163 |
explanation_language = st.selectbox("Explanation Language", EXPLANATION_LANGUAGES, key="sem_expl")
|
164 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
165 |
st.caption("Example questions:")
|
166 |
st.write(", ".join(EXAMPLE_QUESTIONS))
|
167 |
|
168 |
-
# --- Voice input widget ---
|
169 |
-
if "sem_question" not in st.session_state:
|
170 |
-
st.session_state["sem_question"] = ""
|
171 |
-
|
172 |
-
voice_input = components.html('''
|
173 |
-
<button id="voice-btn" style="margin-bottom:8px;">🎤 Speak your question</button>
|
174 |
-
<span id="voice-status" style="margin-left:8px;"></span>
|
175 |
-
<script>
|
176 |
-
const btn = document.getElementById('voice-btn');
|
177 |
-
const status = document.getElementById('voice-status');
|
178 |
-
let recognition;
|
179 |
-
if ('webkitSpeechRecognition' in window) {
|
180 |
-
recognition = new webkitSpeechRecognition();
|
181 |
-
recognition.lang = 'en-US';
|
182 |
-
recognition.continuous = false;
|
183 |
-
recognition.interimResults = false;
|
184 |
-
btn.onclick = function() {
|
185 |
-
recognition.start();
|
186 |
-
status.textContent = 'Listening...';
|
187 |
-
};
|
188 |
-
recognition.onresult = function(event) {
|
189 |
-
const transcript = event.results[0][0].transcript;
|
190 |
-
window.parent.postMessage({isStreamlitMessage: true, type: 'streamlit:setComponentValue', value: transcript}, '*');
|
191 |
-
status.textContent = 'Heard: ' + transcript;
|
192 |
-
};
|
193 |
-
recognition.onerror = function() {
|
194 |
-
status.textContent = 'Voice error';
|
195 |
-
};
|
196 |
-
recognition.onend = function() {
|
197 |
-
if (status.textContent === 'Listening...') status.textContent = '';
|
198 |
-
};
|
199 |
-
} else {
|
200 |
-
btn.disabled = true;
|
201 |
-
status.textContent = 'Voice not supported';
|
202 |
-
}
|
203 |
-
</script>
|
204 |
-
''', height=60)
|
205 |
-
|
206 |
-
# If voice input is received, update the question field directly in session state
|
207 |
-
if voice_input and isinstance(voice_input, str) and voice_input.strip():
|
208 |
-
if is_coding_question(voice_input):
|
209 |
-
st.session_state["sem_question"] = voice_input
|
210 |
-
st.success(f"Question recognized: {voice_input}")
|
211 |
-
else:
|
212 |
-
st.warning("Please ask a relevant question.")
|
213 |
-
|
214 |
-
# Single input field for question (typed or spoken)
|
215 |
-
question = st.text_input("Ask a question about your code", key="sem_question")
|
216 |
-
|
217 |
-
# Run Semantic Search button
|
218 |
if st.button("Run Semantic Search"):
|
219 |
if not code_input.strip() or not question.strip():
|
220 |
st.error("Both code and question are required.")
|
@@ -224,4 +191,4 @@ elif page == "Semantic Search":
|
|
224 |
with st.spinner("Running Semantic Search..."):
|
225 |
answer = call_groq_api(f"{question}\n\nCode:\n{code_input}")
|
226 |
st.success("Answer:")
|
227 |
-
st.write(answer)
|
|
|
2 |
import difflib
|
3 |
import requests
|
4 |
import datetime
|
5 |
+
import base64
|
6 |
+
import io
|
7 |
|
8 |
# --- CONFIG ---
|
9 |
GROQ_API_KEY = st.secrets.get('GROQ_API_KEY', 'YOUR_GROQ_API_KEY')
|
|
|
22 |
"How can I make this code more readable?"
|
23 |
]
|
24 |
|
25 |
+
# --- API CALLS ---
|
26 |
def call_groq_api(prompt, model="llama3-70b-8192"):
|
27 |
headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
|
28 |
data = {"model": model, "messages": [{"role": "user", "content": prompt}]}
|
|
|
32 |
else:
|
33 |
return f"[Groq API Error] {response.text}"
|
34 |
|
35 |
+
def call_blackbox_agent(messages, model="gpt-4o"):
|
36 |
+
"""
|
37 |
+
messages: list of dicts, e.g.
|
38 |
+
[
|
39 |
+
{"role": "system", "content": "You are a helpful coding assistant."},
|
40 |
+
{"role": "user", "content": "Refactor this code: ..."}
|
41 |
+
]
|
42 |
+
"""
|
43 |
+
url = "https://api.blackbox.ai/v1/chat/completions"
|
44 |
headers = {
|
45 |
"Content-Type": "application/json",
|
46 |
"Authorization": f"Bearer {BLACKBOX_API_KEY}"
|
47 |
}
|
48 |
data = {
|
49 |
+
"model": model,
|
50 |
"messages": messages
|
51 |
}
|
52 |
response = requests.post(url, headers=headers, json=data)
|
|
|
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 |
|
68 |
def get_inline_diff(original, modified):
|
|
|
73 |
fromfile='Original',
|
74 |
tofile='Refactored'
|
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 |
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([
|
|
|
132 |
for t in timeline:
|
133 |
st.subheader(t["step"])
|
134 |
st.write(t["output"])
|
135 |
+
# Show code diff (Original vs Refactored)
|
136 |
st.subheader("Code Diff (Original vs Refactored)")
|
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")
|
144 |
|
145 |
elif page == "Semantic Search":
|
|
|
159 |
with col4:
|
160 |
explanation_language = st.selectbox("Explanation Language", EXPLANATION_LANGUAGES, key="sem_expl")
|
161 |
|
162 |
+
# Audio recorder for voice input
|
163 |
+
audio_bytes = st.file_uploader("Record your question (wav format)", type=["wav"], key="audio_input")
|
164 |
+
question = st.text_input("Ask a question about your code")
|
165 |
+
|
166 |
+
if audio_bytes is not None:
|
167 |
+
audio_data = audio_bytes.read()
|
168 |
+
audio_base64 = base64.b64encode(audio_data).decode("utf-8")
|
169 |
+
# Prepare message for Blackbox AI agent to transcribe audio
|
170 |
+
messages = [
|
171 |
+
{"role": "system", "content": "You are a helpful assistant that transcribes audio to text."},
|
172 |
+
{"role": "user", "content": f"Transcribe this audio (base64 encoded wav): {audio_base64}"}
|
173 |
+
]
|
174 |
+
transcription = call_blackbox_agent(messages)
|
175 |
+
st.session_state['voice_question'] = transcription
|
176 |
+
st.experimental_rerun()
|
177 |
+
|
178 |
+
# Use transcribed question if available
|
179 |
+
if 'voice_question' in st.session_state and st.session_state['voice_question']:
|
180 |
+
question = st.session_state['voice_question']
|
181 |
+
|
182 |
st.caption("Example questions:")
|
183 |
st.write(", ".join(EXAMPLE_QUESTIONS))
|
184 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
185 |
if st.button("Run Semantic Search"):
|
186 |
if not code_input.strip() or not question.strip():
|
187 |
st.error("Both code and question are required.")
|
|
|
191 |
with st.spinner("Running Semantic Search..."):
|
192 |
answer = call_groq_api(f"{question}\n\nCode:\n{code_input}")
|
193 |
st.success("Answer:")
|
194 |
+
st.write(answer)
|