Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,6 +2,7 @@ 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')
|
|
@@ -20,6 +21,7 @@ EXAMPLE_QUESTIONS = [
|
|
| 20 |
"How can I make this code more readable?"
|
| 21 |
]
|
| 22 |
|
|
|
|
| 23 |
def call_groq_api(prompt, model="llama3-70b-8192"):
|
| 24 |
headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
|
| 25 |
data = {"model": model, "messages": [{"role": "user", "content": prompt}]}
|
|
@@ -45,12 +47,15 @@ def call_blackbox_agent(messages):
|
|
| 45 |
else:
|
| 46 |
return call_groq_api(messages[-1]["content"])
|
| 47 |
|
|
|
|
| 48 |
def code_matches_language(code, language):
|
|
|
|
| 49 |
if language.lower() in code.lower():
|
| 50 |
return True
|
| 51 |
-
return True
|
| 52 |
|
| 53 |
def calculate_code_complexity(code):
|
|
|
|
| 54 |
lines = code.count('\n') + 1
|
| 55 |
return f"{lines} lines"
|
| 56 |
|
|
@@ -75,12 +80,72 @@ def is_coding_question(question):
|
|
| 75 |
except Exception:
|
| 76 |
return False
|
| 77 |
|
|
|
|
| 78 |
st.set_page_config(page_title="AI Workflow App", layout="wide")
|
| 79 |
st.title("AI Assistant with Workflow (Streamlit Edition)")
|
| 80 |
|
|
|
|
| 81 |
page = st.sidebar.radio("Navigate", ["Home", "AI Workflow", "Semantic Search"])
|
| 82 |
|
| 83 |
-
if page == "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
st.header("Semantic Search")
|
| 85 |
code_input = st.text_area("Paste your code here", height=200, key="sem_code")
|
| 86 |
uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"], key="sem_file")
|
|
@@ -100,9 +165,14 @@ if page == "Semantic Search":
|
|
| 100 |
st.caption("Example questions:")
|
| 101 |
st.write(", ".join(EXAMPLE_QUESTIONS))
|
| 102 |
|
| 103 |
-
# --- Voice input
|
| 104 |
-
st.
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
<span id="voice-status" style="margin-left:8px;"></span>
|
| 107 |
<script>
|
| 108 |
const btn = document.getElementById('voice-btn');
|
|
@@ -119,12 +189,7 @@ if page == "Semantic Search":
|
|
| 119 |
};
|
| 120 |
recognition.onresult = function(event) {
|
| 121 |
const transcript = event.results[0][0].transcript;
|
| 122 |
-
|
| 123 |
-
const streamlitInput = window.parent.document.querySelector('input[data-testid="stTextInput"]');
|
| 124 |
-
if (streamlitInput) {
|
| 125 |
-
streamlitInput.value = transcript;
|
| 126 |
-
streamlitInput.dispatchEvent(new Event('input', { bubbles: true }));
|
| 127 |
-
}
|
| 128 |
status.textContent = 'Heard: ' + transcript;
|
| 129 |
};
|
| 130 |
recognition.onerror = function() {
|
|
@@ -138,78 +203,32 @@ if page == "Semantic Search":
|
|
| 138 |
status.textContent = 'Voice not supported';
|
| 139 |
}
|
| 140 |
</script>
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
-
# ---
|
| 144 |
-
question = st.text_input("Ask a question about your code", key="sem_question")
|
| 145 |
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
if not code_input.strip() or not question.strip():
|
| 148 |
st.error("Both code and question are required.")
|
| 149 |
elif not code_matches_language(code_input, programming_language):
|
| 150 |
st.error(f"Language mismatch. Please check your code and language selection.")
|
| 151 |
-
elif not is_coding_question(question):
|
| 152 |
-
st.warning("Please ask a relevant question.")
|
| 153 |
else:
|
| 154 |
with st.spinner("Running Semantic Search..."):
|
| 155 |
answer = call_groq_api(f"{question}\n\nCode:\n{code_input}")
|
| 156 |
st.success("Answer:")
|
| 157 |
st.write(answer)
|
| 158 |
-
|
| 159 |
-
elif page == "AI Workflow":
|
| 160 |
-
st.header("Full AI Workflow")
|
| 161 |
-
code_input = st.text_area("Paste your code here", height=200)
|
| 162 |
-
uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"])
|
| 163 |
-
if uploaded_file:
|
| 164 |
-
code_input = uploaded_file.read().decode("utf-8")
|
| 165 |
-
st.text_area("File content", code_input, height=200, key="file_content")
|
| 166 |
-
col1, col2, col3, col4 = st.columns(4)
|
| 167 |
-
with col1:
|
| 168 |
-
programming_language = st.selectbox("Programming Language", PROGRAMMING_LANGUAGES)
|
| 169 |
-
with col2:
|
| 170 |
-
skill_level = st.selectbox("Skill Level", SKILL_LEVELS)
|
| 171 |
-
with col3:
|
| 172 |
-
user_role = st.selectbox("Your Role", USER_ROLES)
|
| 173 |
-
with col4:
|
| 174 |
-
explanation_language = st.selectbox("Explanation Language", EXPLANATION_LANGUAGES)
|
| 175 |
-
if code_input:
|
| 176 |
-
st.caption(f"Complexity: {calculate_code_complexity(code_input)}")
|
| 177 |
-
if st.button("Run Workflow", type="primary"):
|
| 178 |
-
if not code_input.strip():
|
| 179 |
-
st.error("Please paste or upload your code.")
|
| 180 |
-
elif not code_matches_language(code_input, programming_language):
|
| 181 |
-
st.error(f"Language mismatch. Please check your code and language selection.")
|
| 182 |
-
else:
|
| 183 |
-
with st.spinner("Running AI Workflow..."):
|
| 184 |
-
steps = [
|
| 185 |
-
("Explain", call_groq_api(f"Explain this {programming_language} code for a {skill_level} {user_role} in {explanation_language}:\n{code_input}")),
|
| 186 |
-
("Refactor", call_blackbox_agent([
|
| 187 |
-
{"role": "system", "content": "You are a helpful coding assistant."},
|
| 188 |
-
{"role": "user", "content": f"Refactor this {programming_language} code: {code_input}"}
|
| 189 |
-
])),
|
| 190 |
-
("Review", call_groq_api(f"Review this {programming_language} code for errors and improvements: {code_input}")),
|
| 191 |
-
("ErrorDetection", call_groq_api(f"Find bugs in this {programming_language} code: {code_input}")),
|
| 192 |
-
("TestGeneration", call_groq_api(f"Generate tests for this {programming_language} code: {code_input}")),
|
| 193 |
-
]
|
| 194 |
-
timeline = []
|
| 195 |
-
for step, output in steps:
|
| 196 |
-
timeline.append({"step": step, "output": output})
|
| 197 |
-
st.success("Workflow complete!")
|
| 198 |
-
for t in timeline:
|
| 199 |
-
st.subheader(t["step"])
|
| 200 |
-
st.write(t["output"])
|
| 201 |
-
st.subheader("Code Diff (Original vs Refactored)")
|
| 202 |
-
refactored_code = steps[1][1]
|
| 203 |
-
st.code(get_inline_diff(code_input, refactored_code), language=programming_language.lower())
|
| 204 |
-
report = f"AI Workflow Report\nGenerated on: {datetime.datetime.now()}\nLanguage: {programming_language}\nSkill Level: {skill_level}\nRole: {user_role}\n\n"
|
| 205 |
-
for t in timeline:
|
| 206 |
-
report += f"## {t['step']}\n{t['output']}\n\n---\n\n"
|
| 207 |
-
st.download_button("Download Report", report, file_name="ai_workflow_report.txt")
|
| 208 |
-
|
| 209 |
-
if page == "Home":
|
| 210 |
-
st.header("Welcome to the AI Assistant!")
|
| 211 |
-
st.markdown("""
|
| 212 |
-
- **Full AI Workflow:** Complete code analysis pipeline with explanation, refactoring, review, and testing (powered by Groq/Blackbox)
|
| 213 |
-
- **Semantic Search:** Ask natural language questions about your code and get intelligent answers
|
| 214 |
-
""")
|
| 215 |
-
st.info("Select a feature from the sidebar to get started.")
|
|
|
|
| 2 |
import difflib
|
| 3 |
import requests
|
| 4 |
import datetime
|
| 5 |
+
import streamlit.components.v1 as components
|
| 6 |
|
| 7 |
# --- CONFIG ---
|
| 8 |
GROQ_API_KEY = st.secrets.get('GROQ_API_KEY', 'YOUR_GROQ_API_KEY')
|
|
|
|
| 21 |
"How can I make this code more readable?"
|
| 22 |
]
|
| 23 |
|
| 24 |
+
# --- API STUBS ---
|
| 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}]}
|
|
|
|
| 47 |
else:
|
| 48 |
return call_groq_api(messages[-1]["content"])
|
| 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 # For demo, always True
|
| 56 |
|
| 57 |
def calculate_code_complexity(code):
|
| 58 |
+
# Dummy complexity metric
|
| 59 |
lines = code.count('\n') + 1
|
| 60 |
return f"{lines} lines"
|
| 61 |
|
|
|
|
| 80 |
except Exception:
|
| 81 |
return False
|
| 82 |
|
| 83 |
+
# --- STREAMLIT APP ---
|
| 84 |
st.set_page_config(page_title="AI Workflow App", layout="wide")
|
| 85 |
st.title("AI Assistant with Workflow (Streamlit Edition)")
|
| 86 |
|
| 87 |
+
# Navigation
|
| 88 |
page = st.sidebar.radio("Navigate", ["Home", "AI Workflow", "Semantic Search"])
|
| 89 |
|
| 90 |
+
if page == "Home":
|
| 91 |
+
st.header("Welcome to the AI Assistant!")
|
| 92 |
+
st.markdown("""
|
| 93 |
+
- **Full AI Workflow:** Complete code analysis pipeline with explanation, refactoring, review, and testing (powered by Groq/Blackbox)
|
| 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 == "AI Workflow":
|
| 99 |
+
st.header("Full AI Workflow")
|
| 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:
|
| 103 |
+
code_input = uploaded_file.read().decode("utf-8")
|
| 104 |
+
st.text_area("File content", code_input, height=200, key="file_content")
|
| 105 |
+
col1, col2, col3, col4 = st.columns(4)
|
| 106 |
+
with col1:
|
| 107 |
+
programming_language = st.selectbox("Programming Language", PROGRAMMING_LANGUAGES)
|
| 108 |
+
with col2:
|
| 109 |
+
skill_level = st.selectbox("Skill Level", SKILL_LEVELS)
|
| 110 |
+
with col3:
|
| 111 |
+
user_role = st.selectbox("Your Role", USER_ROLES)
|
| 112 |
+
with col4:
|
| 113 |
+
explanation_language = st.selectbox("Explanation Language", EXPLANATION_LANGUAGES)
|
| 114 |
+
if code_input:
|
| 115 |
+
st.caption(f"Complexity: {calculate_code_complexity(code_input)}")
|
| 116 |
+
if st.button("Run Workflow", type="primary"):
|
| 117 |
+
if not code_input.strip():
|
| 118 |
+
st.error("Please paste or upload your code.")
|
| 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 AI Workflow..."):
|
| 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([
|
| 126 |
+
{"role": "system", "content": "You are a helpful coding assistant."},
|
| 127 |
+
{"role": "user", "content": f"Refactor this {programming_language} code: {code_input}"}
|
| 128 |
+
])),
|
| 129 |
+
("Review", call_groq_api(f"Review this {programming_language} code for errors and improvements: {code_input}")),
|
| 130 |
+
("ErrorDetection", call_groq_api(f"Find bugs in this {programming_language} code: {code_input}")),
|
| 131 |
+
("TestGeneration", call_groq_api(f"Generate tests for this {programming_language} code: {code_input}")),
|
| 132 |
+
]
|
| 133 |
+
timeline = []
|
| 134 |
+
for step, output in steps:
|
| 135 |
+
timeline.append({"step": step, "output": output})
|
| 136 |
+
st.success("Workflow complete!")
|
| 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 |
+
report = f"AI Workflow Report\nGenerated on: {datetime.datetime.now()}\nLanguage: {programming_language}\nSkill Level: {skill_level}\nRole: {user_role}\n\n"
|
| 144 |
+
for t in timeline:
|
| 145 |
+
report += f"## {t['step']}\n{t['output']}\n\n---\n\n"
|
| 146 |
+
st.download_button("Download Report", report, file_name="ai_workflow_report.txt")
|
| 147 |
+
|
| 148 |
+
elif page == "Semantic Search":
|
| 149 |
st.header("Semantic Search")
|
| 150 |
code_input = st.text_area("Paste your code here", height=200, key="sem_code")
|
| 151 |
uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"], key="sem_file")
|
|
|
|
| 165 |
st.caption("Example questions:")
|
| 166 |
st.write(", ".join(EXAMPLE_QUESTIONS))
|
| 167 |
|
| 168 |
+
# --- Voice input widget ---
|
| 169 |
+
if 'voice_question' not in st.session_state:
|
| 170 |
+
st.session_state['voice_question'] = ''
|
| 171 |
+
if 'run_semantic_search' not in st.session_state:
|
| 172 |
+
st.session_state['run_semantic_search'] = False
|
| 173 |
+
|
| 174 |
+
voice_input = components.html('''
|
| 175 |
+
<button id="voice-btn" style="margin-bottom:8px;">🎤 Speak your question</button>
|
| 176 |
<span id="voice-status" style="margin-left:8px;"></span>
|
| 177 |
<script>
|
| 178 |
const btn = document.getElementById('voice-btn');
|
|
|
|
| 189 |
};
|
| 190 |
recognition.onresult = function(event) {
|
| 191 |
const transcript = event.results[0][0].transcript;
|
| 192 |
+
window.parent.postMessage({isStreamlitMessage: true, type: 'streamlit:setComponentValue', value: transcript}, '*');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
status.textContent = 'Heard: ' + transcript;
|
| 194 |
};
|
| 195 |
recognition.onerror = function() {
|
|
|
|
| 203 |
status.textContent = 'Voice not supported';
|
| 204 |
}
|
| 205 |
</script>
|
| 206 |
+
''', height=60)
|
| 207 |
+
|
| 208 |
+
# Use the return value from components.html as the transcript
|
| 209 |
+
if voice_input and isinstance(voice_input, str) and voice_input.strip():
|
| 210 |
+
if is_coding_question(voice_input):
|
| 211 |
+
st.session_state['voice_question'] = voice_input
|
| 212 |
+
st.session_state['run_semantic_search'] = True
|
| 213 |
+
st.success(f"Question recognized: {voice_input}")
|
| 214 |
+
else:
|
| 215 |
+
st.warning("Please ask a relevant question.")
|
| 216 |
|
| 217 |
+
# --- Main question input ---
|
| 218 |
+
question = st.text_input("Ask a question about your code", value=st.session_state.get('voice_question', ''), key="sem_question")
|
| 219 |
|
| 220 |
+
# Run Semantic Search button
|
| 221 |
+
run_btn = st.button("Run Semantic Search")
|
| 222 |
+
run_search = run_btn or st.session_state.get('run_semantic_search', False)
|
| 223 |
+
if run_search:
|
| 224 |
+
st.session_state['run_semantic_search'] = False # reset trigger
|
| 225 |
if not code_input.strip() or not 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"{question}\n\nCode:\n{code_input}")
|
| 232 |
st.success("Answer:")
|
| 233 |
st.write(answer)
|
| 234 |
+
// ... existing code ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|