Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,10 +2,10 @@ import streamlit as st
|
|
2 |
import difflib
|
3 |
import requests
|
4 |
import datetime
|
5 |
-
import
|
6 |
-
import io
|
7 |
|
8 |
# --- CONFIG ---
|
|
|
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,8 +22,9 @@ EXAMPLE_QUESTIONS = [
|
|
22 |
"How can I make this code more readable?"
|
23 |
]
|
24 |
|
25 |
-
# --- API
|
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}]}
|
29 |
response = requests.post("https://api.groq.com/openai/v1/chat/completions", json=data, headers=headers)
|
@@ -32,21 +33,14 @@ def call_groq_api(prompt, model="llama3-70b-8192"):
|
|
32 |
else:
|
33 |
return f"[Groq API Error] {response.text}"
|
34 |
|
35 |
-
def call_blackbox_agent(messages
|
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":
|
50 |
"messages": messages
|
51 |
}
|
52 |
response = requests.post(url, headers=headers, json=data)
|
@@ -57,12 +51,14 @@ def call_blackbox_agent(messages, model="gpt-4o"):
|
|
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 |
-
|
|
|
66 |
return f"{lines} lines"
|
67 |
|
68 |
def get_inline_diff(original, modified):
|
@@ -73,25 +69,40 @@ def get_inline_diff(original, modified):
|
|
73 |
fromfile='Original',
|
74 |
tofile='Refactored'
|
75 |
)
|
76 |
-
return '
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
|
78 |
# --- STREAMLIT APP ---
|
79 |
-
st.set_page_config(page_title="
|
80 |
-
st.title("
|
81 |
|
82 |
# Navigation
|
83 |
-
page = st.sidebar.radio("Navigate", ["Home", "
|
84 |
|
85 |
if page == "Home":
|
86 |
-
st.header("Welcome to the
|
87 |
st.markdown("""
|
88 |
-
- **Full
|
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 == "
|
94 |
-
st.header("Full
|
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,7 +125,8 @@ 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
|
|
|
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,14 +144,14 @@ elif page == "Code Workflow":
|
|
132 |
for t in timeline:
|
133 |
st.subheader(t["step"])
|
134 |
st.write(t["output"])
|
135 |
-
# Show code diff (
|
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"
|
141 |
for t in timeline:
|
142 |
-
report += f"## {t['step']}
|
143 |
st.download_button("Download Report", report, file_name="ai_workflow_report.txt")
|
144 |
|
145 |
elif page == "Semantic Search":
|
@@ -159,29 +171,59 @@ 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.")
|
@@ -192,3 +234,30 @@ elif page == "Semantic Search":
|
|
192 |
answer = call_groq_api(f"{question}\n\nCode:\n{code_input}")
|
193 |
st.success("Answer:")
|
194 |
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)
|
|
|
51 |
|
52 |
# --- UTILS ---
|
53 |
def code_matches_language(code, language):
|
54 |
+
# Simple heuristic, can be improved
|
55 |
if language.lower() in code.lower():
|
56 |
return True
|
57 |
+
return True # For demo, always True
|
58 |
|
59 |
def calculate_code_complexity(code):
|
60 |
+
# Dummy complexity metric
|
61 |
+
lines = code.count('\n') + 1
|
62 |
return f"{lines} lines"
|
63 |
|
64 |
def get_inline_diff(original, modified):
|
|
|
69 |
fromfile='Original',
|
70 |
tofile='Refactored'
|
71 |
)
|
72 |
+
return '\n'.join(diff)
|
73 |
+
|
74 |
+
def is_coding_question(question):
|
75 |
+
"""
|
76 |
+
Uses Blackbox AI agent to check if the question is about programming/code.
|
77 |
+
Returns True if yes, False otherwise.
|
78 |
+
"""
|
79 |
+
messages = [
|
80 |
+
{"role": "system", "content": "You are a helpful coding assistant."},
|
81 |
+
{"role": "user", "content": f"Is the following question about programming or code? Answer only 'yes' or 'no'. Question: {question}"}
|
82 |
+
]
|
83 |
+
try:
|
84 |
+
response = call_blackbox_agent(messages)
|
85 |
+
return 'yes' in response.lower()
|
86 |
+
except Exception:
|
87 |
+
return False
|
88 |
|
89 |
# --- STREAMLIT APP ---
|
90 |
+
st.set_page_config(page_title="AI Workflow App", layout="wide")
|
91 |
+
st.title("AI Assistant with Workflow (Streamlit Edition)")
|
92 |
|
93 |
# Navigation
|
94 |
+
page = st.sidebar.radio("Navigate", ["Home", "AI Workflow", "Semantic Search", "Code Comment Generator"])
|
95 |
|
96 |
if page == "Home":
|
97 |
+
st.header("Welcome to the AI Assistant!")
|
98 |
st.markdown("""
|
99 |
+
- **Full AI Workflow:** Complete code analysis pipeline with explanation, refactoring, review, and testing (powered by Groq/Blackbox)
|
100 |
- **Semantic Search:** Ask natural language questions about your code and get intelligent answers
|
101 |
""")
|
102 |
st.info("Select a feature from the sidebar to get started.")
|
103 |
|
104 |
+
elif page == "AI Workflow":
|
105 |
+
st.header("Full AI Workflow")
|
106 |
code_input = st.text_area("Paste your code here", height=200)
|
107 |
uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"])
|
108 |
if uploaded_file:
|
|
|
125 |
elif not code_matches_language(code_input, programming_language):
|
126 |
st.error(f"Language mismatch. Please check your code and language selection.")
|
127 |
else:
|
128 |
+
with st.spinner("Running AI Workflow..."):
|
129 |
+
# Simulate workflow steps
|
130 |
steps = [
|
131 |
("Explain", call_groq_api(f"Explain this {programming_language} code for a {skill_level} {user_role} in {explanation_language}:\n{code_input}")),
|
132 |
("Refactor", call_blackbox_agent([
|
|
|
144 |
for t in timeline:
|
145 |
st.subheader(t["step"])
|
146 |
st.write(t["output"])
|
147 |
+
# Show code diff (dummy for now)
|
148 |
st.subheader("Code Diff (Original vs Refactored)")
|
149 |
refactored_code = steps[1][1] # Blackbox agent output
|
150 |
st.code(get_inline_diff(code_input, refactored_code), language=programming_language.lower())
|
151 |
# Download report
|
152 |
+
report = f"AI Workflow Report\nGenerated on: {datetime.datetime.now()}\nLanguage: {programming_language}\nSkill Level: {skill_level}\nRole: {user_role}\n\n"
|
153 |
for t in timeline:
|
154 |
+
report += f"## {t['step']}\n{t['output']}\n\n---\n\n"
|
155 |
st.download_button("Download Report", report, file_name="ai_workflow_report.txt")
|
156 |
|
157 |
elif page == "Semantic Search":
|
|
|
171 |
with col4:
|
172 |
explanation_language = st.selectbox("Explanation Language", EXPLANATION_LANGUAGES, key="sem_expl")
|
173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
174 |
st.caption("Example questions:")
|
175 |
st.write(", ".join(EXAMPLE_QUESTIONS))
|
176 |
|
177 |
+
# --- Voice input widget ---
|
178 |
+
if "sem_question" not in st.session_state:
|
179 |
+
st.session_state["sem_question"] = ""
|
180 |
+
|
181 |
+
voice_input = components.html('''
|
182 |
+
<button id="voice-btn" style="margin-bottom:8px;">🎤 Speak your question</button>
|
183 |
+
<span id="voice-status" style="margin-left:8px;"></span>
|
184 |
+
<script>
|
185 |
+
const btn = document.getElementById('voice-btn');
|
186 |
+
const status = document.getElementById('voice-status');
|
187 |
+
let recognition;
|
188 |
+
if ('webkitSpeechRecognition' in window) {
|
189 |
+
recognition = new webkitSpeechRecognition();
|
190 |
+
recognition.lang = 'en-US';
|
191 |
+
recognition.continuous = false;
|
192 |
+
recognition.interimResults = false;
|
193 |
+
btn.onclick = function() {
|
194 |
+
recognition.start();
|
195 |
+
status.textContent = 'Listening...';
|
196 |
+
};
|
197 |
+
recognition.onresult = function(event) {
|
198 |
+
const transcript = event.results[0][0].transcript;
|
199 |
+
window.parent.postMessage({isStreamlitMessage: true, type: 'streamlit:setComponentValue', value: transcript}, '*');
|
200 |
+
status.textContent = 'Heard: ' + transcript;
|
201 |
+
};
|
202 |
+
recognition.onerror = function() {
|
203 |
+
status.textContent = 'Voice error';
|
204 |
+
};
|
205 |
+
recognition.onend = function() {
|
206 |
+
if (status.textContent === 'Listening...') status.textContent = '';
|
207 |
+
};
|
208 |
+
} else {
|
209 |
+
btn.disabled = true;
|
210 |
+
status.textContent = 'Voice not supported';
|
211 |
+
}
|
212 |
+
</script>
|
213 |
+
''', height=60)
|
214 |
+
|
215 |
+
# If voice input is received, update the question field directly in session state
|
216 |
+
if voice_input and isinstance(voice_input, str) and voice_input.strip():
|
217 |
+
if is_coding_question(voice_input):
|
218 |
+
st.session_state["sem_question"] = voice_input
|
219 |
+
st.success(f"Question recognized: {voice_input}")
|
220 |
+
else:
|
221 |
+
st.warning("Please ask a relevant question.")
|
222 |
+
|
223 |
+
# Single input field for question (typed or spoken)
|
224 |
+
question = st.text_input("Ask a question about your code", key="sem_question")
|
225 |
+
|
226 |
+
# Run Semantic Search button
|
227 |
if st.button("Run Semantic Search"):
|
228 |
if not code_input.strip() or not question.strip():
|
229 |
st.error("Both code and question are required.")
|
|
|
234 |
answer = call_groq_api(f"{question}\n\nCode:\n{code_input}")
|
235 |
st.success("Answer:")
|
236 |
st.write(answer)
|
237 |
+
|
238 |
+
elif page == "Code Comment Generator":
|
239 |
+
st.header("Code Comment Generator")
|
240 |
+
code_input = st.text_area("Paste your code here", height=200, key="comment_code")
|
241 |
+
uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"], key="comment_file")
|
242 |
+
if uploaded_file:
|
243 |
+
code_input = uploaded_file.read().decode("utf-8")
|
244 |
+
st.text_area("File content", code_input, height=200, key="comment_file_content")
|
245 |
+
programming_language = st.selectbox("Programming Language", PROGRAMMING_LANGUAGES, key="comment_lang")
|
246 |
+
if st.button("Generate Comments"):
|
247 |
+
if not code_input.strip():
|
248 |
+
st.error("Please paste or upload your code.")
|
249 |
+
else:
|
250 |
+
with st.spinner("Generating commented code..."):
|
251 |
+
prompt = (
|
252 |
+
f"Add clear, helpful comments to this {programming_language} code. "
|
253 |
+
"Keep the code unchanged except for adding comments. "
|
254 |
+
"Return the full code with comments:\n\n"
|
255 |
+
f"{code_input}"
|
256 |
+
)
|
257 |
+
commented_code = call_blackbox_agent([
|
258 |
+
{"role": "system", "content": "You are a helpful coding assistant."},
|
259 |
+
{"role": "user", "content": prompt}
|
260 |
+
])
|
261 |
+
st.success("Commented code generated!")
|
262 |
+
st.code(commented_code, language=programming_language.lower())
|
263 |
+
st.download_button("Download Commented Code", commented_code, file_name="commented_code.txt")
|