yaleh commited on
Commit
f7e0aa2
·
1 Parent(s): 7ea8528

Updated UI and guidelines.

Browse files
app/streamlit_meta_prompt.py CHANGED
@@ -466,8 +466,8 @@ if __name__ == "__main__":
466
  st.session_state.initial_system_message = ""
467
  if 'initial_acceptance_criteria' not in st.session_state:
468
  st.session_state.initial_acceptance_criteria = ""
469
- if 'system_message' not in st.session_state:
470
- st.session_state.system_message = ""
471
  if 'output' not in st.session_state:
472
  st.session_state.output = ""
473
  if 'analysis' not in st.session_state:
@@ -485,6 +485,10 @@ if __name__ == "__main__":
485
  if 'acceptance_criteria_output' in st.session_state:
486
  st.session_state.initial_acceptance_criteria = st.session_state.acceptance_criteria_output
487
 
 
 
 
 
488
  if active_model_tab == "Simple":
489
  simple_model_name = simple_model_name_input
490
  advanced_executor_model_name = None
@@ -527,19 +531,35 @@ if __name__ == "__main__":
527
  max_output_age = max_output_age_input
528
  aggressive_exploration = aggressive_exploration_input
529
 
 
 
 
 
 
 
 
 
 
 
530
  col1, col2 = st.columns(2)
531
 
532
  with col1:
533
- user_message = st.text_area("User Message", "").strip()
534
- expected_output = st.text_area("Expected Output", "").strip()
535
- initial_system_message = st.text_area("Initial System Message", st.session_state.initial_system_message).strip()
536
- acceptance_criteria = st.text_area("Acceptance Criteria", st.session_state.initial_acceptance_criteria).strip()
537
 
538
- generate_button_clicked = st.button("Generate", type="primary")
 
 
 
 
539
 
540
  with col2:
541
  if generate_button_clicked:
542
  try:
 
 
 
543
  if active_model_tab == "Simple":
544
  system_message, output, analysis, acceptance_criteria, chat_log = process_message_with_single_llm(
545
  user_message,
@@ -604,10 +624,11 @@ if __name__ == "__main__":
604
  key="system_message_output", height=100)
605
  st.button("Copy System Message", key="copy_system_message",
606
  on_click=copy_system_message)
607
- st.text_area("Output", st.session_state.output, height=100)
608
- st.text_area("Analysis", st.session_state.analysis, height=100)
609
  acceptance_criteria_output = st.text_area(
610
  "Acceptance Criteria", key="acceptance_criteria_output", height=100)
611
  st.button("Copy Acceptance Criteria", key="copy_acceptance_criteria",
612
  on_click=copy_acceptance_criteria)
 
 
 
613
  st.json(st.session_state.chat_log)
 
466
  st.session_state.initial_system_message = ""
467
  if 'initial_acceptance_criteria' not in st.session_state:
468
  st.session_state.initial_acceptance_criteria = ""
469
+ if 'system_message_output' not in st.session_state:
470
+ st.session_state.system_message_output = ""
471
  if 'output' not in st.session_state:
472
  st.session_state.output = ""
473
  if 'analysis' not in st.session_state:
 
485
  if 'acceptance_criteria_output' in st.session_state:
486
  st.session_state.initial_acceptance_criteria = st.session_state.acceptance_criteria_output
487
 
488
+ def clear_session_state():
489
+ for key in st.session_state.keys():
490
+ del st.session_state[key]
491
+
492
  if active_model_tab == "Simple":
493
  simple_model_name = simple_model_name_input
494
  advanced_executor_model_name = None
 
531
  max_output_age = max_output_age_input
532
  aggressive_exploration = aggressive_exploration_input
533
 
534
+ data_editor_data = st.data_editor(
535
+ [{"user_message": "", "expected_output": ""}],
536
+ column_config={
537
+ "user_message": st.column_config.TextColumn("User Message"),
538
+ "expected_output": st.column_config.TextColumn("Expected Output"),
539
+ },
540
+ hide_index=True,
541
+ use_container_width=True,
542
+ )
543
+
544
  col1, col2 = st.columns(2)
545
 
546
  with col1:
547
+ with st.expander("Advanced Inputs"):
548
+ initial_system_message = st.text_area("Initial System Message", st.session_state.initial_system_message).strip()
549
+ acceptance_criteria = st.text_area("Acceptance Criteria", st.session_state.initial_acceptance_criteria).strip()
 
550
 
551
+ col1_1, col1_2 = st.columns(2)
552
+ with col1_1:
553
+ generate_button_clicked = st.button("Generate", type="primary")
554
+ with col1_2:
555
+ clear_button_clicked = st.button("Clear", on_click=clear_session_state)
556
 
557
  with col2:
558
  if generate_button_clicked:
559
  try:
560
+ user_message = data_editor_data[0]["user_message"].strip()
561
+ expected_output = data_editor_data[0]["expected_output"].strip()
562
+
563
  if active_model_tab == "Simple":
564
  system_message, output, analysis, acceptance_criteria, chat_log = process_message_with_single_llm(
565
  user_message,
 
624
  key="system_message_output", height=100)
625
  st.button("Copy System Message", key="copy_system_message",
626
  on_click=copy_system_message)
 
 
627
  acceptance_criteria_output = st.text_area(
628
  "Acceptance Criteria", key="acceptance_criteria_output", height=100)
629
  st.button("Copy Acceptance Criteria", key="copy_acceptance_criteria",
630
  on_click=copy_acceptance_criteria)
631
+ st.text_area("Output", st.session_state.output, height=100)
632
+ st.text_area("Analysis", st.session_state.analysis, height=100)
633
+
634
  st.json(st.session_state.chat_log)
guidelines/gradio.md CHANGED
@@ -1,29 +1,255 @@
1
- # Gradio Development Guidelines
2
-
3
- ## Best Practices
4
-
5
- - Use `gr.Blocks` to create a structured UI layout with rows, columns, tabs, and accordions.
6
- - Organize related UI elements into groups using `gr.Group` for better readability and maintainability.
7
- - Provide clear labels and instructions for user inputs and interactions using `gr.Markdown` and `gr.Textbox`.
8
- - Use `gr.Dropdown` to allow users to select from a predefined list of options.
9
- - Implement buttons with `gr.Button` and assign appropriate callbacks using the `click` event.
10
- - Use `gr.Examples` to provide sample inputs for users to quickly test the app's functionality.
11
- - Handle file uploads and downloads using `gr.FileUpload` and `gr.FileDownload`.
12
- - Display output using appropriate components like `gr.Textbox`, `gr.Chatbot`, `gr.Dataframe`, etc.
13
- - Implement flagging functionality to allow users to report issues or provide feedback.
14
- - Use `gr.Accordion` to hide detailed information that may not be necessary for all users.
15
- - Provide a clear and concise title for the app using the `title` parameter in `gr.Blocks`.
16
- - Use `gr.ClearButton` to allow users to reset input fields and start over.
17
-
18
- ## Principles
19
-
20
- - Prioritize usability and user experience in the app's design and layout.
21
- - Ensure the app is responsive and works well on different screen sizes and devices.
22
- - Optimize performance by minimizing unnecessary computations and caching results when possible.
23
- - Follow PEP 8 style guidelines for Python code.
24
- - Document the app's purpose, usage instructions, and code to enhance maintainability.
25
- - Test the app thoroughly to identify and fix bugs, edge cases, and performance issues.
26
- - Consider accessibility and ensure the app can be used by people with different abilities.
27
- - Provide clear feedback to users about the app's status and results.
28
- - Allow users to customize the app's behavior through settings and options.
29
- - Design the app to be modular and extensible, allowing for future enhancements and new features.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Gradio Framework Guideline
2
+
3
+ ## 1. Framework Overview
4
+ Gradio is a Python library that allows you to quickly create web interfaces for machine learning models, APIs, and other data science projects. It provides a simple way to build interactive demos and prototypes without requiring extensive web development knowledge.
5
+
6
+ Key features of Gradio include:
7
+ - Easy creation of user interfaces for machine learning models
8
+ - Automatic generation of input and output components based on function signatures
9
+ - Built-in support for various data types, such as text, image, audio, and video
10
+ - Customizable layout and styling options
11
+ - Sharing and collaboration features for showcasing your work
12
+
13
+ ## 2. Installation and Setup
14
+ To install Gradio, you can use pip, the Python package installer. Open a terminal and run the following command:
15
+
16
+ ```
17
+ pip install gradio
18
+ ```
19
+
20
+ To set up a new project using Gradio, create a new Python file and import the gradio library:
21
+
22
+ ```python
23
+ import gradio as gr
24
+ ```
25
+
26
+ ## 3. Core Concepts
27
+ Gradio revolves around the concept of creating "interfaces" for your functions or machine learning models. An interface is a web page that allows users to interact with your code by providing inputs and receiving outputs.
28
+
29
+ The core components of a Gradio interface are:
30
+ - Input components: Widgets that allow users to provide input data, such as text boxes, file uploads, or dropdown menus.
31
+ - Output components: Elements that display the results of your function or model, such as text, images, or plots.
32
+ - Function or model: The Python function or machine learning model that takes the input data, processes it, and returns the output data.
33
+
34
+ ## 4. Component Structure
35
+ Gradio provides various components that you can use to build your interface. Here are some commonly used components:
36
+
37
+ - `gr.Textbox`: A text input component that allows users to enter single-line or multi-line text.
38
+ - Example: `user_message_input = gr.Textbox(label="User Message", show_copy_button=True)`
39
+ - `gr.Number`: A numeric input component that allows users to enter numbers with specified precision, minimum, maximum, and step values.
40
+ - Example: `recursion_limit_input = gr.Number(label="Recursion Limit", value=config.recursion_limit, precision=0, minimum=1, maximum=config.recursion_limit_max, step=1)`
41
+ - `gr.Dropdown`: A dropdown component that allows users to select an option from a list of choices.
42
+ - Example: `simple_model_name_input = gr.Dropdown(label="Model Name", choices=config.llms.keys(), value=list(config.llms.keys())[0])`
43
+ - `gr.Checkbox`: A checkbox component that allows users to toggle a boolean value.
44
+ - Example: `aggressive_exploration = gr.Checkbox(label="Aggressive Exploration", value=config.aggressive_exploration)`
45
+ - `gr.Button`: A button component that triggers an event when clicked.
46
+ - Example: `simple_submit_button = gr.Button(value="Submit", variant="primary")`
47
+ - `gr.ClearButton`: A button component that clears the specified components when clicked.
48
+ - Example: `simple_clear_button = gr.ClearButton([user_message_input, expected_output_input, acceptance_criteria_input, initial_system_message_input], value='Clear All')`
49
+ - `gr.Chatbot`: A chatbot component that displays a conversation-like interface with bubbles for messages.
50
+ - Example: `logs_chatbot = gr.Chatbot(label='Messages', show_copy_button=True, layout='bubble', bubble_full_width=False, render_markdown=False)`
51
+ - `gr.Accordion`: A component that allows you to group other components within an accordion-style collapsible section.
52
+ - Example:
53
+ ```python
54
+ with gr.Accordion("Initial System Message & Acceptance Criteria", open=False):
55
+ # Components inside the accordion
56
+ ```
57
+
58
+ ## 5. UI Operations and Callbacks
59
+ Gradio allows you to define callbacks and event handlers to respond to user interactions and perform actions. Here are some common UI operation scenarios and how to handle them:
60
+
61
+ 1. Button Click Events:
62
+ - Use the `click()` method on a button component to specify the function to be called when the button is clicked.
63
+ - Example: `generate_acceptance_criteria_button.click(generate_acceptance_criteria, inputs=[...], outputs=[...])`
64
+
65
+ 2. Tab Selection Events:
66
+ - Use the `select()` method on a tab component to specify the function to be called when the tab is selected.
67
+ - Example: `simple_llm_tab.select(on_model_tab_select)`
68
+
69
+ 3. Flagging and Saving Data:
70
+ - Use the `FlagMethod` class to define a flagging callback that saves data when a flag button is clicked.
71
+ - Example: `flag_method = FlagMethod(flagging_callback, "Flag", "")`
72
+ - Attach the flagging callback to the flag button using the `click()` method.
73
+ - Example: `flag_button.click(flag_method, inputs=flagging_inputs, outputs=flag_button, preprocess=False, queue=False, show_api=False)`
74
+
75
+ 4. Clearing Components:
76
+ - Use the `ClearButton` component to clear specified components when clicked.
77
+ - Example: `clear_logs_button = gr.ClearButton([logs_chatbot], value='Clear Logs')`
78
+
79
+ 5. Loading Examples:
80
+ - Use the `gr.Examples` component to load examples from a file and populate the specified input components.
81
+ - Example: `examples = gr.Examples(config.examples_path, inputs=[...])`
82
+
83
+ ## 6. State Management
84
+ Gradio provides a way to manage the state of your interface across multiple function calls. You can use the `gr.State()` component to store and pass data between functions.
85
+
86
+ Here's an example of using state management in Gradio:
87
+
88
+ ```python
89
+ import gradio as gr
90
+
91
+ def update_count(count):
92
+ return count + 1
93
+
94
+ count_state = gr.State(0)
95
+
96
+ iface = gr.Interface(fn=update_count, inputs=count_state, outputs=count_state)
97
+ iface.launch()
98
+ ```
99
+
100
+ In this example, we define an `update_count` function that takes a count as input and increments it by 1. We create a Gradio interface with a `gr.State()` component initialized with a value of 0. The `update_count` function is called each time the interface is used, updating the count state.
101
+
102
+ ## 7. Routing
103
+ Gradio supports creating multi-page interfaces using the `gr.Blocks()` class. You can define multiple pages and navigate between them using buttons or links.
104
+
105
+ Here's an example of creating a multi-page interface with Gradio:
106
+
107
+ ```python
108
+ import gradio as gr
109
+
110
+ with gr.Blocks() as demo:
111
+ with gr.Tab("Page 1"):
112
+ # Components for page 1
113
+ pass
114
+ with gr.Tab("Page 2"):
115
+ # Components for page 2
116
+ pass
117
+
118
+ demo.launch()
119
+ ```
120
+
121
+ In this example, we create a Gradio interface using `gr.Blocks()` and define two tabs using `gr.Tab()`. Each tab represents a separate page in the interface, and you can add components specific to each page.
122
+
123
+ ## 8. Data Fetching
124
+ Gradio allows you to fetch data from external sources, such as APIs or databases, and use it in your interface. You can use the `gr.inputs.Textbox()` component to accept user input and pass it to a function that fetches the data.
125
+
126
+ Here's an example of fetching data from an API using Gradio:
127
+
128
+ ```python
129
+ import gradio as gr
130
+ import requests
131
+
132
+ def get_data(query):
133
+ response = requests.get(f"https://api.example.com/data?query={query}")
134
+ return response.json()
135
+
136
+ iface = gr.Interface(fn=get_data, inputs="text", outputs="json")
137
+ iface.launch()
138
+ ```
139
+
140
+ In this example, we define a `get_data` function that takes a query as input, makes a GET request to an API endpoint, and returns the response data as JSON. We create a Gradio interface with a text input component and a JSON output component.
141
+
142
+ ## 9. Styling
143
+ Gradio provides options to customize the styling of your interface. You can use CSS classes and inline styles to modify the appearance of components.
144
+
145
+ Here's an example of styling components in Gradio:
146
+
147
+ ```python
148
+ import gradio as gr
149
+
150
+ iface = gr.Interface(
151
+ fn=lambda x: x,
152
+ inputs=gr.inputs.Textbox(lines=5, label="Enter text"),
153
+ outputs="text",
154
+ title="Text Analysis",
155
+ description="Enter text to analyze its sentiment.",
156
+ css=".gradio-container {background-color: #f0f0f0;}",
157
+ )
158
+ iface.launch()
159
+ ```
160
+
161
+ In this example, we create a Gradio interface with a text input component and a text output component. We customize the styling by providing a CSS class `.gradio-container` to set the background color of the interface container.
162
+
163
+ ## 10. Performance Optimization
164
+ To optimize the performance of your Gradio interface, you can consider the following techniques:
165
+ - Minimize the number of input and output components to reduce the amount of data transferred between the client and server.
166
+ - Use caching to store and reuse the results of expensive computations.
167
+ - Implement pagination or lazy loading for large datasets to load data incrementally.
168
+ - Utilize asynchronous processing for time-consuming tasks to keep the interface responsive.
169
+
170
+ Here's an example of using caching in Gradio:
171
+
172
+ ```python
173
+ import gradio as gr
174
+
175
+ @gr.cache()
176
+ def expensive_computation(x):
177
+ # Perform expensive computation
178
+ return result
179
+
180
+ iface = gr.Interface(fn=expensive_computation, inputs="text", outputs="text")
181
+ iface.launch()
182
+ ```
183
+
184
+ In this example, we define an `expensive_computation` function and decorate it with `@gr.cache()` to enable caching. Gradio will store the results of the function for each unique input and reuse them when the same input is provided again, avoiding redundant computations.
185
+
186
+ ## 11. Testing
187
+ Gradio provides a way to write unit tests for your interfaces using the `gr.test()` function. You can define test cases with input data and expected output data to verify the correctness of your functions or models.
188
+
189
+ Here's an example of writing tests for a Gradio interface:
190
+
191
+ ```python
192
+ import gradio as gr
193
+
194
+ def greet(name):
195
+ return f"Hello, {name}!"
196
+
197
+ iface = gr.Interface(fn=greet, inputs="text", outputs="text")
198
+
199
+ tests = [
200
+ {"input": "Alice", "output": "Hello, Alice!"},
201
+ {"input": "Bob", "output": "Hello, Bob!"},
202
+ ]
203
+
204
+ gr.test iface, tests
205
+ ```
206
+
207
+ In this example, we define a `greet` function and create a Gradio interface. We then define a list of test cases, each specifying an input value and the expected output value. Finally, we use `gr.test()` to run the tests and verify that the interface produces the expected outputs for the given inputs.
208
+
209
+ ## 12. Deployment
210
+ Gradio interfaces can be easily deployed to various platforms, such as Hugging Face Spaces, Heroku, or your own server. Gradio provides built-in support for deploying interfaces to Hugging Face Spaces.
211
+
212
+ Here's an example of deploying a Gradio interface to Hugging Face Spaces:
213
+
214
+ ```python
215
+ import gradio as gr
216
+
217
+ def greet(name):
218
+ return f"Hello, {name}!"
219
+
220
+ iface = gr.Interface(fn=greet, inputs="text", outputs="text")
221
+
222
+ iface.launch(share=True)
223
+ ```
224
+
225
+ In this example, we create a Gradio interface and call `iface.launch(share=True)` to deploy the interface to Hugging Face Spaces. Gradio will generate a unique URL for your interface, allowing others to access and interact with it.
226
+
227
+ ## 13. Best Practices and Common Pitfalls
228
+ When using Gradio, consider the following best practices and common pitfalls:
229
+ - Keep your interface simple and intuitive for users to understand and use.
230
+ - Provide clear instructions and examples to guide users on how to interact with your interface.
231
+ - Validate and sanitize user inputs to prevent unexpected behavior or security vulnerabilities.
232
+ - Handle errors gracefully and provide informative error messages to users.
233
+ - Optimize the performance of your interface by minimizing the number of components and using caching when appropriate.
234
+ - Test your interface thoroughly with various inputs and edge cases to ensure its robustness.
235
+
236
+ Common pitfalls to avoid:
237
+ - Overloading the interface with too many components or complex layouts, leading to a confusing user experience.
238
+ - Failing to handle edge cases or unexpected inputs, resulting in errors or incorrect outputs.
239
+ - Neglecting to secure your interface against potential security risks, such as unauthorized access or malicious inputs.
240
+ - Forgetting to optimize the performance of your interface, leading to slow response times or resource exhaustion.
241
+
242
+ ## 14. Community and Resources
243
+ Gradio has a vibrant community and provides various resources to help you get started and learn more about the framework. Here are some useful links:
244
+ - Gradio Documentation: https://gradio.app/docs/
245
+ - Gradio GitHub Repository: https://github.com/gradio-app/gradio
246
+ - Gradio Examples: https://gradio.app/examples/
247
+ - Gradio Community Forum: https://discuss.huggingface.co/c/gradio/33
248
+ - Gradio Twitter: https://twitter.com/gradio
249
+
250
+ These resources provide documentation, examples, and a platform to engage with the Gradio community, ask questions, and share your projects.
251
+
252
+ Remember to refer to the Gradio documentation for the most up-to-date information and advanced usage scenarios.
253
+
254
+ Happy building with Gradio!
255
+
guidelines/streamlit.md CHANGED
@@ -1,30 +1,643 @@
1
- # Streamlit Development Guidelines
2
-
3
- ## Best Practices
4
-
5
- - Use `st.session_state` to store and share data across the app, such as input data, output results, and UI state.
6
- - Organize code into functions for better readability and maintainability.
7
- - Use `st.expander` to group related UI elements and allow users to collapse/expand sections.
8
- - Provide options for users to import/export data, such as using `st.file_uploader` and `st.download_button`.
9
- - Use `st.columns` to create responsive layouts and align UI elements.
10
- - Provide clear labels and instructions for user inputs and interactions.
11
- - Handle exceptions and display user-friendly error messages using `st.warning`.
12
- - Use `st.spinner` to indicate when long-running operations are in progress.
13
- - Allow users to customize and control the app's behavior through widgets like `st.slider`, `st.selectbox`, etc.
14
- - Use `st.dataframe` to display interactive tables, with features like row selection.
15
- - Implement callbacks using `on_click` or `on_change` to respond to user interactions.
16
- - Use `st.sidebar` to display additional information or controls without cluttering the main UI.
17
- - Organize the app's UI elements in a logical order, grouping related functionality together.
18
-
19
- ## Principles
20
-
21
- - Prioritize usability and user experience in the app's design and layout.
22
- - Ensure the app is responsive and works well on different screen sizes.
23
- - Optimize performance by minimizing unnecessary computations and caching results when possible.
24
- - Follow PEP 8 style guidelines for Python code.
25
- - Document the app's purpose, usage instructions, and code to enhance maintainability.
26
- - Test the app thoroughly to identify and fix bugs, edge cases, and performance issues.
27
- - Consider accessibility and ensure the app can be used by people with different abilities.
28
- - Provide clear feedback to users about the app's status and results.
29
- - Allow users to customize the app's behavior through settings and options.
30
- - Design the app to be modular and extensible, allowing for future enhancements and new features.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Streamlit Guideline
2
+
3
+ ## 1. Framework Overview
4
+
5
+ ### Introduction to Streamlit
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
+ ```python
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
+ #### Stateful Components
341
+ Stateful components involve user interaction and can change based on user input.
342
+
343
+ ```python
344
+ if 'count' not in st.session_state:
345
+ st.session_state.count = 0
346
+
347
+ def increment_counter():
348
+ st.session_state.count += 1
349
+
350
+ st.button('Increment', on_click=increment_counter)
351
+ st.write('Count:', st.session_state.count)
352
+ ```
353
+
354
+ ### Lifecycle Methods or Hooks
355
+
356
+ Streamlit does not have traditional lifecycle methods like React, but you can use callbacks and session state to manage component behavior.
357
+
358
+ ```python
359
+ if 'count' not in st.session_state:
360
+ st.session_state.count = 0
361
+
362
+ def increment_counter():
363
+ st.session_state.count += 1
364
+
365
+ st.button('Increment', on_click=increment_counter)
366
+ st.write('Count:', st.session_state.count)
367
+ ```
368
+
369
+ ## 5. UI Operations and Callbacks
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
+ if st.button('Click Me'):
380
+ st.write('Button Clicked!')
381
+ ```
382
+
383
+ #### Form Submissions
384
+ Forms are used to group related inputs and can be submitted together.
385
+
386
+ ```python
387
+ with st.form(key='my_form'):
388
+ text_input = st.text_input(label='Enter some text')
389
+ submit_button = st.form_submit_button(label='Submit')
390
+
391
+ if submit_button:
392
+ st.write(f'You entered: {text_input}')
393
+ ```
394
+
395
+ #### Checkboxes
396
+ Checkboxes are used to capture boolean inputs.
397
+
398
+ ```python
399
+ agree = st.checkbox("I agree")
400
+ if agree:
401
+ st.write("Great! You agreed.")
402
+ ```
403
+
404
+ #### Radio Buttons
405
+ Radio buttons allow users to select one option from a set.
406
+
407
+ ```python
408
+ option = st.radio("Choose an option", ["Option 1", "Option 2"])
409
+ st.write("You selected:", option)
410
+ ```
411
+
412
+ #### Select Boxes
413
+ Select boxes allow users to select one option from a dropdown.
414
+
415
+ ```python
416
+ choice = st.selectbox("Select an option", ["A", "B", "C"])
417
+ st.write("You selected:", choice)
418
+ ```
419
+
420
+ #### Multiselect Boxes
421
+ Multiselect boxes allow users to select multiple options.
422
+
423
+ ```python
424
+ multi_choices = st.multiselect("Choose multiple options", ["X", "Y", "Z"])
425
+ st.write("You selected:", multi_choices)
426
+ ```
427
+
428
+ #### Sliders
429
+ Sliders allow users to select a value from a range.
430
+
431
+ ```python
432
+ value = st.slider("Select a value", 0, 100, 50)
433
+ st.write("You selected:", value)
434
+ ```
435
+
436
+ #### Text Inputs
437
+ Text inputs allow users to enter text.
438
+
439
+ ```python
440
+ text = st.text_input("Enter some text")
441
+ st.write("You entered:", text)
442
+ ```
443
+
444
+ #### Number Inputs
445
+ Number inputs allow users to enter numeric values.
446
+
447
+ ```python
448
+ number = st.number_input("Enter a number")
449
+ st.write("You entered:", number)
450
+ ```
451
+
452
+ #### Date and Time Inputs
453
+ Date and time inputs allow users to select dates and times.
454
+
455
+ ```python
456
+ date = st.date_input("Select a date")
457
+ st.write("You selected:", date)
458
+
459
+ time = st.time_input("Select a time")
460
+ st.write("You selected:", time)
461
+ ```
462
+
463
+ #### File Uploaders
464
+ File uploaders allow users to upload files.
465
+
466
+ ```python
467
+ file = st.file_uploader("Upload a file")
468
+ if file is not None:
469
+ st.write("File uploaded:", file.name)
470
+ ```
471
+
472
+ ### Implementing and Using Callbacks
473
+
474
+ Callbacks are functions that are called when a specific event occurs, such as a button click or form submission. Streamlit allows you to define callbacks using the `on_click` and `on_change` parameters.
475
+
476
+ #### Callbacks with Session State
477
+ Callbacks can be used to update the session state, allowing you to manage state across reruns of the app.
478
+
479
+ ```python
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
+ st.button('Increment', on_click=increment_counter)
487
+ st.write('Count:', st.session_state.count)
488
+ ```
489
+
490
+ #### Callbacks with Forms
491
+ Callbacks can also be used with forms to handle form submissions.
492
+
493
+ ```python
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
+ if submit_button:
499
+ st.write(f'You entered: {text_input}')
500
+ ```
501
+
502
+ #### Callbacks with Widgets
503
+ Callbacks can be used with various widgets to handle user interactions.
504
+
505
+ ```python
506
+ def on_change():
507
+ st.write(f'Value changed to: {st.session_state.slider_value}')
508
+
509
+ st.slider('Select a value', 0, 100, key='slider_value', on_change=on_change)
510
+ ```
511
+
512
+ By leveraging these components and callbacks, you can create interactive and dynamic Streamlit applications that respond to user inputs and actions.
513
+
514
+ ## 6. State Management
515
+
516
+ ### Framework's Approach to State Management
517
+ - **Session State**: Streamlit provides a session state API to manage state across reruns of the app.
518
+ - **Example**:
519
+ ```python
520
+ if 'count' not in st.session_state:
521
+ st.session_state.count = 0
522
+
523
+ def increment_counter():
524
+ st.session_state.count += 1
525
+
526
+ st.button('Increment', on_click=increment_counter)
527
+ st.write('Count:', st.session_state.count)
528
+ ```
529
+
530
+ ## 7. Routing
531
+
532
+ ### Routing System
533
+ - Streamlit does not have a traditional routing system like React Router. All navigation is handled within the single-page app.
534
+
535
+ ## 8. Data Fetching
536
+
537
+ ### Fetching and Handling Data from APIs
538
+ - **Example**:
539
+ ```python
540
+ import requests
541
+
542
+ response = requests.get('https://api.example.com/data')
543
+ data = response.json()
544
+ st.write(data)
545
+ ```
546
+
547
+ ### Error Handling and Loading States
548
+ - **Error Handling**:
549
+ ```python
550
+ try:
551
+ response = requests.get('https://api.example.com/data')
552
+ response.raise_for_status()
553
+ data = response.json()
554
+ st.write(data)
555
+ except requests.exceptions.HTTPError as err:
556
+ st.error(f'Error fetching data: {err}')
557
+ ```
558
+ - **Loading States**:
559
+ ```python
560
+ with st.spinner('Loading...'):
561
+ response = requests.get('https://api.example.com/data')
562
+ data = response.json()
563
+ st.write(data)
564
+ ```
565
+
566
+ ## 9. Styling
567
+
568
+ ### Recommended Approaches for Styling Components
569
+ - **Custom CSS**: Streamlit allows custom CSS for styling.
570
+ - **Example**:
571
+ ```python
572
+ st.markdown(
573
+ """
574
+ <style>
575
+ .stButton > button {
576
+ color: white;
577
+ background-color: red;
578
+ }
579
+ </style>
580
+ """,
581
+ unsafe_allow_html=True
582
+ )
583
+ ```
584
+
585
+ ### Implementing Responsive Design
586
+ - Streamlit provides built-in responsive design features through its layout components (e.g., columns, containers).
587
+
588
+ ## 10. Performance Optimization
589
+
590
+ ### Guidelines for Optimizing Performance
591
+ - **Caching**: Use Streamlit's caching mechanisms to optimize performance.
592
+ - **Example**:
593
+ ```python
594
+ @st.cache
595
+ def fetch_data():
596
+ response = requests.get('https://api.example.com/data')
597
+ return response.json()
598
+
599
+ data = fetch_data()
600
+ st.write(data)
601
+ ```
602
+
603
+ ## 11. Testing
604
+
605
+ ### Recommended Testing Methodologies
606
+ - **Unit Testing**: Use Python's unittest or pytest frameworks for unit testing.
607
+ - **Integration Testing**: Streamlit apps can be tested using Selenium or other browser automation tools.
608
+
609
+ ## 12. Deployment
610
+
611
+ ### Building and Deploying Applications
612
+ - **Streamlit Sharing**: Streamlit provides a free hosting service called Streamlit Sharing.
613
+ - **Docker**: You can also deploy Streamlit apps using Docker.
614
+
615
+ ## 13. Best Practices and Common Pitfalls
616
+
617
+ ### Best Practices
618
+ - **Modular Code**: Organize your code into modular functions and files.
619
+ - **Consistent Styling**: Use custom CSS for consistent styling across the app.
620
+ - **Error Handling**: Implement robust error handling for data fetching and user inputs.
621
+
622
+ ### Common Pitfalls
623
+ - **Overusing Session State**: Avoid overusing session state for simple state management.
624
+ - **Performance Issues**: Be mindful of performance issues, especially with large datasets.
625
+
626
+ ## 14. Community and Resources
627
+
628
+ ### Links to Official Documentation, Community Forums, and Helpful Resources
629
+ - **Official Documentation**: [Streamlit Documentation](https://docs.streamlit.io/)
630
+ - **Community Forum**: [Streamlit Forum](https://discuss.streamlit.io/)
631
+ - **GitHub Repository**: [Streamlit GitHub](https://github.com/streamlit/streamlit)
632
+
633
+ ### Popular Tools, Extensions, and Libraries
634
+ - **Streamlit Components**: [Streamlit Components](https://streamlit.io/components)
635
+ - **Awesome Streamlit**: [Awesome Streamlit](https://awesome-streamlit.org/)
636
+
637
+ ### Notable Community Projects
638
+ - **Streamlit Gallery**: [Streamlit Gallery](https://streamlit.io/gallery)
639
+ - **Streamlit Cheat Sheet**: [Streamlit Cheat Sheet](https://share.streamlit.io/daniellewisdl/streamlit-cheat-sheet/app.py)
640
+
641
+ ## Conclusion
642
+
643
+ This guideline provides a comprehensive overview of Streamlit, covering its installation, core concepts, component structure, UI operations, state management, data fetching, styling, performance optimization, testing, deployment, best practices, and community resources. By following this guide, developers can effectively utilize Streamlit to create efficient and interactive web applications for data science and machine learning projects.