Spaces:
Running
Running
Fixed some Streamlit related bugs.
Browse files- Dockerfile +2 -1
- app/streamlit_meta_prompt.py +121 -87
- app/streamlit_sample_generator.py +16 -14
- config.yml +1 -0
- guidelines/streamlit.md +145 -644
Dockerfile
CHANGED
@@ -38,10 +38,11 @@ RUN poetry install --with=dev
|
|
38 |
|
39 |
COPY meta_prompt /app/meta_prompt/
|
40 |
COPY app /app/app/
|
|
|
41 |
RUN poetry install --with=dev
|
42 |
|
43 |
# Expose the Streamlit default port
|
44 |
EXPOSE 8501
|
45 |
|
46 |
# Run the Streamlit script when the container launches
|
47 |
-
CMD ["streamlit", "run", "app
|
|
|
38 |
|
39 |
COPY meta_prompt /app/meta_prompt/
|
40 |
COPY app /app/app/
|
41 |
+
COPY app.py /app/app.py
|
42 |
RUN poetry install --with=dev
|
43 |
|
44 |
# Expose the Streamlit default port
|
45 |
EXPOSE 8501
|
46 |
|
47 |
# Run the Streamlit script when the container launches
|
48 |
+
CMD ["streamlit", "run", "app.py"]
|
app/streamlit_meta_prompt.py
CHANGED
@@ -462,8 +462,8 @@ with st.sidebar:
|
|
462 |
aggressive_exploration_input = st.checkbox("Aggressive Exploration", False)
|
463 |
|
464 |
# Initialize session state
|
465 |
-
if '
|
466 |
-
st.session_state.
|
467 |
if 'initial_system_message' not in st.session_state:
|
468 |
st.session_state.initial_system_message = ""
|
469 |
if 'initial_acceptance_criteria' not in st.session_state:
|
@@ -480,15 +480,13 @@ if 'chat_log' not in st.session_state:
|
|
480 |
st.session_state.chat_log = []
|
481 |
|
482 |
def copy_system_message():
|
483 |
-
|
484 |
-
st.session_state.initial_system_message = st.session_state.system_message_output
|
485 |
|
486 |
def copy_acceptance_criteria():
|
487 |
-
|
488 |
-
st.session_state.initial_acceptance_criteria = st.session_state.acceptance_criteria_output
|
489 |
|
490 |
def clear_session_state():
|
491 |
-
st.session_state.
|
492 |
st.session_state.initial_system_message = ""
|
493 |
st.session_state.initial_acceptance_criteria = ""
|
494 |
st.session_state.system_message_output = ""
|
@@ -498,7 +496,82 @@ def clear_session_state():
|
|
498 |
st.session_state.chat_log = []
|
499 |
|
500 |
def sync_input_data():
|
501 |
-
st.session_state.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
502 |
|
503 |
if active_model_tab == "Simple":
|
504 |
simple_model_name = simple_model_name_input
|
@@ -543,13 +616,14 @@ max_output_age = max_output_age_input
|
|
543 |
aggressive_exploration = aggressive_exploration_input
|
544 |
|
545 |
data_editor_data = st.data_editor(
|
546 |
-
st.session_state.
|
|
|
547 |
num_rows="dynamic",
|
548 |
column_config={
|
549 |
"Input": st.column_config.TextColumn("Input", width="large"),
|
550 |
"Output": st.column_config.TextColumn("Output", width="large"),
|
551 |
},
|
552 |
-
hide_index=
|
553 |
use_container_width=True,
|
554 |
)
|
555 |
|
@@ -557,91 +631,51 @@ col1, col2 = st.columns(2)
|
|
557 |
|
558 |
with col1:
|
559 |
with st.expander("Advanced Inputs"):
|
560 |
-
|
561 |
-
|
562 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
563 |
col1_1, col1_2, col1_3 = st.columns(3)
|
564 |
with col1_1:
|
565 |
-
generate_button_clicked = st.button("Generate",
|
|
|
|
|
566 |
with col1_2:
|
567 |
-
sync_button_clicked = st.button("Sync", on_click=sync_input_data)
|
568 |
with col1_3:
|
569 |
clear_button_clicked = st.button("Clear", on_click=clear_session_state)
|
570 |
|
571 |
with col2:
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
|
576 |
-
|
577 |
-
if active_model_tab == "Simple":
|
578 |
-
system_message, output, analysis, acceptance_criteria, chat_log = process_message_with_single_llm(
|
579 |
-
user_message,
|
580 |
-
expected_output,
|
581 |
-
acceptance_criteria,
|
582 |
-
initial_system_message,
|
583 |
-
recursion_limit,
|
584 |
-
max_output_age,
|
585 |
-
simple_model_name,
|
586 |
-
prompt_template_group,
|
587 |
-
aggressive_exploration,
|
588 |
-
)
|
589 |
-
elif active_model_tab == "Advanced":
|
590 |
-
system_message, output, analysis, acceptance_criteria, chat_log = process_message_with_2_llms(
|
591 |
-
user_message,
|
592 |
-
expected_output,
|
593 |
-
acceptance_criteria,
|
594 |
-
initial_system_message,
|
595 |
-
recursion_limit,
|
596 |
-
max_output_age,
|
597 |
-
advanced_optimizer_model_name_input,
|
598 |
-
advanced_executor_model_name_input,
|
599 |
-
prompt_template_group,
|
600 |
-
aggressive_exploration,
|
601 |
-
)
|
602 |
-
else: # Expert
|
603 |
-
system_message, output, analysis, acceptance_criteria, chat_log = process_message_with_expert_llms(
|
604 |
-
user_message,
|
605 |
-
expected_output,
|
606 |
-
acceptance_criteria,
|
607 |
-
initial_system_message,
|
608 |
-
recursion_limit,
|
609 |
-
max_output_age,
|
610 |
-
expert_prompt_initial_developer_model_name,
|
611 |
-
expert_prompt_initial_developer_temperature_input,
|
612 |
-
expert_prompt_acceptance_criteria_model_name,
|
613 |
-
expert_prompt_acceptance_criteria_temperature_input,
|
614 |
-
expert_prompt_developer_model_name,
|
615 |
-
expert_prompt_developer_temperature_input,
|
616 |
-
expert_prompt_executor_model_name,
|
617 |
-
expert_prompt_executor_temperature_input,
|
618 |
-
expert_prompt_output_history_analyzer_model_name,
|
619 |
-
expert_prompt_output_history_analyzer_temperature_input,
|
620 |
-
expert_prompt_analyzer_model_name,
|
621 |
-
expert_prompt_analyzer_temperature_input,
|
622 |
-
expert_prompt_suggester_model_name,
|
623 |
-
expert_prompt_suggester_temperature_input,
|
624 |
-
prompt_template_group,
|
625 |
-
aggressive_exploration,
|
626 |
-
)
|
627 |
-
|
628 |
-
st.session_state.system_message_output = system_message
|
629 |
-
st.session_state.output = output
|
630 |
-
st.session_state.analysis = analysis
|
631 |
-
st.session_state.acceptance_criteria_output = acceptance_criteria
|
632 |
-
st.session_state.chat_log = chat_log
|
633 |
-
|
634 |
-
except Exception as e:
|
635 |
-
st.error(f"Error: {e}")
|
636 |
-
|
637 |
-
st.text_area("System Message",
|
638 |
-
key="system_message_output", height=100)
|
639 |
-
st.button("Copy System Message", key="copy_system_message",
|
640 |
-
on_click=copy_system_message)
|
641 |
acceptance_criteria_output = st.text_area(
|
642 |
-
"Acceptance Criteria",
|
643 |
-
|
644 |
-
|
|
|
645 |
st.text_area("Output", st.session_state.output, height=100)
|
646 |
st.text_area("Analysis", st.session_state.analysis, height=100)
|
647 |
|
|
|
462 |
aggressive_exploration_input = st.checkbox("Aggressive Exploration", False)
|
463 |
|
464 |
# Initialize session state
|
465 |
+
if 'shared_input_data' not in st.session_state:
|
466 |
+
st.session_state.shared_input_data = pd.DataFrame(columns=["Input", "Output"])
|
467 |
if 'initial_system_message' not in st.session_state:
|
468 |
st.session_state.initial_system_message = ""
|
469 |
if 'initial_acceptance_criteria' not in st.session_state:
|
|
|
480 |
st.session_state.chat_log = []
|
481 |
|
482 |
def copy_system_message():
|
483 |
+
st.session_state.initial_system_message = system_message_output
|
|
|
484 |
|
485 |
def copy_acceptance_criteria():
|
486 |
+
st.session_state.initial_acceptance_criteria = acceptance_criteria_output
|
|
|
487 |
|
488 |
def clear_session_state():
|
489 |
+
st.session_state.shared_input_data = pd.DataFrame(columns=["Input", "Output"])
|
490 |
st.session_state.initial_system_message = ""
|
491 |
st.session_state.initial_acceptance_criteria = ""
|
492 |
st.session_state.system_message_output = ""
|
|
|
496 |
st.session_state.chat_log = []
|
497 |
|
498 |
def sync_input_data():
|
499 |
+
st.session_state.shared_input_data = data_editor_data.copy()
|
500 |
+
|
501 |
+
def pull_sample_description():
|
502 |
+
if 'description_output_text' in st.session_state:
|
503 |
+
st.session_state.initial_system_message = st.session_state.description_output_text
|
504 |
+
|
505 |
+
def generate_callback():
|
506 |
+
try:
|
507 |
+
first_input_key = data_editor_data["Input"].first_valid_index()
|
508 |
+
first_output_key = data_editor_data["Output"].first_valid_index()
|
509 |
+
user_message = data_editor_data["Input"][first_input_key].strip()
|
510 |
+
expected_output = data_editor_data["Output"][first_output_key].strip()
|
511 |
+
|
512 |
+
input_acceptance_criteria = initial_acceptance_criteria.strip() if 'initial_acceptance_criteria' in st.session_state else ""
|
513 |
+
input_system_message = initial_system_message.strip() if 'initial_system_message' in st.session_state else ""
|
514 |
+
|
515 |
+
if active_model_tab == "Simple":
|
516 |
+
system_message, output, analysis, acceptance_criteria, chat_log = process_message_with_single_llm(
|
517 |
+
user_message,
|
518 |
+
expected_output,
|
519 |
+
input_acceptance_criteria,
|
520 |
+
input_system_message,
|
521 |
+
recursion_limit,
|
522 |
+
max_output_age,
|
523 |
+
simple_model_name,
|
524 |
+
prompt_template_group,
|
525 |
+
aggressive_exploration,
|
526 |
+
)
|
527 |
+
elif active_model_tab == "Advanced":
|
528 |
+
system_message, output, analysis, acceptance_criteria, chat_log = process_message_with_2_llms(
|
529 |
+
user_message,
|
530 |
+
expected_output,
|
531 |
+
input_acceptance_criteria,
|
532 |
+
input_system_message,
|
533 |
+
recursion_limit,
|
534 |
+
max_output_age,
|
535 |
+
advanced_optimizer_model_name_input,
|
536 |
+
advanced_executor_model_name_input,
|
537 |
+
prompt_template_group,
|
538 |
+
aggressive_exploration,
|
539 |
+
)
|
540 |
+
else: # Expert
|
541 |
+
system_message, output, analysis, acceptance_criteria, chat_log = process_message_with_expert_llms(
|
542 |
+
user_message,
|
543 |
+
expected_output,
|
544 |
+
input_acceptance_criteria,
|
545 |
+
input_system_message,
|
546 |
+
recursion_limit,
|
547 |
+
max_output_age,
|
548 |
+
expert_prompt_initial_developer_model_name,
|
549 |
+
expert_prompt_initial_developer_temperature_input,
|
550 |
+
expert_prompt_acceptance_criteria_model_name,
|
551 |
+
expert_prompt_acceptance_criteria_temperature_input,
|
552 |
+
expert_prompt_developer_model_name,
|
553 |
+
expert_prompt_developer_temperature_input,
|
554 |
+
expert_prompt_executor_model_name,
|
555 |
+
expert_prompt_executor_temperature_input,
|
556 |
+
expert_prompt_output_history_analyzer_model_name,
|
557 |
+
expert_prompt_output_history_analyzer_temperature_input,
|
558 |
+
expert_prompt_analyzer_model_name,
|
559 |
+
expert_prompt_analyzer_temperature_input,
|
560 |
+
expert_prompt_suggester_model_name,
|
561 |
+
expert_prompt_suggester_temperature_input,
|
562 |
+
prompt_template_group,
|
563 |
+
aggressive_exploration,
|
564 |
+
)
|
565 |
+
|
566 |
+
st.session_state.system_message_output = system_message
|
567 |
+
st.session_state.output = output
|
568 |
+
st.session_state.analysis = analysis
|
569 |
+
st.session_state.acceptance_criteria_output = acceptance_criteria
|
570 |
+
st.session_state.chat_log = chat_log
|
571 |
+
|
572 |
+
except Exception as e:
|
573 |
+
st.error(f"Error: {e}")
|
574 |
+
|
575 |
|
576 |
if active_model_tab == "Simple":
|
577 |
simple_model_name = simple_model_name_input
|
|
|
616 |
aggressive_exploration = aggressive_exploration_input
|
617 |
|
618 |
data_editor_data = st.data_editor(
|
619 |
+
st.session_state.shared_input_data,
|
620 |
+
# key="meta_prompt_input_data",
|
621 |
num_rows="dynamic",
|
622 |
column_config={
|
623 |
"Input": st.column_config.TextColumn("Input", width="large"),
|
624 |
"Output": st.column_config.TextColumn("Output", width="large"),
|
625 |
},
|
626 |
+
hide_index=False,
|
627 |
use_container_width=True,
|
628 |
)
|
629 |
|
|
|
631 |
|
632 |
with col1:
|
633 |
with st.expander("Advanced Inputs"):
|
634 |
+
|
635 |
+
initial_system_message = st.text_area(
|
636 |
+
"Initial System Message",
|
637 |
+
# "Default System Message",
|
638 |
+
# st.session_state.initial_system_message,
|
639 |
+
key="initial_system_message"
|
640 |
+
)
|
641 |
+
|
642 |
+
col1_1, col1_2 = st.columns(2)
|
643 |
+
with col1_1:
|
644 |
+
pull_sample_description_button = st.button("Pull Sample Description", key="pull_sample_description",
|
645 |
+
on_click=pull_sample_description)
|
646 |
+
with col1_2:
|
647 |
+
st.button("Pull Output", key="copy_system_message",
|
648 |
+
on_click=copy_system_message)
|
649 |
+
initial_acceptance_criteria = st.text_area(
|
650 |
+
"Acceptance Criteria",
|
651 |
+
# "Default Acceptance Criteria",
|
652 |
+
# st.session_state.initial_acceptance_criteria,
|
653 |
+
key="initial_acceptance_criteria"
|
654 |
+
)
|
655 |
+
st.button("Pull Output", key="copy_acceptance_criteria",
|
656 |
+
on_click=copy_acceptance_criteria)
|
657 |
+
|
658 |
col1_1, col1_2, col1_3 = st.columns(3)
|
659 |
with col1_1:
|
660 |
+
generate_button_clicked = st.button("Generate", key="generate_button",
|
661 |
+
on_click=generate_callback,
|
662 |
+
type="primary")
|
663 |
with col1_2:
|
664 |
+
sync_button_clicked = st.button("Sync Data", on_click=sync_input_data)
|
665 |
with col1_3:
|
666 |
clear_button_clicked = st.button("Clear", on_click=clear_session_state)
|
667 |
|
668 |
with col2:
|
669 |
+
system_message_output = st.text_area("System Message",
|
670 |
+
# st.session_state.system_message_output,
|
671 |
+
key="system_message_output",
|
672 |
+
height=100)
|
673 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
674 |
acceptance_criteria_output = st.text_area(
|
675 |
+
"Acceptance Criteria",
|
676 |
+
# st.session_state.acceptance_criteria_output,
|
677 |
+
key="acceptance_criteria_output",
|
678 |
+
height=100)
|
679 |
st.text_area("Output", st.session_state.output, height=100)
|
680 |
st.text_area("Analysis", st.session_state.analysis, height=100)
|
681 |
|
app/streamlit_sample_generator.py
CHANGED
@@ -144,8 +144,8 @@ def example_selected():
|
|
144 |
|
145 |
|
146 |
# Session State
|
147 |
-
if '
|
148 |
-
st.session_state.
|
149 |
|
150 |
if 'description_output_text' not in st.session_state:
|
151 |
st.session_state.description_output_text = ''
|
@@ -245,7 +245,7 @@ def import_input_data_from_json():
|
|
245 |
data = st.session_state.input_file.getvalue()
|
246 |
data = json.loads(data)
|
247 |
data = [{k.capitalize(): v for k, v in d.items()} for d in data]
|
248 |
-
st.session_state.
|
249 |
except Exception as e:
|
250 |
st.warning(f"Failed to import JSON: {str(e)}")
|
251 |
|
@@ -278,11 +278,11 @@ def add_new_suggestion():
|
|
278 |
st.session_state.new_suggestion = "" # Clear the input field
|
279 |
|
280 |
def sync_input_data():
|
281 |
-
st.session_state.meta_prompt_input_data = input_data.copy()
|
282 |
-
st.session_state.
|
283 |
|
284 |
def clear_session_state():
|
285 |
-
st.session_state.
|
286 |
st.session_state.description_output_text = ''
|
287 |
st.session_state.suggestions = []
|
288 |
st.session_state.input_analysis_output_text = ''
|
@@ -298,13 +298,15 @@ st.markdown("Enter input-output pairs in the table below to generate a task desc
|
|
298 |
|
299 |
# Input column
|
300 |
input_data = st.data_editor(
|
301 |
-
st.session_state.
|
|
|
302 |
num_rows="dynamic",
|
303 |
use_container_width=True,
|
304 |
column_config={
|
305 |
"Input": st.column_config.TextColumn("Input", width="large"),
|
306 |
"Output": st.column_config.TextColumn("Output", width="large"),
|
307 |
},
|
|
|
308 |
)
|
309 |
|
310 |
with st.expander("Model Settings"):
|
@@ -336,7 +338,7 @@ with col1:
|
|
336 |
"Generate", type="primary", on_click=generate_examples_dataframe)
|
337 |
with col2:
|
338 |
sync_button = st.button(
|
339 |
-
"Sync", on_click=sync_input_data)
|
340 |
with col3:
|
341 |
clear_button = st.button(
|
342 |
"Clear", on_click=clear_session_state)
|
@@ -370,7 +372,7 @@ with st.expander("Description and Analysis"):
|
|
370 |
|
371 |
examples_directly_output = st.dataframe(st.session_state.examples_directly_dataframe, use_container_width=True,
|
372 |
selection_mode="multi-row", key="selected_example_directly_id",
|
373 |
-
on_select=example_directly_selected)
|
374 |
input_analysis_output = st.text_area(
|
375 |
"Input Analysis", value=st.session_state.input_analysis_output_text, height=100)
|
376 |
generate_briefs_button = st.button(
|
@@ -381,21 +383,21 @@ with st.expander("Description and Analysis"):
|
|
381 |
"Generate Examples from Briefs", on_click=update_examples_from_briefs_dataframe)
|
382 |
examples_from_briefs_output = st.dataframe(st.session_state.examples_from_briefs_dataframe, use_container_width=True,
|
383 |
selection_mode="multi-row", key="selected_example_from_briefs_id",
|
384 |
-
on_select=example_from_briefs_selected)
|
385 |
|
386 |
examples_output = st.dataframe(st.session_state.examples_dataframe, use_container_width=True,
|
387 |
-
selection_mode="multi-row", key="selected_example_id", on_select=example_selected)
|
388 |
|
389 |
def append_selected_to_input_data():
|
390 |
if st.session_state.selected_example is not None:
|
391 |
-
st.session_state.
|
392 |
-
[
|
393 |
st.session_state.selected_example = None
|
394 |
|
395 |
def show_sidebar():
|
396 |
if st.session_state.selected_example is not None:
|
397 |
with st.sidebar:
|
398 |
-
st.dataframe(st.session_state.selected_example) # Display DataFrame in sidebar
|
399 |
st.button("Append to Input Data", on_click=append_selected_to_input_data)
|
400 |
|
401 |
show_sidebar()
|
|
|
144 |
|
145 |
|
146 |
# Session State
|
147 |
+
if 'shared_input_data' not in st.session_state:
|
148 |
+
st.session_state.shared_input_data = pd.DataFrame(columns=["Input", "Output"])
|
149 |
|
150 |
if 'description_output_text' not in st.session_state:
|
151 |
st.session_state.description_output_text = ''
|
|
|
245 |
data = st.session_state.input_file.getvalue()
|
246 |
data = json.loads(data)
|
247 |
data = [{k.capitalize(): v for k, v in d.items()} for d in data]
|
248 |
+
st.session_state.shared_input_data = pd.DataFrame(data)
|
249 |
except Exception as e:
|
250 |
st.warning(f"Failed to import JSON: {str(e)}")
|
251 |
|
|
|
278 |
st.session_state.new_suggestion = "" # Clear the input field
|
279 |
|
280 |
def sync_input_data():
|
281 |
+
# st.session_state.meta_prompt_input_data = input_data.copy()
|
282 |
+
st.session_state.shared_input_data = input_data.copy()
|
283 |
|
284 |
def clear_session_state():
|
285 |
+
st.session_state.shared_input_data = pd.DataFrame(columns=["Input", "Output"])
|
286 |
st.session_state.description_output_text = ''
|
287 |
st.session_state.suggestions = []
|
288 |
st.session_state.input_analysis_output_text = ''
|
|
|
298 |
|
299 |
# Input column
|
300 |
input_data = st.data_editor(
|
301 |
+
st.session_state.shared_input_data,
|
302 |
+
# key="sample_generator_input_data",
|
303 |
num_rows="dynamic",
|
304 |
use_container_width=True,
|
305 |
column_config={
|
306 |
"Input": st.column_config.TextColumn("Input", width="large"),
|
307 |
"Output": st.column_config.TextColumn("Output", width="large"),
|
308 |
},
|
309 |
+
hide_index=False
|
310 |
)
|
311 |
|
312 |
with st.expander("Model Settings"):
|
|
|
338 |
"Generate", type="primary", on_click=generate_examples_dataframe)
|
339 |
with col2:
|
340 |
sync_button = st.button(
|
341 |
+
"Sync Data", on_click=sync_input_data)
|
342 |
with col3:
|
343 |
clear_button = st.button(
|
344 |
"Clear", on_click=clear_session_state)
|
|
|
372 |
|
373 |
examples_directly_output = st.dataframe(st.session_state.examples_directly_dataframe, use_container_width=True,
|
374 |
selection_mode="multi-row", key="selected_example_directly_id",
|
375 |
+
on_select=example_directly_selected, hide_index=False)
|
376 |
input_analysis_output = st.text_area(
|
377 |
"Input Analysis", value=st.session_state.input_analysis_output_text, height=100)
|
378 |
generate_briefs_button = st.button(
|
|
|
383 |
"Generate Examples from Briefs", on_click=update_examples_from_briefs_dataframe)
|
384 |
examples_from_briefs_output = st.dataframe(st.session_state.examples_from_briefs_dataframe, use_container_width=True,
|
385 |
selection_mode="multi-row", key="selected_example_from_briefs_id",
|
386 |
+
on_select=example_from_briefs_selected, hide_index=False)
|
387 |
|
388 |
examples_output = st.dataframe(st.session_state.examples_dataframe, use_container_width=True,
|
389 |
+
selection_mode="multi-row", key="selected_example_id", on_select=example_selected, hide_index=True)
|
390 |
|
391 |
def append_selected_to_input_data():
|
392 |
if st.session_state.selected_example is not None:
|
393 |
+
st.session_state.shared_input_data = pd.concat(
|
394 |
+
[input_data, st.session_state.selected_example], ignore_index=True)
|
395 |
st.session_state.selected_example = None
|
396 |
|
397 |
def show_sidebar():
|
398 |
if st.session_state.selected_example is not None:
|
399 |
with st.sidebar:
|
400 |
+
st.dataframe(st.session_state.selected_example, hide_index=False) # Display DataFrame in sidebar
|
401 |
st.button("Append to Input Data", on_click=append_selected_to_input_data)
|
402 |
|
403 |
show_sidebar()
|
config.yml
CHANGED
@@ -82,6 +82,7 @@ recursion_limit_max: 25
|
|
82 |
max_output_age: 2
|
83 |
allow_flagging: false
|
84 |
# verbose: false
|
|
|
85 |
|
86 |
prompt_templates:
|
87 |
|
|
|
82 |
max_output_age: 2
|
83 |
allow_flagging: false
|
84 |
# verbose: false
|
85 |
+
verbose: true
|
86 |
|
87 |
prompt_templates:
|
88 |
|
guidelines/streamlit.md
CHANGED
@@ -1,723 +1,224 @@
|
|
1 |
-
# Streamlit Guideline
|
2 |
|
3 |
## 1. Framework Overview
|
4 |
|
5 |
-
|
6 |
-
Streamlit is an open-source app framework specifically designed for Machine Learning and Data Science teams. It allows developers to create web apps for their data projects quickly and efficiently using Python scripting. Streamlit's key features include its simplicity, ease of use, and the ability to build and deploy apps rapidly.
|
7 |
-
|
8 |
-
### Key Features
|
9 |
-
- **Simplicity**: Streamlit's API is designed to be intuitive and easy to use, making it accessible for both beginners and experienced developers.
|
10 |
-
- **Rapid Development**: With Streamlit, you can go from idea to app in minutes, thanks to its reactive programming model.
|
11 |
-
- **Python-Centric**: Streamlit leverages Python for all the coding, making it a favorite among data scientists and ML engineers.
|
12 |
-
- **Rich Widgets**: Streamlit provides a variety of widgets like sliders, buttons, and text inputs, which enhance user interaction with the app.
|
13 |
-
|
14 |
-
### Advantages
|
15 |
-
- **No Frontend Experience Required**: Developers can focus on Python scripting without needing to learn HTML, CSS, or JavaScript.
|
16 |
-
- **Automatic UI Updates**: Streamlit automatically updates the web app when the script is modified, facilitating rapid prototyping.
|
17 |
-
- **Seamless Integration**: It integrates well with other Python libraries and tools commonly used in data science and ML.
|
18 |
-
|
19 |
-
## 2. Installation and Setup
|
20 |
-
|
21 |
-
### Step-by-Step Installation
|
22 |
-
1. **Install Streamlit**: Open your terminal and run the following command to install Streamlit using pip:
|
23 |
-
```bash
|
24 |
-
pip install streamlit
|
25 |
-
```
|
26 |
-
2. **Verify Installation**: To ensure Streamlit is installed correctly, run:
|
27 |
-
```bash
|
28 |
-
streamlit hello
|
29 |
-
```
|
30 |
-
This command will open a sample app in your default web browser.
|
31 |
-
|
32 |
-
### Setting Up a New Project
|
33 |
-
1. **Create a New Directory**:
|
34 |
-
```bash
|
35 |
-
mkdir my_streamlit_app
|
36 |
-
cd my_streamlit_app
|
37 |
-
```
|
38 |
-
2. **Create a Python Script**: Create a new Python file, e.g., `app.py`.
|
39 |
-
3. **Write Your First App**: Open `app.py` in your favorite text editor and add the following lines:
|
40 |
-
```python
|
41 |
-
import streamlit as st
|
42 |
-
|
43 |
-
st.title("My First Streamlit App")
|
44 |
-
st.write("Hello, world!")
|
45 |
-
```
|
46 |
-
4. **Run Your App**: In the terminal, run:
|
47 |
-
```bash
|
48 |
-
streamlit run app.py
|
49 |
-
```
|
50 |
-
This command will start a local web server and open your app in the browser.
|
51 |
-
|
52 |
-
### Prerequisites and Dependencies
|
53 |
-
- **Python**: Ensure Python 3.6 or later is installed on your system.
|
54 |
-
- **Pip**: Pip should be installed to manage Python packages.
|
55 |
-
|
56 |
-
## 3. Core Concepts
|
57 |
-
|
58 |
-
### Fundamental Concepts and Principles
|
59 |
-
- **Reactive Programming**: Streamlit follows a reactive programming model where changes in the script automatically update the app.
|
60 |
-
- **Widgets**: Streamlit provides various widgets (e.g., sliders, buttons, text inputs) to interact with the app.
|
61 |
-
- **Layouts and Containers**: Streamlit allows you to organize your app's layout using columns, containers, and expanders.
|
62 |
-
|
63 |
-
### Architecture and Design Patterns
|
64 |
-
- **Single-Page App**: Streamlit apps are typically single-page applications where the entire app runs within a single HTML page.
|
65 |
-
- **State Management**: Streamlit manages the state of the app automatically, but you can use session state for more complex state management.
|
66 |
-
|
67 |
-
## 4. Component Structure
|
68 |
-
|
69 |
-
### Creating and Structuring Components
|
70 |
-
|
71 |
-
Streamlit provides a variety of components to build interactive web applications. These components range from simple text displays to complex widgets that allow user input. Understanding how to structure and use these components is crucial for building effective Streamlit apps.
|
72 |
-
|
73 |
-
Here is the list of components with brief descriptions, examples, and links to the reference page:
|
74 |
-
|
75 |
-
### Basic Components
|
76 |
-
|
77 |
-
* `st.title()`: Display a title.
|
78 |
-
+ Example: `st.title("My Streamlit App")`
|
79 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/text/st.title)
|
80 |
-
* `st.header()`: Display a header.
|
81 |
-
+ Example: `st.header("Welcome to My App")`
|
82 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/text/st.header)
|
83 |
-
* `st.subheader()`: Display a subheader.
|
84 |
-
+ Example: `st.subheader("This is a subheader")`
|
85 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/text/st.subheader)
|
86 |
-
* `st.text()`: Display fixed-width text.
|
87 |
-
+ Example: `st.text("Some fixed-width text")`
|
88 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/text/st.text)
|
89 |
-
* `st.markdown()`: Render markdown text.
|
90 |
-
+ Example: `st.markdown("**Bold** and *italic* text")`
|
91 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/text/st.markdown)
|
92 |
-
* `st.latex()`: Display mathematical expressions formatted as LaTeX.
|
93 |
-
+ Example: `st.latex(r"\alpha + \beta = \gamma")`
|
94 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/text/st.latex)
|
95 |
-
* `st.write()`: Write a generic piece of text or data.
|
96 |
-
+ Example: `st.write("Here's a dataframe:", df)`
|
97 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/write-magic/st.write)
|
98 |
-
* `st.dataframe()`: Display a dataframe.
|
99 |
-
+ Example: `st.dataframe(df)`
|
100 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/data/st.dataframe)
|
101 |
-
* `st.table()`: Display a static table.
|
102 |
-
+ Example: `st.table(df)`
|
103 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/data/st.table)
|
104 |
-
* `st.json()`: Display JSON data.
|
105 |
-
+ Example: `st.json(df.to_json())`
|
106 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/data/st.json)
|
107 |
-
* `st.button()`: Create a button.
|
108 |
-
+ Example: `if st.button("Click me"): st.write("Button clicked!")`
|
109 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/widgets/st.button)
|
110 |
-
* `st.checkbox()`: Create a checkbox.
|
111 |
-
+ Example: `agree = st.checkbox("I agree")`
|
112 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/widgets/st.checkbox)
|
113 |
-
* `st.radio()`: Create a radio button group.
|
114 |
-
+ Example: `option = st.radio("Choose an option", ["Option 1", "Option 2"])`
|
115 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/widgets/st.radio)
|
116 |
-
* `st.selectbox()`: Create a select box.
|
117 |
-
+ Example: `choice = st.selectbox("Select an option", ["A", "B", "C"])`
|
118 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/widgets/st.selectbox)
|
119 |
-
* `st.multiselect()`: Create a multiselect box.
|
120 |
-
+ Example: `multi_choices = st.multiselect("Choose multiple options", ["X", "Y", "Z"])`
|
121 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/widgets/st.multiselect)
|
122 |
-
* `st.slider()`: Create a slider.
|
123 |
-
+ Example: `value = st.slider("Select a value", 0, 100, 50)`
|
124 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/widgets/st.slider)
|
125 |
-
* `st.text_input()`: Create a text input box.
|
126 |
-
+ Example: `text = st.text_input("Enter some text")`
|
127 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/widgets/st.text_input)
|
128 |
-
* `st.number_input()`: Create a number input box.
|
129 |
-
+ Example: `number = st.number_input("Enter a number")`
|
130 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/widgets/st.number_input)
|
131 |
-
* `st.date_input()`: Create a date input box.
|
132 |
-
+ Example: `date = st.date_input("Select a date")`
|
133 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/widgets/st.date_input)
|
134 |
-
* `st.time_input()`: Create a time input box.
|
135 |
-
+ Example: `time = st.time_input("Select a time")`
|
136 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/widgets/st.time_input)
|
137 |
-
* `st.file_uploader()`: Allow file uploads.
|
138 |
-
+ Example: `file = st.file_uploader("Upload a file")`
|
139 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/widgets/st.file_uploader)
|
140 |
-
|
141 |
-
### Layout Components
|
142 |
-
|
143 |
-
* `st.sidebar()`: Add content to the sidebar.
|
144 |
-
+ Example: `st.sidebar.title("Sidebar Title")`
|
145 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/layout/st.sidebar)
|
146 |
-
* `st.columns()`: Create columns for layout.
|
147 |
-
+ Example: `col1, col2 = st.columns(2)`
|
148 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/layout/st.columns)
|
149 |
-
* `st.expander()`: Create an expandable container.
|
150 |
-
+ Example: `with st.expander("Click to expand"): st.write("Expanded content")`
|
151 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/layout/st.expander)
|
152 |
-
* `st.container()`: Insert a multi-element container.
|
153 |
-
+ Example: `c = st.container()`
|
154 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/layout/st.container)
|
155 |
-
* `st.empty()`: Insert a single-element container.
|
156 |
-
+ Example: `c = st.empty()`
|
157 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/layout/st.empty)
|
158 |
-
* `st.tabs()`: Insert containers separated into tabs.
|
159 |
-
+ Example: `tab1, tab2 = st.tabs(["Tab 1", "Tab 2"])`
|
160 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/layout/st.tabs)
|
161 |
-
|
162 |
-
### Status Components
|
163 |
-
|
164 |
-
* `st.progress()`: Display a progress bar.
|
165 |
-
+ Example: `with st.progress(100): do_something()`
|
166 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/status/st.progress)
|
167 |
-
* `st.spinner()`: Display a spinning wheel.
|
168 |
-
+ Example: `with st.spinner("Wait for it..."): do_something()`
|
169 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/status/st.spinner)
|
170 |
-
* `st.success()`: Display a success message.
|
171 |
-
+ Example: `st.success("Done!")`
|
172 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/status/st.success)
|
173 |
-
* `st.error()`: Display an error message.
|
174 |
-
+ Example: `st.error("Error message")`
|
175 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/status/st.error)
|
176 |
-
* `st.warning()`: Display a warning message.
|
177 |
-
+ Example: `st.warning("Warning message")`
|
178 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/status/st.warning)
|
179 |
-
* `st.info()`: Display an info message.
|
180 |
-
+ Example: `st.info("Info message")`
|
181 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/status/st.info)
|
182 |
-
* `st.exception()`: Display an exception message.
|
183 |
-
+ Example: `st.exception("Exception message")`
|
184 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/status/st.exception)
|
185 |
-
* `st.stop()`: Stop the app.
|
186 |
-
+ Example: `st.stop()`
|
187 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/status/st.stop)
|
188 |
-
|
189 |
-
### Navigation Components
|
190 |
-
|
191 |
-
* `st.page_link()`: Display a link to another page in a multipage app.
|
192 |
-
+ Example: `st.page_link("app.py", label="Home", icon="🏠")`
|
193 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/widgets/st.page_link)
|
194 |
-
* `st.navigation()`: Configure the available pages in a multipage app.
|
195 |
-
+ Example: `st.navigation({"Your account": [log_out, settings]})`
|
196 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/navigation/st.navigation)
|
197 |
-
* `st.page()`: Define a page in a multipage app.
|
198 |
-
+ Example: `home = st.Page("home.py", title="Home", icon="🏠")`
|
199 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/navigation/st.page)
|
200 |
-
* `st.switch_page()`: Programmatically navigate to a specified page.
|
201 |
-
+ Example: `st.switch_page("pages/my_page.py")`
|
202 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/navigation/st.switch_page)
|
203 |
-
|
204 |
-
### Execution Flow Components
|
205 |
-
|
206 |
-
* `st.form()`: Create a form that batches elements together with a “Submit” button.
|
207 |
-
+ Example: `with st.form(key="my_form"): name = st.text_input("Name")`
|
208 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/execution-flow/st.form)
|
209 |
-
* `st.form_submit_button()`: Create a form submit button.
|
210 |
-
+ Example: `st.form_submit_button("Sign up")`
|
211 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/execution-flow/st.form_submit_button)
|
212 |
-
* `st.dialog()`: Insert a modal dialog that can rerun independently from the rest of the script.
|
213 |
-
+ Example: `@st.dialog("Sign up") def email_form(): name = st.text_input("Name")`
|
214 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/execution-flow/st.dialog)
|
215 |
-
* `st.fragment()`: Define a fragment to rerun independently from the rest of the script.
|
216 |
-
+ Example: `@st.fragment(run_every="10s") def fragment(): df = get_data()`
|
217 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/execution-flow/st.fragment)
|
218 |
-
* `st.rerun()`: Rerun the script immediately.
|
219 |
-
+ Example: `st.rerun()`
|
220 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/execution-flow/st.rerun)
|
221 |
-
* `st.stop()`: Stop the app.
|
222 |
-
+ Example: `st.stop()`
|
223 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/execution-flow/st.stop)
|
224 |
-
|
225 |
-
### Caching and State Components
|
226 |
-
|
227 |
-
* `st.cache_data()`: Function decorator to cache functions that return data.
|
228 |
-
+ Example: `@st.cache_data def long_function(param1, param2): return data`
|
229 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/caching-and-state/st.cache_data)
|
230 |
-
* `st.cache_resource()`: Function decorator to cache functions that return global resources.
|
231 |
-
+ Example: `@st.cache_resource def init_model(): return pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")`
|
232 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/caching-and-state/st.cache_resource)
|
233 |
-
* `st.session_state()`: Session state is a way to share variables between reruns, for each user session.
|
234 |
-
+ Example: `st.session_state["key"] = value`
|
235 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/caching-and-state/st.session_state)
|
236 |
-
* `st.query_params()`: Get, set, or clear the query parameters that are shown in the browser's URL bar.
|
237 |
-
+ Example: `st.query_params["key"] = value`
|
238 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/caching-and-state/st.query_params)
|
239 |
-
|
240 |
-
### Utilities Components
|
241 |
-
|
242 |
-
* `st.context()`: st.context provides a read-only interface to access cookies and headers.
|
243 |
-
+ Example: `st.context.cookies`
|
244 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/utilities/st.context)
|
245 |
-
* `st.help()`: Display object’s doc string, nicely formatted.
|
246 |
-
+ Example: `st.help(st.write)`
|
247 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/utilities/st.help)
|
248 |
-
* `st.html()`: Renders HTML strings to your app.
|
249 |
-
+ Example: `st.html("<p>Foo bar.</p>")`
|
250 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/utilities/st.html)
|
251 |
-
* `st.experimental_user()`: st.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.
|
252 |
-
+ Example: `if st.experimental_user.email == "[email protected]": st.write("Welcome back,", st.experimental_user.email)`
|
253 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/utilities/st.experimental_user)
|
254 |
-
|
255 |
-
### Testing Components
|
256 |
-
|
257 |
-
* `st.testing.v1.AppTest`: Simulates a running Streamlit app for testing.
|
258 |
-
+ Example: `at = AppTest.from_file("streamlit_app.py")`
|
259 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest)
|
260 |
-
* `st.testing.v1.ElementTree`: A representation of container elements.
|
261 |
-
+ Example: `at.sidebar`
|
262 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreeblock)
|
263 |
-
* `st.testing.v1.Block`: A representation of container elements.
|
264 |
-
+ Example: `at.sidebar`
|
265 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreeblock)
|
266 |
-
* `st.testing.v1.Element`: The base class for representation of all elements.
|
267 |
-
+ Example: `at.title`
|
268 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreeelement)
|
269 |
-
* `st.testing.v1.Button`: A representation of st.button and st.form_submit_button.
|
270 |
-
+ Example: `at.button`
|
271 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreebutton)
|
272 |
-
* `st.testing.v1.ChatInput`: A representation of st.chat_input.
|
273 |
-
+ Example: `at.chat_input`
|
274 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreechatinput)
|
275 |
-
* `st.testing.v1.Checkbox`: A representation of st.checkbox.
|
276 |
-
+ Example: `at.checkbox`
|
277 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreecheckbox)
|
278 |
-
* `st.testing.v1.ColorPicker`: A representation of st.color_picker.
|
279 |
-
+ Example: `at.color_picker`
|
280 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreecolorpicker)
|
281 |
-
* `st.testing.v1.DateInput`: A representation of st.date_input.
|
282 |
-
+ Example: `at.date_input`
|
283 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreedateinput)
|
284 |
-
* `st.testing.v1.Multiselect`: A representation of st.multiselect.
|
285 |
-
+ Example: `at.multiselect`
|
286 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreemultiselect)
|
287 |
-
* `st.testing.v1.NumberInput`: A representation of st.number_input.
|
288 |
-
+ Example: `at.number_input`
|
289 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreenumberinput)
|
290 |
-
* `st.testing.v1.Radio`: A representation of st.radio.
|
291 |
-
+ Example: `at.radio`
|
292 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreeradio)
|
293 |
-
* `st.testing.v1.SelectSlider`: A representation of st.select_slider.
|
294 |
-
+ Example: `at.select_slider`
|
295 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreeselectslider)
|
296 |
-
* `st.testing.v1.Selectbox`: A representation of st.selectbox.
|
297 |
-
+ Example: `at.selectbox`
|
298 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreeselectbox)
|
299 |
-
* `st.testing.v1.Slider`: A representation of st.slider.
|
300 |
-
+ Example: `at.slider`
|
301 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreeslider)
|
302 |
-
* `st.testing.v1.TextArea`: A representation of st.text_area.
|
303 |
-
+ Example: `at.text_area`
|
304 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreetextarea)
|
305 |
-
* `st.testing.v1.TextInput`: A representation of st.text_input.
|
306 |
-
+ Example: `at.text_input`
|
307 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreetextinput)
|
308 |
-
* `st.testing.v1.TimeInput`: A representation of st.time_input.
|
309 |
-
+ Example: `at.time_input`
|
310 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreetimeinput)
|
311 |
-
* `st.testing.v1.Toggle`: A representation of st.toggle.
|
312 |
-
+ Example: `at.toggle`
|
313 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element%5Ftreetoggle)
|
314 |
-
|
315 |
-
### Custom Components
|
316 |
-
|
317 |
-
* `st.components.v1.declare_component()`: Create and register a custom component.
|
318 |
-
+ Example: `declare_component("custom_slider", "/frontend")`
|
319 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/custom-components/st.components.v1.declare_component)
|
320 |
-
* `st.components.v1.html()`: Display an HTML string in an iframe.
|
321 |
-
+ Example: `html("<p>Foo bar.</p>")`
|
322 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/custom-components/st.components.v1.html)
|
323 |
-
* `st.components.v1.iframe()`: Load a remote URL in an iframe.
|
324 |
-
+ Example: `iframe("docs.streamlit.io")`
|
325 |
-
+ [Reference](https://docs.streamlit.io/develop/api-reference/custom-components/st.components.v1.iframe)
|
326 |
-
|
327 |
-
### Examples of Different Types of Components
|
328 |
-
|
329 |
-
#### Functional Components
|
330 |
-
Functional components are straightforward and used for displaying static content.
|
331 |
|
332 |
-
|
333 |
-
st.title("Welcome to My App")
|
334 |
-
st.header("Main Features")
|
335 |
-
st.subheader("Feature 1")
|
336 |
-
st.text("This is a description of feature 1.")
|
337 |
-
st.markdown("**Feature 2** is also important.")
|
338 |
-
```
|
339 |
|
340 |
-
|
341 |
-
Stateful components involve user interaction and can change based on user input.
|
342 |
|
343 |
-
|
344 |
-
if 'count' not in st.session_state:
|
345 |
-
st.session_state.count = 0
|
346 |
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
st.button('Increment', on_click=increment_counter)
|
351 |
-
st.write('Count:', st.session_state.count)
|
352 |
-
```
|
353 |
|
354 |
-
###
|
355 |
|
356 |
-
|
357 |
|
358 |
```python
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
|
|
|
|
|
|
367 |
```
|
368 |
|
369 |
-
|
370 |
-
|
371 |
-
### Handling User Interactions and Events
|
372 |
-
|
373 |
-
User interactions are a core part of any interactive web application. Streamlit provides various widgets to capture user input and trigger actions based on these inputs.
|
374 |
-
|
375 |
-
#### Button Clicks
|
376 |
-
Buttons are used to trigger actions. You can use the `on_click` parameter to define a callback function.
|
377 |
|
378 |
```python
|
379 |
-
|
380 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
381 |
```
|
382 |
|
383 |
-
####
|
384 |
-
Forms are used to group related inputs and can be submitted together.
|
385 |
|
386 |
```python
|
387 |
-
|
388 |
-
|
389 |
-
submit_button = st.form_submit_button(label='Submit')
|
390 |
|
391 |
-
if
|
392 |
-
st.
|
393 |
```
|
394 |
|
395 |
-
|
396 |
-
Checkboxes are used to capture boolean inputs.
|
397 |
|
398 |
-
|
399 |
-
agree = st.checkbox("I agree")
|
400 |
-
if agree:
|
401 |
-
st.write("Great! You agreed.")
|
402 |
-
```
|
403 |
|
404 |
-
|
405 |
-
|
|
|
406 |
|
407 |
-
|
408 |
-
option = st.radio("Choose an option", ["Option 1", "Option 2"])
|
409 |
-
st.write("You selected:", option)
|
410 |
-
```
|
411 |
|
412 |
-
####
|
413 |
-
Select boxes allow users to select one option from a dropdown.
|
414 |
|
415 |
```python
|
416 |
-
|
417 |
-
|
418 |
```
|
419 |
|
420 |
-
####
|
421 |
-
Multiselect boxes allow users to select multiple options.
|
422 |
|
423 |
```python
|
424 |
-
|
425 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
426 |
```
|
427 |
|
428 |
-
####
|
429 |
-
Sliders allow users to select a value from a range.
|
430 |
|
431 |
```python
|
432 |
-
|
433 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
434 |
```
|
435 |
|
436 |
-
|
437 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
438 |
|
439 |
```python
|
440 |
-
|
441 |
-
st.
|
442 |
```
|
443 |
|
444 |
-
####
|
445 |
-
Number inputs allow users to enter numeric values.
|
446 |
|
447 |
```python
|
448 |
-
|
449 |
-
|
|
|
|
|
|
|
450 |
```
|
451 |
|
452 |
-
|
453 |
-
Date and time inputs allow users to select dates and times.
|
454 |
|
455 |
-
|
456 |
-
date = st.date_input("Select a date")
|
457 |
-
st.write("You selected:", date)
|
458 |
|
459 |
-
|
460 |
-
|
461 |
-
|
|
|
|
|
462 |
|
463 |
-
|
464 |
-
File uploaders allow users to upload files.
|
465 |
|
466 |
```python
|
467 |
-
|
468 |
-
|
469 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
470 |
```
|
471 |
|
472 |
-
|
473 |
|
474 |
-
|
475 |
|
476 |
-
|
477 |
-
Callbacks can be used to update the session state, allowing you to manage state across reruns of the app.
|
478 |
|
479 |
-
|
480 |
-
if 'count' not in st.session_state:
|
481 |
-
st.session_state.count = 0
|
482 |
-
|
483 |
-
def increment_counter():
|
484 |
-
st.session_state.count += 1
|
485 |
|
486 |
-
|
487 |
-
st.
|
|
|
488 |
```
|
489 |
|
490 |
-
|
491 |
-
Callbacks can also be used with forms to handle form submissions.
|
492 |
|
493 |
-
|
494 |
-
with st.form(key='my_form'):
|
495 |
-
text_input = st.text_input(label='Enter some text')
|
496 |
-
submit_button = st.form_submit_button(label='Submit')
|
497 |
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
|
502 |
-
|
503 |
-
Callbacks can be used with various widgets to handle user interactions.
|
504 |
|
505 |
```python
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
```
|
511 |
|
512 |
-
|
513 |
|
514 |
-
###
|
515 |
|
516 |
-
Streamlit
|
517 |
|
518 |
-
|
519 |
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
your_working_directory/
|
524 |
-
├── pages/
|
525 |
-
│ ├── a_page.py
|
526 |
-
│ └── another_page.py
|
527 |
-
└── your_homepage.py
|
528 |
-
```
|
529 |
-
- **Run**: `streamlit run your_homepage.py`
|
530 |
-
|
531 |
-
- **Using `st.Page` and `st.navigation`**: This method offers more flexibility. Define pages using `st.Page` and configure navigation with `st.navigation` in your entrypoint file.
|
532 |
-
- **Example**:
|
533 |
-
```python
|
534 |
-
import streamlit as st
|
535 |
-
pg = st.navigation([st.Page("page_1.py"), st.Page("page_2.py")])
|
536 |
-
pg.run()
|
537 |
-
```
|
538 |
-
|
539 |
-
#### Page Terminology
|
540 |
-
|
541 |
-
- **Page Source**: Python file or callable function.
|
542 |
-
- **Page Label**: Identifies the page in the navigation menu.
|
543 |
-
- **Page Title**: HTML `<title>` element content.
|
544 |
-
- **Page URL Pathname**: Relative path from the root URL.
|
545 |
-
- **Page Icons**: Favicon and icon next to the page label.
|
546 |
-
|
547 |
-
#### Navigation
|
548 |
-
|
549 |
-
- **Default Navigation**: Appears in the sidebar.
|
550 |
-
- **Custom Navigation**: Use `st.page_link` to build a custom menu.
|
551 |
-
- **Programmatic Navigation**: Use `st.switch_page`.
|
552 |
-
|
553 |
-
#### Widget Statefulness
|
554 |
-
|
555 |
-
Widgets reset to default values when switching pages. To maintain state:
|
556 |
-
|
557 |
-
- **Option 1**: Place widgets in the entrypoint file (only works with `st.Page` and `st.navigation`).
|
558 |
-
- **Example**:
|
559 |
-
```python
|
560 |
-
import streamlit as st
|
561 |
-
pg = st.navigation([st.Page("page_1.py"), st.Page("page_2.py")])
|
562 |
-
st.sidebar.selectbox("Group", ["A", "B", "C"], key="group")
|
563 |
-
st.sidebar.slider("Size", 1, 5, key="size")
|
564 |
-
pg.run()
|
565 |
-
```
|
566 |
-
|
567 |
-
- **Option 2**: Use a separate key in `st.session_state` to save widget values.
|
568 |
-
- **Example**:
|
569 |
-
```python
|
570 |
-
import streamlit as st
|
571 |
-
def store_value(key):
|
572 |
-
st.session_state[key] = st.session_state["_" + key]
|
573 |
-
def load_value(key):
|
574 |
-
st.session_state["_" + key] = st.session_state[key]
|
575 |
-
load_value("my_key")
|
576 |
-
st.number_input("Number of filters", key="_my_key", on_change=store_value, args=["my_key"])
|
577 |
-
```
|
578 |
-
|
579 |
-
- **Option 3**: Ensure widget values persist by checking `st.session_state` at the top of each page.
|
580 |
-
- **Example**:
|
581 |
-
```python
|
582 |
-
if "my_key" in st.session_state:
|
583 |
-
st.session_state.my_key = st.session_state.my_key
|
584 |
-
```
|
585 |
-
|
586 |
-
For more details, refer to the [Streamlit documentation](https://docs.streamlit.io/develop/concepts/multipage-apps).
|
587 |
-
|
588 |
-
_forum_
|
589 |
-
|
590 |
-
### Still have questions?
|
591 |
-
|
592 |
-
Our [forums](https://discuss.streamlit.io/) are full of helpful information and Streamlit experts.
|
593 |
-
|
594 |
-
## 6. State Management
|
595 |
-
|
596 |
-
### Framework's Approach to State Management
|
597 |
-
- **Session State**: Streamlit provides a session state API to manage state across reruns of the app.
|
598 |
-
- **Example**:
|
599 |
-
```python
|
600 |
-
if 'count' not in st.session_state:
|
601 |
-
st.session_state.count = 0
|
602 |
-
|
603 |
-
def increment_counter():
|
604 |
-
st.session_state.count += 1
|
605 |
-
|
606 |
-
st.button('Increment', on_click=increment_counter)
|
607 |
-
st.write('Count:', st.session_state.count)
|
608 |
-
```
|
609 |
-
|
610 |
-
## 7. Routing
|
611 |
-
|
612 |
-
### Routing System
|
613 |
-
- Streamlit does not have a traditional routing system like React Router. All navigation is handled within the single-page app.
|
614 |
-
|
615 |
-
## 8. Data Fetching
|
616 |
-
|
617 |
-
### Fetching and Handling Data from APIs
|
618 |
-
- **Example**:
|
619 |
-
```python
|
620 |
-
import requests
|
621 |
-
|
622 |
-
response = requests.get('https://api.example.com/data')
|
623 |
-
data = response.json()
|
624 |
-
st.write(data)
|
625 |
-
```
|
626 |
-
|
627 |
-
### Error Handling and Loading States
|
628 |
-
- **Error Handling**:
|
629 |
-
```python
|
630 |
-
try:
|
631 |
-
response = requests.get('https://api.example.com/data')
|
632 |
-
response.raise_for_status()
|
633 |
-
data = response.json()
|
634 |
-
st.write(data)
|
635 |
-
except requests.exceptions.HTTPError as err:
|
636 |
-
st.error(f'Error fetching data: {err}')
|
637 |
-
```
|
638 |
-
- **Loading States**:
|
639 |
-
```python
|
640 |
-
with st.spinner('Loading...'):
|
641 |
-
response = requests.get('https://api.example.com/data')
|
642 |
-
data = response.json()
|
643 |
-
st.write(data)
|
644 |
-
```
|
645 |
-
|
646 |
-
## 9. Styling
|
647 |
-
|
648 |
-
### Recommended Approaches for Styling Components
|
649 |
-
- **Custom CSS**: Streamlit allows custom CSS for styling.
|
650 |
-
- **Example**:
|
651 |
-
```python
|
652 |
-
st.markdown(
|
653 |
-
"""
|
654 |
-
<style>
|
655 |
-
.stButton > button {
|
656 |
-
color: white;
|
657 |
-
background-color: red;
|
658 |
-
}
|
659 |
-
</style>
|
660 |
-
""",
|
661 |
-
unsafe_allow_html=True
|
662 |
-
)
|
663 |
-
```
|
664 |
-
|
665 |
-
### Implementing Responsive Design
|
666 |
-
- Streamlit provides built-in responsive design features through its layout components (e.g., columns, containers).
|
667 |
-
|
668 |
-
## 10. Performance Optimization
|
669 |
-
|
670 |
-
### Guidelines for Optimizing Performance
|
671 |
-
- **Caching**: Use Streamlit's caching mechanisms to optimize performance.
|
672 |
-
- **Example**:
|
673 |
-
```python
|
674 |
-
@st.cache
|
675 |
-
def fetch_data():
|
676 |
-
response = requests.get('https://api.example.com/data')
|
677 |
-
return response.json()
|
678 |
-
|
679 |
-
data = fetch_data()
|
680 |
-
st.write(data)
|
681 |
-
```
|
682 |
-
|
683 |
-
## 11. Testing
|
684 |
-
|
685 |
-
### Recommended Testing Methodologies
|
686 |
-
- **Unit Testing**: Use Python's unittest or pytest frameworks for unit testing.
|
687 |
-
- **Integration Testing**: Streamlit apps can be tested using Selenium or other browser automation tools.
|
688 |
-
|
689 |
-
## 12. Deployment
|
690 |
-
|
691 |
-
### Building and Deploying Applications
|
692 |
-
- **Streamlit Sharing**: Streamlit provides a free hosting service called Streamlit Sharing.
|
693 |
-
- **Docker**: You can also deploy Streamlit apps using Docker.
|
694 |
-
|
695 |
-
## 13. Best Practices and Common Pitfalls
|
696 |
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
|
|
701 |
|
702 |
-
|
703 |
-
|
704 |
-
|
|
|
|
|
705 |
|
706 |
-
|
707 |
|
708 |
-
|
709 |
-
- **
|
710 |
-
- **
|
711 |
-
- **
|
712 |
|
713 |
-
###
|
714 |
-
- **Streamlit Components**: [Streamlit Components](https://streamlit.io/components)
|
715 |
-
- **Awesome Streamlit**: [Awesome Streamlit](https://awesome-streamlit.org/)
|
716 |
|
717 |
-
|
718 |
-
- **
|
719 |
-
- **
|
720 |
|
721 |
## Conclusion
|
722 |
|
723 |
-
This guideline provides a comprehensive overview of Streamlit
|
|
|
1 |
+
# Streamlit Project Guideline
|
2 |
|
3 |
## 1. Framework Overview
|
4 |
|
5 |
+
Streamlit is an open-source Python library that makes it easy to create and share custom web apps for machine learning and data science. It allows developers to build web applications quickly by writing pure Python scripts. Streamlit's key features include its simplicity, ease of use, and the ability to seamlessly integrate with other data science tools and libraries.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
+
## 2. Component Structure
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
+
### Component Types
|
|
|
10 |
|
11 |
+
In the provided project, the components are primarily function-based, focusing on data processing, generation, and UI interactions. The main types of components identified are:
|
|
|
|
|
12 |
|
13 |
+
- **Data Processing Functions**: Functions like `process_json`, `generate_description_only`, and `analyze_input` handle data processing tasks.
|
14 |
+
- **UI Interaction Functions**: Functions like `example_directly_selected`, `example_from_briefs_selected`, and `example_selected` manage user interactions within the Streamlit UI.
|
15 |
+
- **Session State Management**: Functions and blocks that handle session state, such as initializing session state variables and updating them based on user actions.
|
|
|
|
|
|
|
16 |
|
17 |
+
### Example Components
|
18 |
|
19 |
+
#### Data Processing Function
|
20 |
|
21 |
```python
|
22 |
+
def process_json(input_json, model_name, generating_batch_size, temperature):
|
23 |
+
try:
|
24 |
+
model = ChatOpenAI(
|
25 |
+
model=model_name, temperature=temperature, max_retries=3)
|
26 |
+
generator = TaskDescriptionGenerator(model)
|
27 |
+
result = generator.process(input_json, generating_batch_size)
|
28 |
+
# Processing logic...
|
29 |
+
return description, suggestions, examples_directly, input_analysis, new_example_briefs, examples_from_briefs, examples
|
30 |
+
except Exception as e:
|
31 |
+
st.warning(f"An error occurred: {str(e)}. Returning default values.")
|
32 |
+
return "", [], [], "", [], [], []
|
33 |
```
|
34 |
|
35 |
+
#### UI Interaction Function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
|
37 |
```python
|
38 |
+
def example_directly_selected():
|
39 |
+
if 'selected_example_directly_id' in st.session_state:
|
40 |
+
try:
|
41 |
+
selected_example_ids = st.session_state.selected_example_directly_id[
|
42 |
+
'selection']['rows']
|
43 |
+
# Interaction logic...
|
44 |
+
except Exception as e:
|
45 |
+
st.session_state.selected_example = None
|
46 |
```
|
47 |
|
48 |
+
#### Session State Management
|
|
|
49 |
|
50 |
```python
|
51 |
+
if 'input_data' not in st.session_state:
|
52 |
+
st.session_state.input_data = pd.DataFrame(columns=["Input", "Output"])
|
|
|
53 |
|
54 |
+
if 'description_output_text' not in st.session_state:
|
55 |
+
st.session_state.description_output_text = ''
|
56 |
```
|
57 |
|
58 |
+
## 3. UI Operations and Callbacks
|
|
|
59 |
|
60 |
+
### Common UI Operations
|
|
|
|
|
|
|
|
|
61 |
|
62 |
+
- **Button Clicks**: Handling button clicks to trigger data processing or state updates.
|
63 |
+
- **Data Editing**: Allowing users to edit data tables directly within the UI.
|
64 |
+
- **File Uploads and Downloads**: Managing file uploads for importing data and file downloads for exporting data.
|
65 |
|
66 |
+
### Example UI Operations
|
|
|
|
|
|
|
67 |
|
68 |
+
#### Button Click Handling
|
|
|
69 |
|
70 |
```python
|
71 |
+
submit_button = st.button(
|
72 |
+
"Generate", type="primary", on_click=generate_examples_dataframe)
|
73 |
```
|
74 |
|
75 |
+
#### Data Editing
|
|
|
76 |
|
77 |
```python
|
78 |
+
input_data = st.data_editor(
|
79 |
+
st.session_state.input_data,
|
80 |
+
num_rows="dynamic",
|
81 |
+
use_container_width=True,
|
82 |
+
column_config={
|
83 |
+
"Input": st.column_config.TextColumn("Input", width="large"),
|
84 |
+
"Output": st.column_config.TextColumn("Output", width="large"),
|
85 |
+
},
|
86 |
+
)
|
87 |
```
|
88 |
|
89 |
+
#### File Upload and Download
|
|
|
90 |
|
91 |
```python
|
92 |
+
input_file = st.file_uploader(
|
93 |
+
label="Import Input Data from JSON",
|
94 |
+
type="json",
|
95 |
+
key="input_file",
|
96 |
+
on_change=import_input_data_from_json
|
97 |
+
)
|
98 |
+
|
99 |
+
export_button = st.button(
|
100 |
+
"Export Input Data to JSON", on_click=export_input_data_to_json
|
101 |
+
)
|
102 |
```
|
103 |
|
104 |
+
## 4. State Management
|
105 |
+
|
106 |
+
### State Management Approach
|
107 |
+
|
108 |
+
Streamlit uses a session state to manage the state of the application across reruns. The session state allows developers to persist variables across reruns, enabling more complex interactions and workflows.
|
109 |
+
|
110 |
+
### Example State Management
|
111 |
+
|
112 |
+
#### Initializing Session State
|
113 |
|
114 |
```python
|
115 |
+
if 'input_data' not in st.session_state:
|
116 |
+
st.session_state.input_data = pd.DataFrame(columns=["Input", "Output"])
|
117 |
```
|
118 |
|
119 |
+
#### Updating Session State
|
|
|
120 |
|
121 |
```python
|
122 |
+
def update_description_output_text():
|
123 |
+
input_json = package_input_data()
|
124 |
+
result = generate_description_only(input_json, model_name, temperature)
|
125 |
+
st.session_state.description_output_text = result[0]
|
126 |
+
st.session_state.suggestions = result[1]
|
127 |
```
|
128 |
|
129 |
+
## 5. Routing
|
|
|
130 |
|
131 |
+
Streamlit does not support traditional client-side routing like other frontend frameworks. Instead, it focuses on creating single-page applications where the URL does not change. Navigation within a Streamlit app is typically handled through the sidebar or buttons that trigger reruns of the script.
|
|
|
|
|
132 |
|
133 |
+
## 6. Data Fetching
|
134 |
+
|
135 |
+
### Data Fetching Methods
|
136 |
+
|
137 |
+
Data fetching in Streamlit is often done through direct API calls within the script. The fetched data is then processed and displayed within the app.
|
138 |
|
139 |
+
### Example Data Fetching
|
|
|
140 |
|
141 |
```python
|
142 |
+
def process_json(input_json, model_name, generating_batch_size, temperature):
|
143 |
+
try:
|
144 |
+
model = ChatOpenAI(
|
145 |
+
model=model_name, temperature=temperature, max_retries=3)
|
146 |
+
generator = TaskDescriptionGenerator(model)
|
147 |
+
result = generator.process(input_json, generating_batch_size)
|
148 |
+
# Data processing logic...
|
149 |
+
return description, suggestions, examples_directly, input_analysis, new_example_briefs, examples_from_briefs, examples
|
150 |
+
except Exception as e:
|
151 |
+
st.warning(f"An error occurred: {str(e)}. Returning default values.")
|
152 |
+
return "", [], [], "", [], [], []
|
153 |
```
|
154 |
|
155 |
+
## 7. Styling
|
156 |
|
157 |
+
### Styling Approaches
|
158 |
|
159 |
+
Streamlit provides basic styling options through its API, such as `st.markdown` for custom HTML and CSS, and `st.sidebar` for organizing content. For more advanced styling, custom CSS can be injected using `st.markdown` with HTML tags.
|
|
|
160 |
|
161 |
+
### Example Styling
|
|
|
|
|
|
|
|
|
|
|
162 |
|
163 |
+
```python
|
164 |
+
st.title("LLM Task Example Generator")
|
165 |
+
st.markdown("Enter input-output pairs in the table below to generate a task description, analysis, and additional examples.")
|
166 |
```
|
167 |
|
168 |
+
## 8. Performance Optimization
|
|
|
169 |
|
170 |
+
### Optimization Techniques
|
|
|
|
|
|
|
171 |
|
172 |
+
- **Code Splitting**: Not applicable in Streamlit as it is a single-page application framework.
|
173 |
+
- **Lazy Loading**: Not directly supported; however, conditional rendering can be used to load components only when needed.
|
174 |
+
- **Memoization**: Use Streamlit's `@st.cache` decorator to cache expensive computations.
|
175 |
|
176 |
+
### Example Optimization
|
|
|
177 |
|
178 |
```python
|
179 |
+
@st.cache
|
180 |
+
def process_json(input_json, model_name, generating_batch_size, temperature):
|
181 |
+
# Expensive computation...
|
182 |
+
return result
|
183 |
```
|
184 |
|
185 |
+
## 9. Testing
|
186 |
|
187 |
+
### Testing Methodologies
|
188 |
|
189 |
+
Streamlit applications can be tested using traditional Python testing frameworks like `unittest` and `pytest`. Integration and end-to-end tests can be challenging due to the nature of Streamlit's rerun mechanism.
|
190 |
|
191 |
+
### Example Testing
|
192 |
|
193 |
+
```python
|
194 |
+
import unittest
|
195 |
+
from your_streamlit_app import process_json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
196 |
|
197 |
+
class TestProcessJson(unittest.TestCase):
|
198 |
+
def test_process_json(self):
|
199 |
+
input_json = '{"key": "value"}'
|
200 |
+
result = process_json(input_json, "model_name", 3, 0.5)
|
201 |
+
self.assertEqual(result[0], "expected_description")
|
202 |
|
203 |
+
if __name__ == "__main__":
|
204 |
+
unittest.main()
|
205 |
+
```
|
206 |
+
|
207 |
+
## 10. Best Practices and Common Pitfalls
|
208 |
|
209 |
+
### Best Practices
|
210 |
|
211 |
+
- **Modular Code**: Organize code into reusable functions and modules.
|
212 |
+
- **Session State Management**: Use session state effectively to manage application state.
|
213 |
+
- **Error Handling**: Implement robust error handling to provide a smooth user experience.
|
214 |
+
- **Performance Optimization**: Use caching and efficient data handling to optimize performance.
|
215 |
|
216 |
+
### Common Pitfalls
|
|
|
|
|
217 |
|
218 |
+
- **Overuse of Reruns**: Avoid triggering unnecessary reruns, which can degrade performance.
|
219 |
+
- **Complex State Management**: Be cautious with complex state management, as it can lead to bugs and unexpected behavior.
|
220 |
+
- **Lack of Testing**: Neglecting testing can lead to issues that are hard to debug in a rapidly changing environment.
|
221 |
|
222 |
## Conclusion
|
223 |
|
224 |
+
This guideline provides a comprehensive overview of using Streamlit within a project, covering component structure, UI operations, state management, data fetching, styling, performance optimization, testing, and best practices. By following these guidelines, developers can create efficient, maintainable, and user-friendly Streamlit applications.
|