Naz786 commited on
Commit
e13f103
·
verified ·
1 Parent(s): 0f792c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -63
app.py CHANGED
@@ -20,7 +20,6 @@ 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}]}
@@ -46,7 +45,6 @@ def call_blackbox_agent(messages):
46
  else:
47
  return call_groq_api(messages[-1]["content"])
48
 
49
- # --- UTILS ---
50
  def code_matches_language(code, language):
51
  if language.lower() in code.lower():
52
  return True
@@ -77,72 +75,12 @@ def is_coding_question(question):
77
  except Exception:
78
  return False
79
 
80
- # --- STREAMLIT APP ---
81
  st.set_page_config(page_title="AI Workflow App", layout="wide")
82
  st.title("AI Assistant with Workflow (Streamlit Edition)")
83
 
84
- # Navigation
85
  page = st.sidebar.radio("Navigate", ["Home", "AI Workflow", "Semantic Search"])
86
 
87
- if page == "Home":
88
- st.header("Welcome to the AI Assistant!")
89
- st.markdown("""
90
- - **Full AI Workflow:** Complete code analysis pipeline with explanation, refactoring, review, and testing (powered by Groq/Blackbox)
91
- - **Semantic Search:** Ask natural language questions about your code and get intelligent answers
92
- """)
93
- st.info("Select a feature from the sidebar to get started.")
94
-
95
- elif page == "AI Workflow":
96
- st.header("Full AI Workflow")
97
- code_input = st.text_area("Paste your code here", height=200)
98
- uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"])
99
- if uploaded_file:
100
- code_input = uploaded_file.read().decode("utf-8")
101
- st.text_area("File content", code_input, height=200, key="file_content")
102
- col1, col2, col3, col4 = st.columns(4)
103
- with col1:
104
- programming_language = st.selectbox("Programming Language", PROGRAMMING_LANGUAGES)
105
- with col2:
106
- skill_level = st.selectbox("Skill Level", SKILL_LEVELS)
107
- with col3:
108
- user_role = st.selectbox("Your Role", USER_ROLES)
109
- with col4:
110
- explanation_language = st.selectbox("Explanation Language", EXPLANATION_LANGUAGES)
111
- if code_input:
112
- st.caption(f"Complexity: {calculate_code_complexity(code_input)}")
113
- if st.button("Run Workflow", type="primary"):
114
- if not code_input.strip():
115
- st.error("Please paste or upload your code.")
116
- elif not code_matches_language(code_input, programming_language):
117
- st.error(f"Language mismatch. Please check your code and language selection.")
118
- else:
119
- with st.spinner("Running AI Workflow..."):
120
- steps = [
121
- ("Explain", call_groq_api(f"Explain this {programming_language} code for a {skill_level} {user_role} in {explanation_language}:\n{code_input}")),
122
- ("Refactor", call_blackbox_agent([
123
- {"role": "system", "content": "You are a helpful coding assistant."},
124
- {"role": "user", "content": f"Refactor this {programming_language} code: {code_input}"}
125
- ])),
126
- ("Review", call_groq_api(f"Review this {programming_language} code for errors and improvements: {code_input}")),
127
- ("ErrorDetection", call_groq_api(f"Find bugs in this {programming_language} code: {code_input}")),
128
- ("TestGeneration", call_groq_api(f"Generate tests for this {programming_language} code: {code_input}")),
129
- ]
130
- timeline = []
131
- for step, output in steps:
132
- timeline.append({"step": step, "output": output})
133
- st.success("Workflow complete!")
134
- for t in timeline:
135
- st.subheader(t["step"])
136
- st.write(t["output"])
137
- st.subheader("Code Diff (Original vs Refactored)")
138
- refactored_code = steps[1][1]
139
- st.code(get_inline_diff(code_input, refactored_code), language=programming_language.lower())
140
- report = f"AI 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":
146
  st.header("Semantic Search")
147
  code_input = st.text_area("Paste your code here", height=200, key="sem_code")
148
  uploaded_file = st.file_uploader("Or upload a code file", type=["py", "js", "ts", "java", "cpp", "cs"], key="sem_file")
@@ -162,6 +100,47 @@ elif page == "Semantic Search":
162
  st.caption("Example questions:")
163
  st.write(", ".join(EXAMPLE_QUESTIONS))
164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  question = st.text_input("Ask a question about your code", key="sem_question")
166
 
167
  if st.button("Run Semantic Search"):
 
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
  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
 
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 == "Semantic Search":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
  st.caption("Example questions:")
101
  st.write(", ".join(EXAMPLE_QUESTIONS))
102
 
103
+ # --- Voice input button (for local use only) ---
104
+ st.markdown("""
105
+ <button id="voice-btn" style="font-size:22px; margin-bottom:8px;">🎤 Speak your question</button>
106
+ <span id="voice-status" style="margin-left:8px;"></span>
107
+ <script>
108
+ const btn = document.getElementById('voice-btn');
109
+ const status = document.getElementById('voice-status');
110
+ let recognition;
111
+ if ('webkitSpeechRecognition' in window) {
112
+ recognition = new webkitSpeechRecognition();
113
+ recognition.lang = 'en-US';
114
+ recognition.continuous = false;
115
+ recognition.interimResults = false;
116
+ btn.onclick = function() {
117
+ recognition.start();
118
+ status.textContent = 'Listening...';
119
+ };
120
+ recognition.onresult = function(event) {
121
+ const transcript = event.results[0][0].transcript;
122
+ // Find the Streamlit input and set its value
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() {
131
+ status.textContent = 'Voice error';
132
+ };
133
+ recognition.onend = function() {
134
+ if (status.textContent === 'Listening...') status.textContent = '';
135
+ };
136
+ } else {
137
+ btn.disabled = true;
138
+ status.textContent = 'Voice not supported';
139
+ }
140
+ </script>
141
+ """, unsafe_allow_html=True)
142
+
143
+ # --- Single input field for question ---
144
  question = st.text_input("Ask a question about your code", key="sem_question")
145
 
146
  if st.button("Run Semantic Search"):