Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
360 lines (308 loc) · 12.6 KB
/
Copy pathmain.py
File metadata and controls
360 lines (308 loc) · 12.6 KB
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import os
import subprocess
import traceback
import pandas as pd
import streamlit as st
from streamlit_mermaid import st_mermaid
from src.code_executor import execute_code
from src.data_handler import get_data_summary, load_data, validate_data
from src.llm_interface import (
gen_viz_code,
generate_explanation,
generate_mermaid_flowchart,
get_visualization_prompt,
initialize_llm_client,
strip_markdown_codeblock,
)
st.set_page_config(
page_title="Bioinformatics Analysis Studio",
layout="wide",
initial_sidebar_state="expanded",
)
# Initialize session state
if "data" not in st.session_state:
st.session_state.data = []
# Add default data loading here
default_file_path = (
"brca_umich_proteomics_imputed.csv" # Default data file in project root
)
if os.path.exists(default_file_path):
try:
data = pd.read_csv(default_file_path) # or pd.read_excel() for xlsx
data_description = get_data_summary(data)
if validate_data(data):
data_entry = {
"file_path": os.path.abspath(default_file_path),
"data_description": data_description,
}
st.session_state.data.append(data_entry)
st.toast(
f"✅ Loaded default file: {os.path.basename(default_file_path)}"
)
except Exception as e:
st.error(f"Error loading default file: {str(e)}")
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "current_code" not in st.session_state:
st.session_state.current_code = None
if "llm_provider" not in st.session_state:
st.session_state.llm_provider = "anthropic"
if "llm_client" not in st.session_state:
st.session_state.llm_client = None
if "current_output_tab" not in st.session_state:
st.session_state.current_output_tab = "Generated Prompt"
if "current_error" not in st.session_state:
st.session_state.current_error = None
if "current_explanation" not in st.session_state:
st.session_state.current_explanation = None
@st.dialog("Debug State", width="large")
def show_state():
st.write(st.session_state)
# Define a function to switch to a specific tab
def switch_to_tab(tab_name):
js_code = f"""
<script>
// Select the tab container
console.log("Switching to tab: {tab_name}")
var tabContainer = window.parent.document.querySelector('.stTabs');
// Select the tab buttons
var tabButtons = tabContainer.querySelectorAll('[role="tab"]');
// Find the button for the target tab and click it
tabButtons.forEach(function(button) {{
if (button.innerText.trim() === "{tab_name}") {{
button.click();
}}
}});
</script>
"""
# Execute the JavaScript code
st.components.v1.html(js_code, height=0, width=0)
def git_info_component():
"""Helper function to get the current git hash and message."""
try:
git_hash = (
subprocess.check_output(["git", "rev-parse", "--short", "HEAD"])
.decode("ascii")
.strip()
)
git_msg = (
subprocess.check_output(["git", "log", "-1", "--pretty=%B"])
.decode("ascii")
.strip()
)
except Exception as e:
return None, str(e)
if git_hash:
return st.caption(f"Git Hash: {git_hash} - {git_msg}")
else:
return st.caption(f"Not in git repository: {git_msg}")
def main():
st.title("🧬 Bioinformatics Analysis Studio")
# Display current git hash
git_info_component()
# Sidebar for file upload and data info
with st.sidebar:
# Initialize LLM client if not already initialized
if st.session_state.llm_client is None:
try:
st.session_state.llm_client = initialize_llm_client(
st.session_state.llm_provider
)
except Exception as e:
st.error(
f"Failed to initialize {st.session_state.llm_provider}: {str(e)}"
)
st.session_state.llm_client = None
# LLM Provider selection with status indicator
st.header("LLM Model")
status_indicator = "✅" if st.session_state.llm_client is not None else "❌"
selected_provider = st.selectbox(
f"{status_indicator} Select Provider",
options=["openai", "anthropic"],
index=0 if st.session_state.llm_provider == "openai" else 1,
)
if selected_provider != st.session_state.llm_provider:
st.session_state.llm_provider = selected_provider
try:
st.session_state.llm_client = initialize_llm_client(selected_provider)
except Exception as e:
st.error(f"Failed to initialize {selected_provider}: {str(e)}")
st.session_state.llm_client = None
st.header("Data Files")
uploaded_files = st.file_uploader(
"Choose data files", type=["csv", "xlsx"], accept_multiple_files=True
)
if uploaded_files:
try:
st.info("Loading data files...")
st.session_state.data = []
for file in uploaded_files:
data = load_data(file)
data_description = get_data_summary(data)
if validate_data(data):
data_entry = {
"file_path": os.path.abspath(file.name),
"data_description": data_description,
}
st.session_state.data.append(data_entry)
st.toast(f"✅ Loaded {len(st.session_state.data)} data files")
except Exception as e:
st.error(f"Error loading files: {str(e)}")
if st.session_state.data:
# Display data files
st.header("Available Data Files")
for data_entry in st.session_state.data:
with st.expander(f"📄 {data_entry['file_path']}"):
summary = data_entry["data_description"]
st.write(summary)
if st.button("Session state (debugging)"):
show_state()
if len(st.session_state.data) > 0:
# Main content area with two columns
col1, col2 = st.columns([4, 5])
with col1:
st.header("📝 Instructions")
user_input = st.text_area(
"Enter your visualization request:",
value="""열: 샘플
행: 단백질
clustermap의 계층적 클러스터링을 사용하여 클러스터 정의
각 클러스터별 상위 100개의 표준 편차가 가장 높은 유전자 선택
변동성이 큰 유전자 상위 목록의 clustermap 표시; 샘플 클러스터를 col_colors 인수로 표시, 딕셔너리를 전달할 수 있음
ticklabels 자동으로 표시
각 클러스터에 고유한 유전자마다 클러스터와 동일한 색깔로 행에 표시
행/열 둘다 색갈 표시되는지 확인
각 클러스터에 해당하는 유전자 print""",
height=300,
key="viz_input",
on_change=generate_visualization,
)
if st.button("Go!"):
if user_input:
generate_visualization()
else:
st.warning("Please enter a visualization request first")
st.checkbox(
"Reuse previous code",
value=False,
# disabled=not st.session_state.current_code,
key="reuse_code",
)
st.checkbox(
"Try to autofix error",
value=False,
# disabled=not st.session_state.current_error,
key="autofix_error",
)
st.slider(
"Temperature",
min_value=0.0,
max_value=1.0,
value=0.3,
step=0.1,
format="%.1f",
key="temperature",
)
with col2:
st.header("📊 Analysis Results")
status = st.status(
"Waiting for instructions", expanded=False, state="error"
)
if "current_prompt" in st.session_state:
tab1, tab2, tab3 = st.tabs(["Code", "Visualization", "Explanation"])
with tab1:
if st.session_state.current_code:
status.write("Generated code")
st.code(
st.session_state.current_code,
language="python",
)
switch_to_tab("Code")
with tab2:
if st.session_state.current_code:
try:
execute_code(
st.session_state.current_code,
st.session_state.data,
status,
)
# Generate explanation after successful visualization
st.session_state.current_error = None
except Exception as e:
st.session_state.current_error = (
str(e) + "\n" + str(traceback.format_exc())
)
st.error(st.session_state.current_error)
switch_to_tab("Visualization")
with tab3:
if st.button("Generate Explanation"):
try:
explanation = generate_explanation(
st.session_state.current_prompt,
st.session_state.current_code,
st.session_state.llm_client,
st.session_state.temperature,
status,
)
st.markdown(explanation)
# Add Mermaid diagram
st.divider()
st.subheader("Analysis Workflow")
mermaid_code = generate_mermaid_flowchart(
st.session_state.current_prompt,
st.session_state.current_code,
st.session_state.llm_client,
st.session_state.temperature,
status,
explanation,
)
st_mermaid(
mermaid_code, pan=False, zoom=False, show_controls=False
)
except Exception as e:
st.error(f"Error generating explanation: {str(e)}")
def generate_visualization():
"""Helper function to generate visualization from prompt"""
if not st.session_state.llm_client:
st.error("Please ensure LLM provider is properly configured")
return
user_prompt = st.session_state.viz_input
current_code = (
st.session_state.current_code if st.session_state.reuse_code else None
)
current_error = st.session_state.current_error
autofix_error = st.session_state.autofix_error
if autofix_error:
user_prompt += str(current_error)
temperature = st.session_state.temperature
try:
st.session_state.chat_history.append(("user", user_prompt))
prompt = get_visualization_prompt(
st.session_state.data, user_prompt, current_code
)
# Store the prompt in session state
st.session_state.current_prompt = prompt
code = strip_markdown_codeblock(
gen_viz_code(
prompt,
st.session_state.llm_client,
temperature,
)
)
st.session_state.current_code = code
st.session_state.chat_history.append(
("assistant", "Generated visualization code:")
)
except Exception as e:
if "Rate limit exceeded" in str(e):
st.error(
"⚠️ Rate limit exceeded. Please try a simpler request or wait a moment before trying again."
)
else:
st.error(f"Error generating visualization: {str(e)}")
if __name__ == "__main__":
try:
main()
except Exception as e:
st.error(f"Application error: {str(e)}")
st.exception(e)