Spaces:
Sleeping
Sleeping
File size: 6,328 Bytes
9b13ff2 22a5a1b c0897d7 4126bd5 c0897d7 6fd750b 722c417 6fd750b 722c417 28e5266 4126bd5 ff6f573 22a5a1b 4126bd5 c0897d7 4126bd5 9b13ff2 4126bd5 6fd750b 4126bd5 6fd750b 4126bd5 e13f103 4126bd5 5dca394 6fd750b e13f103 0f792c7 6fd750b 8985573 4126bd5 8985573 22a5a1b 4126bd5 6fd750b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
import streamlit as st
import difflib
import requests
import datetime
# --- CONFIG ---
GROQ_API_KEY = st.secrets.get('GROQ_API_KEY', 'YOUR_GROQ_API_KEY')
BLACKBOX_API_KEY = st.secrets.get('BLACKBOX_API_KEY', 'YOUR_BLACKBOX_API_KEY')
PROGRAMMING_LANGUAGES = ["Python", "JavaScript", "TypeScript", "Java", "C++", "C#"]
SKILL_LEVELS = ["Beginner", "Intermediate", "Expert"]
USER_ROLES = ["Student", "Frontend Developer", "Backend Developer", "Data Scientist"]
EXPLANATION_LANGUAGES = ["English", "Spanish", "Chinese", "Urdu"]
EXAMPLE_QUESTIONS = [
"What does this function do?",
"How can I optimize this code?",
"What are the potential bugs in this code?",
"How does this algorithm work?",
"What design patterns are used here?",
"How can I make this code more readable?"
]
def call_groq_api(prompt, model="llama3-70b-8192"):
headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
data = {"model": model, "messages": [{"role": "user", "content": prompt}]}
response = requests.post("https://api.groq.com/openai/v1/chat/completions", json=data, headers=headers)
if response.status_code == 200:
return response.json()['choices'][0]['message']['content']
else:
return f"[Groq API Error] {response.text}"
def call_blackbox_agent(messages):
url = "https://api.code.blackbox.ai/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {BLACKBOX_API_KEY}"
}
data = {
"model": "code-chat",
"messages": messages
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
return response.json()["choices"][0]["message"]["content"]
else:
return call_groq_api(messages[-1]["content"])
def code_matches_language(code, language):
if language.lower() in code.lower():
return True
return True
def calculate_code_complexity(code):
lines = code.count('\n') + 1
return f"{lines} lines"
def get_inline_diff(original, modified):
diff = difflib.unified_diff(
original.splitlines(),
modified.splitlines(),
lineterm='',
fromfile='Original',
tofile='Refactored'
)
return '\n'.join(diff)
def is_coding_question(question):
messages = [
{"role": "system", "content": "You are a helpful coding assistant."},
{"role": "user", "content": f"Is the following question about programming or code? Answer only 'yes' or 'no'. Question: {question}"}
]
try:
response = call_blackbox_agent(messages)
return 'yes' in response.lower()
except Exception:
return False
st.set_page_config(page_title="AI Workflow App", layout="wide")
st.title("AI Assistant with Workflow (Streamlit Edition)")
page = st.sidebar.radio("Navigate", ["Home", "AI Workflow", "Semantic Search"])
if page == "Semantic Search":
st.header("Semantic Search")
code_input = st.text_area("Paste your code here", height=200, key="sem_code")
uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"], key="sem_file")
if uploaded_file:
code_input = uploaded_file.read().decode("utf-8")
st.text_area("File content", code_input, height=200, key="sem_file_content")
col1, col2, col3, col4 = st.columns(4)
with col1:
programming_language = st.selectbox("Programming Language", PROGRAMMING_LANGUAGES, key="sem_lang")
with col2:
skill_level = st.selectbox("Skill Level", SKILL_LEVELS, key="sem_skill")
with col3:
user_role = st.selectbox("Your Role", USER_ROLES, key="sem_role")
with col4:
explanation_language = st.selectbox("Explanation Language", EXPLANATION_LANGUAGES, key="sem_expl")
st.caption("Example questions:")
st.write(", ".join(EXAMPLE_QUESTIONS))
# --- Voice input button (for local use only) ---
st.markdown("""
<button id="voice-btn" style="font-size:22px; margin-bottom:8px;">🎤 Speak your question</button>
<span id="voice-status" style="margin-left:8px;"></span>
<script>
const btn = document.getElementById('voice-btn');
const status = document.getElementById('voice-status');
let recognition;
if ('webkitSpeechRecognition' in window) {
recognition = new webkitSpeechRecognition();
recognition.lang = 'en-US';
recognition.continuous = false;
recognition.interimResults = false;
btn.onclick = function() {
recognition.start();
status.textContent = 'Listening...';
};
recognition.onresult = function(event) {
const transcript = event.results[0][0].transcript;
// Find the Streamlit input and set its value
const streamlitInput = window.parent.document.querySelector('input[data-testid="stTextInput"]');
if (streamlitInput) {
streamlitInput.value = transcript;
streamlitInput.dispatchEvent(new Event('input', { bubbles: true }));
}
status.textContent = 'Heard: ' + transcript;
};
recognition.onerror = function() {
status.textContent = 'Voice error';
};
recognition.onend = function() {
if (status.textContent === 'Listening...') status.textContent = '';
};
} else {
btn.disabled = true;
status.textContent = 'Voice not supported';
}
</script>
""", unsafe_allow_html=True)
# --- Single input field for question ---
question = st.text_input("Ask a question about your code", key="sem_question")
if st.button("Run Semantic Search"):
if not code_input.strip() or not question.strip():
st.error("Both code and question are required.")
elif not code_matches_language(code_input, programming_language):
st.error(f"Language mismatch. Please check your code and language selection.")
elif not is_coding_question(question):
st.warning("Please ask a relevant question.")
else:
with st.spinner("Running Semantic Search..."):
answer = call_groq_api(f"{question}\n\nCode:\n{code_input}")
st.success("Answer:")
st.write(answer) |