vishmay007 commited on
Commit
095fd88
·
verified ·
1 Parent(s): 689dfd4

Upload folder using huggingface_hub (part 15)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +6 -0
  2. venv/Lib/site-packages/streamlit-1.60.0.dist-info/INSTALLER +1 -0
  3. venv/Lib/site-packages/streamlit-1.60.0.dist-info/METADATA +224 -0
  4. venv/Lib/site-packages/streamlit-1.60.0.dist-info/RECORD +0 -0
  5. venv/Lib/site-packages/streamlit-1.60.0.dist-info/REQUESTED +0 -0
  6. venv/Lib/site-packages/streamlit-1.60.0.dist-info/WHEEL +5 -0
  7. venv/Lib/site-packages/streamlit-1.60.0.dist-info/entry_points.txt +2 -0
  8. venv/Lib/site-packages/streamlit-1.60.0.dist-info/top_level.txt +1 -0
  9. venv/Lib/site-packages/streamlit/runtime/memory_uploaded_file_manager.py +177 -0
  10. venv/Lib/site-packages/streamlit/runtime/metrics_util.py +661 -0
  11. venv/Lib/site-packages/streamlit/runtime/outside_container_wrapper.py +46 -0
  12. venv/Lib/site-packages/streamlit/runtime/pages_manager.py +214 -0
  13. venv/Lib/site-packages/streamlit/runtime/parallel_coordinator.py +241 -0
  14. venv/Lib/site-packages/streamlit/runtime/runtime.py +788 -0
  15. venv/Lib/site-packages/streamlit/runtime/runtime_util.py +166 -0
  16. venv/Lib/site-packages/streamlit/runtime/script_data.py +46 -0
  17. venv/Lib/site-packages/streamlit/runtime/scriptrunner/__init__.py +38 -0
  18. venv/Lib/site-packages/streamlit/runtime/scriptrunner/__pycache__/__init__.cpython-314.pyc +0 -0
  19. venv/Lib/site-packages/streamlit/runtime/scriptrunner/__pycache__/exec_code.cpython-314.pyc +0 -0
  20. venv/Lib/site-packages/streamlit/runtime/scriptrunner/__pycache__/magic.cpython-314.pyc +0 -0
  21. venv/Lib/site-packages/streamlit/runtime/scriptrunner/__pycache__/magic_funcs.cpython-314.pyc +0 -0
  22. venv/Lib/site-packages/streamlit/runtime/scriptrunner/__pycache__/script_cache.cpython-314.pyc +0 -0
  23. venv/Lib/site-packages/streamlit/runtime/scriptrunner/__pycache__/script_runner.cpython-314.pyc +0 -0
  24. venv/Lib/site-packages/streamlit/runtime/scriptrunner/exec_code.py +167 -0
  25. venv/Lib/site-packages/streamlit/runtime/scriptrunner/magic.py +277 -0
  26. venv/Lib/site-packages/streamlit/runtime/scriptrunner/magic_funcs.py +32 -0
  27. venv/Lib/site-packages/streamlit/runtime/scriptrunner/script_cache.py +89 -0
  28. venv/Lib/site-packages/streamlit/runtime/scriptrunner/script_runner.py +937 -0
  29. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__init__.py +19 -0
  30. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/__init__.cpython-314.pyc +0 -0
  31. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/exceptions.cpython-314.pyc +0 -0
  32. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/script_requests.cpython-314.pyc +0 -0
  33. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/script_run_context.cpython-314.pyc +0 -0
  34. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/script_run_context_attr.cpython-314.pyc +0 -0
  35. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/shared_run_state.cpython-314.pyc +0 -0
  36. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/thread_safe_set.cpython-314.pyc +0 -0
  37. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/exceptions.py +44 -0
  38. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/script_requests.py +311 -0
  39. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/script_run_context.py +463 -0
  40. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/script_run_context_attr.py +25 -0
  41. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/shared_run_state.py +86 -0
  42. venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/thread_safe_set.py +69 -0
  43. venv/Lib/site-packages/streamlit/runtime/secrets.py +652 -0
  44. venv/Lib/site-packages/streamlit/runtime/session_manager.py +438 -0
  45. venv/Lib/site-packages/streamlit/runtime/state/__init__.py +49 -0
  46. venv/Lib/site-packages/streamlit/runtime/state/__pycache__/__init__.cpython-314.pyc +0 -0
  47. venv/Lib/site-packages/streamlit/runtime/state/__pycache__/common.cpython-314.pyc +0 -0
  48. venv/Lib/site-packages/streamlit/runtime/state/__pycache__/presentation.cpython-314.pyc +0 -0
  49. venv/Lib/site-packages/streamlit/runtime/state/__pycache__/query_params.cpython-314.pyc +0 -0
  50. venv/Lib/site-packages/streamlit/runtime/state/__pycache__/query_params_proxy.cpython-314.pyc +0 -0
.gitattributes CHANGED
@@ -268,3 +268,9 @@ venv/Lib/site-packages/rpds/rpds.cp314-win_amd64.pyd filter=lfs diff=lfs merge=l
268
  venv/Lib/site-packages/streamlit/__pycache__/emojis.cpython-314.pyc filter=lfs diff=lfs merge=lfs -text
269
  venv/Lib/site-packages/streamlit/__pycache__/material_icon_names.cpython-314.pyc filter=lfs diff=lfs merge=lfs -text
270
  venv/Lib/site-packages/streamlit/elements/lib/__pycache__/column_types.cpython-314.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
268
  venv/Lib/site-packages/streamlit/__pycache__/emojis.cpython-314.pyc filter=lfs diff=lfs merge=lfs -text
269
  venv/Lib/site-packages/streamlit/__pycache__/material_icon_names.cpython-314.pyc filter=lfs diff=lfs merge=lfs -text
270
  venv/Lib/site-packages/streamlit/elements/lib/__pycache__/column_types.cpython-314.pyc filter=lfs diff=lfs merge=lfs -text
271
+ venv/Lib/site-packages/streamlit/static/static/media/MaterialSymbols-Rounded.1hm6dVzH.woff2 filter=lfs diff=lfs merge=lfs -text
272
+ venv/Lib/site-packages/streamlit/static/static/media/SourceSansVF-Italic.ttf.Bt9VkdQ3.woff2 filter=lfs diff=lfs merge=lfs -text
273
+ venv/Lib/site-packages/streamlit/static/static/media/SourceSansVF-Upright.ttf.BsWL4Kly.woff2 filter=lfs diff=lfs merge=lfs -text
274
+ venv/Lib/site-packages/streamlit/static/static/media/SourceSerifVariable-Italic.ttf.CVdzAtxO.woff2 filter=lfs diff=lfs merge=lfs -text
275
+ venv/Lib/site-packages/streamlit/static/static/media/SourceSerifVariable-Roman.ttf.mdpVL9bi.woff2 filter=lfs diff=lfs merge=lfs -text
276
+ venv/Lib/site-packages/streamlit/testing/v1/__pycache__/element_tree.cpython-314.pyc filter=lfs diff=lfs merge=lfs -text
venv/Lib/site-packages/streamlit-1.60.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
venv/Lib/site-packages/streamlit-1.60.0.dist-info/METADATA ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: streamlit
3
+ Version: 1.60.0
4
+ Summary: A faster way to build and share data apps
5
+ Author-email: Snowflake Inc <hello@streamlit.io>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://streamlit.io
8
+ Project-URL: Documentation, https://docs.streamlit.io/
9
+ Project-URL: Source Code, https://github.com/streamlit/streamlit
10
+ Project-URL: Bug Tracker, https://github.com/streamlit/streamlit/issues
11
+ Project-URL: Release Notes, https://docs.streamlit.io/develop/quick-reference/changelog
12
+ Project-URL: Community, https://discuss.streamlit.io/
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Environment :: Console
15
+ Classifier: Environment :: Web Environment
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Intended Audience :: Science/Research
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Database :: Front-Ends
24
+ Classifier: Topic :: Office/Business :: Financial :: Spreadsheet
25
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
26
+ Classifier: Topic :: Scientific/Engineering :: Visualization
27
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
28
+ Classifier: Topic :: Software Development :: Widget Sets
29
+ Requires-Python: >=3.10
30
+ Description-Content-Type: text/markdown
31
+ Requires-Dist: altair!=5.4.0,!=5.4.1,<7,>=4.0
32
+ Requires-Dist: blinker<2,>=1.5.0
33
+ Requires-Dist: click<9,>=7.0
34
+ Requires-Dist: gitpython!=3.1.19,<4,>=3.0.7
35
+ Requires-Dist: numpy<3,>=1.23
36
+ Requires-Dist: packaging>=20
37
+ Requires-Dist: pandas<4,>=1.4.0
38
+ Requires-Dist: pillow<13,>=7.1.0
39
+ Requires-Dist: pydeck<1,>=0.8.0b4
40
+ Requires-Dist: protobuf<8,>=3.20
41
+ Requires-Dist: pyarrow<25,>=7.0
42
+ Requires-Dist: requests<3,>=2.27
43
+ Requires-Dist: tenacity<10,>=8.1.0
44
+ Requires-Dist: toml<2,>=0.10.1
45
+ Requires-Dist: typing-extensions<5,>=4.10.0
46
+ Requires-Dist: starlette<2,>=0.40.0
47
+ Requires-Dist: uvicorn<1,>=0.30.0
48
+ Requires-Dist: httptools<1,>=0.6.3
49
+ Requires-Dist: anyio<5,>=4.0.0
50
+ Requires-Dist: python-multipart<1,>=0.0.10
51
+ Requires-Dist: websockets<17,>=12.0.0
52
+ Requires-Dist: itsdangerous<3,>=2.1.2
53
+ Requires-Dist: watchdog<7,>=2.1.5; platform_system != "Darwin"
54
+ Provides-Extra: snowflake
55
+ Requires-Dist: snowflake-snowpark-python[modin]>=1.17.0; extra == "snowflake"
56
+ Requires-Dist: snowflake-connector-python>=3.3.0; extra == "snowflake"
57
+ Provides-Extra: pdf
58
+ Requires-Dist: streamlit-pdf>=1.0.0; extra == "pdf"
59
+ Provides-Extra: auth
60
+ Requires-Dist: Authlib>=1.3.2; extra == "auth"
61
+ Requires-Dist: httpx>=0.24.1; extra == "auth"
62
+ Provides-Extra: charts
63
+ Requires-Dist: matplotlib>=3.0.0; extra == "charts"
64
+ Requires-Dist: graphviz>=0.19.0; extra == "charts"
65
+ Requires-Dist: plotly>=4.0.0; extra == "charts"
66
+ Requires-Dist: orjson>=3.5.0; extra == "charts"
67
+ Provides-Extra: sql
68
+ Requires-Dist: SQLAlchemy>=2.0.0; extra == "sql"
69
+ Provides-Extra: performance
70
+ Requires-Dist: orjson>=3.5.0; extra == "performance"
71
+ Requires-Dist: uvloop>=0.15.2; (sys_platform != "win32" and sys_platform != "cygwin" and platform_python_implementation != "PyPy") and extra == "performance"
72
+ Provides-Extra: all
73
+ Requires-Dist: streamlit[auth,charts,pdf,performance,snowflake,sql]; extra == "all"
74
+ Requires-Dist: rich>=11.0.0; extra == "all"
75
+
76
+ <br>
77
+
78
+ <img src="https://user-images.githubusercontent.com/7164864/217935870-c0bc60a3-6fc0-4047-b011-7b4c59488c91.png" alt="Streamlit logo" style="margin-top:50px"></img>
79
+
80
+ # Welcome to Streamlit 👋
81
+
82
+ **A faster way to build and share data apps.**
83
+
84
+ ## What is Streamlit?
85
+
86
+ Streamlit lets you transform Python scripts into interactive web apps in minutes, instead of weeks. Build dashboards, generate reports, or create chat apps. Once you’ve created an app, you can use our [Community Cloud platform](https://streamlit.io/cloud) to deploy, manage, and share your app.
87
+
88
+ ### Why choose Streamlit?
89
+
90
+ - **Simple and Pythonic:** Write beautiful, easy-to-read code.
91
+ - **Fast, interactive prototyping:** Let others interact with your data and provide feedback quickly.
92
+ - **Live editing:** See your app update instantly as you edit your script.
93
+ - **Open-source and free:** Join a vibrant community and contribute to Streamlit's future.
94
+
95
+ ## Installation
96
+
97
+ Open a terminal and run:
98
+
99
+ ```bash
100
+ $ pip install streamlit
101
+ $ streamlit hello
102
+ ```
103
+
104
+ If this opens our sweet _Streamlit Hello_ app in your browser, you're all set! If not, head over to [our docs](https://docs.streamlit.io/get-started) for specific installs.
105
+
106
+ The app features a bunch of examples of what you can do with Streamlit. Jump to the [quickstart](#quickstart) section to understand how that all works.
107
+
108
+ <img src="https://user-images.githubusercontent.com/7164864/217936487-1017784e-68ec-4e0d-a7f6-6b97525ddf88.gif" alt="Streamlit Hello" width=500 href="none"></img>
109
+
110
+ ## Quickstart
111
+
112
+ ### A little example
113
+
114
+ Create a new file named `streamlit_app.py` in your project directory with the following code:
115
+ ```python
116
+ import streamlit as st
117
+ x = st.slider("Select a value")
118
+ st.write(x, "squared is", x * x)
119
+ ```
120
+
121
+ Now run it to open the app!
122
+ ```
123
+ $ streamlit run streamlit_app.py
124
+ ```
125
+
126
+ <img src="https://user-images.githubusercontent.com/7164864/215172915-cf087c56-e7ae-449a-83a4-b5fa0328d954.gif" width=300 alt="Little example"></img>
127
+
128
+ ### Give me more!
129
+
130
+ Streamlit comes in with [a ton of additional powerful elements](https://docs.streamlit.io/develop/api-reference) to spice up your data apps and delight your viewers. Some examples:
131
+
132
+ <table border="0">
133
+ <tr>
134
+ <td>
135
+ <a target="_blank" href="https://docs.streamlit.io/develop/api-reference/widgets">
136
+ <img src="https://user-images.githubusercontent.com/7164864/217936099-12c16f8c-7fe4-44b1-889a-1ac9ee6a1b44.png" style="max-height:150px; width:auto; display:block;">
137
+ </a>
138
+ </td>
139
+ <td>
140
+ <a target="_blank" href="https://docs.streamlit.io/develop/api-reference/data/st.dataframe">
141
+ <img src="https://user-images.githubusercontent.com/7164864/215110064-5eb4e294-8f30-4933-9563-0275230e52b5.gif" style="max-height:150px; width:auto; display:block;">
142
+ </a>
143
+ </td>
144
+ <td>
145
+ <a target="_blank" href="https://docs.streamlit.io/develop/api-reference/charts">
146
+ <img src="https://user-images.githubusercontent.com/7164864/215174472-bca8a0d7-cf4b-4268-9c3b-8c03dad50bcd.gif" style="max-height:150px; width:auto; display:block;">
147
+ </a>
148
+ </td>
149
+ <td>
150
+ <a target="_blank" href="https://docs.streamlit.io/develop/api-reference/layout">
151
+ <img src="https://user-images.githubusercontent.com/7164864/217936149-a35c35be-0d96-4c63-8c6a-1c4b52aa8f60.png" style="max-height:150px; width:auto; display:block;">
152
+ </a>
153
+ </td>
154
+ <td>
155
+ <a target="_blank" href="https://docs.streamlit.io/develop/concepts/multipage-apps">
156
+ <img src="https://user-images.githubusercontent.com/7164864/215173883-eae0de69-7c1d-4d78-97d0-3bc1ab865e5b.gif" style="max-height:150px; width:auto; display:block;">
157
+ </a>
158
+ </td>
159
+ <td>
160
+ <a target="_blank" href="https://streamlit.io/gallery">
161
+ <img src="https://user-images.githubusercontent.com/7164864/215109229-6ae9111f-e5c1-4f0b-b3a2-87a79268ccc9.gif" style="max-height:150px; width:auto; display:block;">
162
+ </a>
163
+ </td>
164
+ </tr>
165
+ <tr>
166
+ <td>Input widgets</td>
167
+ <td>Dataframes</td>
168
+ <td>Charts</td>
169
+ <td>Layout</td>
170
+ <td>Multi-page apps</td>
171
+ <td>Fun</td>
172
+ </tr>
173
+ </table>
174
+
175
+
176
+ Our vibrant creators community also extends Streamlit capabilities using  🧩 [Streamlit Components](https://streamlit.io/components).
177
+
178
+ ## Get inspired
179
+
180
+ There's so much you can build with Streamlit:
181
+ - 🤖  [LLMs & chatbot apps](https://streamlit.io/gallery?category=llms)
182
+ - 🧬  [Science & technology apps](https://streamlit.io/gallery?category=science-technology)
183
+ - 💬  [NLP & language apps](https://streamlit.io/gallery?category=nlp-language)
184
+ - 🏦  [Finance & business apps](https://streamlit.io/gallery?category=finance-business)
185
+ - 🗺  [Geography & society apps](https://streamlit.io/gallery?category=geography-society)
186
+ - and more!
187
+
188
+ **Check out [our gallery!](https://streamlit.io/gallery)** 🎈
189
+
190
+ ## Community Cloud
191
+
192
+ Deploy, manage and share your apps for free using our [Community Cloud](https://streamlit.io/cloud)! Sign-up [here](https://share.streamlit.io/signup). <br><br>
193
+ <img src="https://user-images.githubusercontent.com/7164864/214965336-64500db3-0d79-4a20-8052-2dda883902d2.gif" width="400"></img>
194
+
195
+ ## Resources
196
+
197
+ - Explore our [docs](https://docs.streamlit.io) to learn how Streamlit works.
198
+ - Ask questions and get help in our [community forum](https://discuss.streamlit.io).
199
+ - Read our [blog](https://blog.streamlit.io) for tips from developers and creators.
200
+ - Extend Streamlit's capabilities by installing or creating your own [Streamlit Components](https://streamlit.io/components).
201
+ - Help others find and play with your app by using the Streamlit GitHub badge in your repository:
202
+ ```markdown
203
+ [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](URL_TO_YOUR_APP)
204
+ ```
205
+ [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://share.streamlit.io/streamlit/roadmap)
206
+
207
+ ## Contribute
208
+
209
+ 🎉 Thanks for your interest in helping improve Streamlit! 🎉
210
+
211
+ We have paused accepting pull requests from outside the Streamlit maintainer team. You can still
212
+ make a valuable contribution by [reporting bugs](https://github.com/streamlit/streamlit/issues/new?template=bug_report.yml),
213
+ [requesting features](https://github.com/streamlit/streamlit/issues/new?template=feature_request.yml),
214
+ [improving or upvoting existing issues](https://github.com/streamlit/streamlit/issues?q=is%3Aissue%20state%3Aopen%20sort%3Areactions-%2B1-desc),
215
+ [commenting on open specs](https://github.com/streamlit/streamlit/issues?q=state%3Aopen%20label%3Achange%3Aspec), creating
216
+ [custom components](https://docs.streamlit.io/develop/concepts/custom-components/components-v2),
217
+ and contributing to [streamlit-extras](https://github.com/arnaudmiribel/streamlit-extras).
218
+
219
+ Read our [contribution guide](https://github.com/streamlit/streamlit/blob/develop/CONTRIBUTING.md)
220
+ for details.
221
+
222
+ ## License
223
+
224
+ Streamlit is completely free and open-source and licensed under the [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) license.
venv/Lib/site-packages/streamlit-1.60.0.dist-info/RECORD ADDED
The diff for this file is too large to render. See raw diff
 
venv/Lib/site-packages/streamlit-1.60.0.dist-info/REQUESTED ADDED
File without changes
venv/Lib/site-packages/streamlit-1.60.0.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
venv/Lib/site-packages/streamlit-1.60.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [console_scripts]
2
+ streamlit = streamlit.web.cli:main
venv/Lib/site-packages/streamlit-1.60.0.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ streamlit
venv/Lib/site-packages/streamlit/runtime/memory_uploaded_file_manager.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import threading
18
+ import uuid
19
+ from collections import defaultdict
20
+ from typing import TYPE_CHECKING
21
+
22
+ from streamlit import util
23
+ from streamlit.runtime.stats import CACHE_MEMORY_FAMILY, CacheStat, group_cache_stats
24
+ from streamlit.runtime.uploaded_file_manager import (
25
+ UploadedFileManager,
26
+ UploadedFileRec,
27
+ UploadFileUrlInfo,
28
+ )
29
+
30
+ if TYPE_CHECKING:
31
+ from collections.abc import Sequence
32
+
33
+
34
+ class MemoryUploadedFileManager(UploadedFileManager):
35
+ """Holds files uploaded by users of the running Streamlit app.
36
+ This class can be used safely from multiple threads simultaneously.
37
+ """
38
+
39
+ def __init__(self, upload_endpoint: str) -> None:
40
+ self.file_storage: dict[str, dict[str, UploadedFileRec]] = defaultdict(dict)
41
+ self.endpoint = upload_endpoint
42
+ self._total_bytes = 0
43
+ self._file_count = 0
44
+ self._lock = threading.Lock()
45
+
46
+ @property
47
+ def stats_families(self) -> Sequence[str]:
48
+ return (CACHE_MEMORY_FAMILY,)
49
+
50
+ def get_files(
51
+ self, session_id: str, file_ids: Sequence[str]
52
+ ) -> list[UploadedFileRec]:
53
+ """Return a list of UploadedFileRec for a given sequence of file_ids.
54
+
55
+ Parameters
56
+ ----------
57
+ session_id
58
+ The ID of the session that owns the files.
59
+ file_ids
60
+ The sequence of ids associated with files to retrieve.
61
+
62
+ Returns
63
+ -------
64
+ List[UploadedFileRec]
65
+ A list of URL UploadedFileRec instances, each instance contains information
66
+ about uploaded file.
67
+ """
68
+ with self._lock:
69
+ # Use `.get` instead of indexing so that reading files for an
70
+ # unknown session does not create an empty entry in the defaultdict.
71
+ session_storage = self.file_storage.get(session_id)
72
+ if session_storage is None:
73
+ return []
74
+
75
+ return [
76
+ file_rec
77
+ for file_id in file_ids
78
+ if (file_rec := session_storage.get(file_id)) is not None
79
+ ]
80
+
81
+ def remove_session_files(self, session_id: str) -> None:
82
+ """Remove all files associated with a given session."""
83
+ with self._lock:
84
+ session_storage = self.file_storage.pop(session_id, None)
85
+ if session_storage is not None:
86
+ self._total_bytes -= sum(
87
+ len(file.data) for file in session_storage.values()
88
+ )
89
+ self._file_count -= len(session_storage)
90
+
91
+ def __repr__(self) -> str:
92
+ return util.repr_(self)
93
+
94
+ def add_file(
95
+ self,
96
+ session_id: str,
97
+ file: UploadedFileRec,
98
+ ) -> None:
99
+ """
100
+ Safe to call from any thread.
101
+
102
+ Parameters
103
+ ----------
104
+ session_id
105
+ The ID of the session that owns the file.
106
+ file
107
+ The file to add.
108
+ """
109
+ with self._lock:
110
+ session_storage = self.file_storage[session_id]
111
+ old_file = session_storage.get(file.file_id)
112
+ if old_file is not None:
113
+ self._total_bytes -= len(old_file.data)
114
+ else:
115
+ self._file_count += 1
116
+
117
+ session_storage[file.file_id] = file
118
+ self._total_bytes += len(file.data)
119
+
120
+ def remove_file(self, session_id: str, file_id: str) -> None:
121
+ """Remove file with given file_id associated with a given session."""
122
+ with self._lock:
123
+ # Use `.get` instead of indexing so that removing a file for an
124
+ # unknown session does not create an empty entry in the defaultdict.
125
+ session_storage = self.file_storage.get(session_id)
126
+ if session_storage is None:
127
+ return
128
+
129
+ file = session_storage.pop(file_id, None)
130
+ if file is not None:
131
+ self._total_bytes -= len(file.data)
132
+ self._file_count -= 1
133
+
134
+ def get_upload_urls(
135
+ self, session_id: str, file_names: Sequence[str]
136
+ ) -> list[UploadFileUrlInfo]:
137
+ """Return a list of UploadFileUrlInfo for a given sequence of file_names."""
138
+ result = []
139
+ for _ in file_names:
140
+ file_id = str(uuid.uuid4())
141
+ result.append(
142
+ UploadFileUrlInfo(
143
+ file_id=file_id,
144
+ upload_url=f"{self.endpoint}/{session_id}/{file_id}",
145
+ delete_url=f"{self.endpoint}/{session_id}/{file_id}",
146
+ )
147
+ )
148
+ return result
149
+
150
+ def get_stats(
151
+ self, _family_names: Sequence[str] | None = None
152
+ ) -> dict[str, list[CacheStat]]:
153
+ """Return the manager's CacheStats.
154
+
155
+ Safe to call from any thread.
156
+ """
157
+ with self._lock:
158
+ total_bytes = self._total_bytes
159
+ file_count = self._file_count
160
+
161
+ # Emit a stat whenever any files are tracked, even if they are all
162
+ # zero-byte uploads (matching the previous per-file behavior). Gating on
163
+ # total_bytes alone would drop zero-byte uploads from the metrics.
164
+ if file_count == 0:
165
+ return {}
166
+
167
+ stats = [
168
+ CacheStat(
169
+ category_name="UploadedFileManager",
170
+ cache_name="",
171
+ byte_length=total_bytes,
172
+ )
173
+ ]
174
+ # In general, get_stats methods need to be able to return only requested stat
175
+ # families, but this method only returns a single family, and we're guaranteed
176
+ # that it was one of those requested if we make it here.
177
+ return {CACHE_MEMORY_FAMILY: group_cache_stats(stats)}
venv/Lib/site-packages/streamlit/runtime/metrics_util.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import contextlib
18
+ import inspect
19
+ import os
20
+ import sys
21
+ import threading
22
+ import time
23
+ import uuid
24
+ from collections.abc import Callable, Sequence, Sized
25
+ from functools import lru_cache, wraps
26
+ from typing import Any, Final, TypeVar, cast, overload
27
+
28
+ from streamlit import config, file_util, type_util, util
29
+ from streamlit.logger import get_logger
30
+ from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
31
+ from streamlit.proto.PageProfile_pb2 import Argument, Command
32
+ from streamlit.runtime.scriptrunner_utils.exceptions import RerunException
33
+ from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx
34
+
35
+ _LOGGER: Final = get_logger(__name__)
36
+
37
+ # Limit the number of commands to keep the page profile message small
38
+ _MAX_TRACKED_COMMANDS: Final = 400
39
+ # Only track a maximum of 25 uses per unique command since some apps use
40
+ # commands excessively (e.g. calling write thousands of times in one rerun)
41
+ # making the page profile useless.
42
+ _MAX_TRACKED_PER_COMMAND: Final = 25
43
+
44
+ # A mapping to convert from the actual name to preferred/shorter representations
45
+ _OBJECT_NAME_MAPPING: Final = {
46
+ "streamlit.delta_generator.DeltaGenerator": "DG",
47
+ # pandas 2.x paths
48
+ "pandas.core.frame.DataFrame": "DataFrame",
49
+ "pandas.core.indexes.base.Index": "PandasIndex",
50
+ "pandas.core.series.Series": "PandasSeries",
51
+ # pandas 3.x paths (module changed from pandas.core.* to pandas.*)
52
+ "pandas.DataFrame": "DataFrame",
53
+ "pandas.Index": "PandasIndex",
54
+ "pandas.Series": "PandasSeries",
55
+ "plotly.graph_objs._figure.Figure": "PlotlyFigure",
56
+ "matplotlib.figure.Figure": "MatplotlibFigure",
57
+ "pandas.io.formats.style.Styler": "PandasStyler",
58
+ "streamlit.connections.sql_connection.SQLConnection": "SQLConnection",
59
+ }
60
+
61
+ # A list of dependencies to check for attribution
62
+ _ATTRIBUTIONS_TO_CHECK: Final = [
63
+ # DB Clients:
64
+ "pymysql",
65
+ "MySQLdb",
66
+ "mysql",
67
+ "pymongo",
68
+ "ibis",
69
+ "boto3",
70
+ "psycopg2",
71
+ "psycopg3",
72
+ "sqlalchemy",
73
+ "elasticsearch",
74
+ "pyodbc",
75
+ "pymssql",
76
+ "cassandra",
77
+ "azure",
78
+ "redis",
79
+ "sqlite3",
80
+ "neo4j",
81
+ "duckdb",
82
+ "opensearchpy",
83
+ "supabase",
84
+ "databricks",
85
+ # Dataframe Libraries:
86
+ "polars",
87
+ "dask",
88
+ "vaex",
89
+ "modin",
90
+ "pyspark",
91
+ "cudf",
92
+ "xarray",
93
+ "geopandas",
94
+ "mars",
95
+ "tables",
96
+ "zarr",
97
+ "datasets",
98
+ "daft",
99
+ # ML & LLM Tools:
100
+ "mistralai",
101
+ "openai",
102
+ "langchain",
103
+ "llama_index",
104
+ "llama_cpp",
105
+ "anthropic",
106
+ "pyllamacpp",
107
+ "cohere",
108
+ "transformers",
109
+ "nomic",
110
+ "diffusers",
111
+ "semantic_kernel",
112
+ "replicate",
113
+ "huggingface_hub",
114
+ "wandb",
115
+ "torch",
116
+ "tensorflow",
117
+ "trubrics",
118
+ "comet_ml",
119
+ "clarifai",
120
+ "reka",
121
+ "hegel",
122
+ "fastchat",
123
+ "assemblyai",
124
+ "openllm",
125
+ "embedchain",
126
+ "haystack",
127
+ "vllm",
128
+ "alpa",
129
+ "jinaai",
130
+ "guidance",
131
+ "litellm",
132
+ "comet_llm",
133
+ "instructor",
134
+ "xgboost",
135
+ "lightgbm",
136
+ "catboost",
137
+ "sklearn",
138
+ "pydantic_ai",
139
+ "datachain",
140
+ "docling",
141
+ "litserve",
142
+ "crawl4ai",
143
+ "baml_client",
144
+ "browser_use",
145
+ "crewai",
146
+ "unsloth",
147
+ "langgraph",
148
+ "dspy",
149
+ "ultralytics",
150
+ "instructor",
151
+ "ragas",
152
+ "swarm",
153
+ "faster_whisper",
154
+ "memori",
155
+ "autogen_agentchat",
156
+ "xai_sdk",
157
+ "agno",
158
+ "langfuse",
159
+ "smolagents",
160
+ "ollama",
161
+ "groq",
162
+ "together",
163
+ "ai21",
164
+ "marvin",
165
+ "outlines",
166
+ "guardrails",
167
+ "promptflow",
168
+ "semantic_router",
169
+ "mem0",
170
+ "aisuite",
171
+ "mlflow",
172
+ "optuna",
173
+ "keras",
174
+ "jax",
175
+ "shap",
176
+ "evidently",
177
+ "great_expectations",
178
+ "bentoml",
179
+ "modal",
180
+ "sagemaker",
181
+ "vertexai",
182
+ "tiktoken",
183
+ "sentence_transformers",
184
+ "spacy",
185
+ "nltk",
186
+ "onnxruntime",
187
+ "llama_api_client",
188
+ # Workflow Tools:
189
+ "prefect",
190
+ "luigi",
191
+ "airflow",
192
+ "dagster",
193
+ "celery",
194
+ # Vector Stores:
195
+ "pgvector",
196
+ "faiss",
197
+ "annoy",
198
+ "pinecone",
199
+ "chromadb",
200
+ "weaviate",
201
+ "qdrant_client",
202
+ "pymilvus",
203
+ "lancedb",
204
+ # Others:
205
+ "snowflake",
206
+ "pydantic",
207
+ "fastapi",
208
+ "playwright",
209
+ "folium",
210
+ "geopandas",
211
+ "httpx",
212
+ "pyecharts",
213
+ "fastplotlib",
214
+ "pygfx",
215
+ "highcharts_core",
216
+ # Optional streamlit dependencies:
217
+ "seaborn",
218
+ "graphviz",
219
+ "matplotlib",
220
+ "uvloop",
221
+ "orjson",
222
+ "rich",
223
+ "streamlit_extras",
224
+ "streamlit_pydantic",
225
+ "pygwalker",
226
+ "plotly",
227
+ "bokeh",
228
+ "plost",
229
+ "authlib",
230
+ # Document Processing:
231
+ "pypdf",
232
+ "pdfplumber",
233
+ "docx",
234
+ "openpyxl",
235
+ "xlsxwriter",
236
+ # Image/Vision:
237
+ "cv2",
238
+ "mediapipe",
239
+ ]
240
+
241
+ _ETC_MACHINE_ID_PATH = "/etc/machine-id"
242
+ _DBUS_MACHINE_ID_PATH = "/var/lib/dbus/machine-id"
243
+
244
+
245
+ def _get_machine_id_v3() -> str:
246
+ """Get the machine ID.
247
+
248
+ This is a unique identifier for a user for tracking metrics,
249
+ that is broken in different ways in some Linux distros and Docker images.
250
+ - at times just a hash of '', which means many machines map to the same ID
251
+ - at times a hash of the same string, when running in a Docker container
252
+ """
253
+
254
+ if os.path.isfile(_ETC_MACHINE_ID_PATH):
255
+ with open(_ETC_MACHINE_ID_PATH, encoding="utf-8") as f:
256
+ machine_id = f.read()
257
+
258
+ elif os.path.isfile(_DBUS_MACHINE_ID_PATH):
259
+ with open(_DBUS_MACHINE_ID_PATH, encoding="utf-8") as f:
260
+ machine_id = f.read()
261
+
262
+ else:
263
+ machine_id = str(uuid.getnode())
264
+
265
+ return machine_id
266
+
267
+
268
+ def _get_machine_id_v4() -> str:
269
+ """Get a random ID that is stable for each machine, generating if needed.
270
+
271
+ This is a unique identifier for a user for tracking metrics.
272
+ Instead of relying on a hardware address in the container or host we'll
273
+ generate a UUID and store it in the ~/.streamlit hidden folder.
274
+ """
275
+ # If gatherUsageStats is False skip this whole code.
276
+ # This is just for people who don't want the extra machine_id_v4 file
277
+ # in their file system.
278
+ if not config.get_option("browser.gatherUsageStats"):
279
+ # This value will never be sent to our telemetry. Just including it here
280
+ # to help debug.
281
+ return "no-machine-id-v4"
282
+
283
+ filepath = file_util.get_streamlit_file_path("machine_id_v4")
284
+ stable_id = None
285
+
286
+ if os.path.exists(filepath):
287
+ with file_util.streamlit_read(filepath) as file:
288
+ stable_id = file.read()
289
+
290
+ if not stable_id:
291
+ stable_id = str(uuid.uuid4())
292
+ with file_util.streamlit_write(filepath) as output:
293
+ output.write(stable_id)
294
+
295
+ return stable_id
296
+
297
+
298
+ class Installation:
299
+ _instance_lock = threading.Lock()
300
+ _instance: Installation | None = None
301
+
302
+ @classmethod
303
+ def instance(cls) -> Installation:
304
+ """Returns the singleton Installation."""
305
+ # We use a double-checked locking optimization to avoid the overhead
306
+ # of acquiring the lock in the common case:
307
+ # https://en.wikipedia.org/wiki/Double-checked_locking
308
+ if cls._instance is None:
309
+ with cls._instance_lock:
310
+ if cls._instance is None:
311
+ cls._instance = Installation()
312
+
313
+ return cls._instance
314
+
315
+ def __init__(self) -> None:
316
+ self.installation_id_v3 = str(
317
+ uuid.uuid5(uuid.NAMESPACE_DNS, _get_machine_id_v3())
318
+ )
319
+
320
+ self.installation_id_v4 = _get_machine_id_v4()
321
+
322
+ def __repr__(self) -> str:
323
+ return util.repr_(self)
324
+
325
+ @property
326
+ def installation_id(self) -> str:
327
+ return self.installation_id_v3
328
+
329
+
330
+ def _get_type_name(obj: object) -> str:
331
+ """Get a simplified name for the type of the given object."""
332
+ with contextlib.suppress(Exception):
333
+ obj_type = obj if inspect.isclass(obj) else type(obj)
334
+ type_name = "unknown"
335
+ if hasattr(obj_type, "__qualname__"):
336
+ type_name = obj_type.__qualname__
337
+ elif hasattr(obj_type, "__name__"):
338
+ type_name = obj_type.__name__
339
+
340
+ if obj_type.__module__ != "builtins":
341
+ # Add the full module path
342
+ type_name = f"{obj_type.__module__}.{type_name}"
343
+
344
+ if type_name in _OBJECT_NAME_MAPPING:
345
+ type_name = _OBJECT_NAME_MAPPING[type_name]
346
+ return type_name
347
+ return "failed"
348
+
349
+
350
+ def _get_top_level_module(func: Callable[..., Any]) -> str:
351
+ """Get the top level module for the given function."""
352
+ module = inspect.getmodule(func)
353
+ if module is None or not module.__name__:
354
+ return "unknown"
355
+ return module.__name__.split(".")[0]
356
+
357
+
358
+ def _get_arg_metadata(arg: object) -> str | None:
359
+ """Get metadata information related to the value of the given object."""
360
+ with contextlib.suppress(Exception):
361
+ if isinstance(arg, (bool)):
362
+ return f"val:{arg}"
363
+
364
+ if isinstance(arg, Sized):
365
+ return f"len:{len(arg)}"
366
+
367
+ return None
368
+
369
+
370
+ @lru_cache(maxsize=256)
371
+ def _get_arg_keywords_cached(func: Callable[..., Any]) -> tuple[str, ...]:
372
+ """Return POSITIONAL_ONLY and POSITIONAL_OR_KEYWORD parameter names as an immutable tuple.
373
+
374
+ Results are cached by function identity. Callers must pass ``func.__func__``
375
+ for bound methods — this function operates on unbound callables only.
376
+
377
+ On Python 3.14+, PEP 649 causes annotation evaluation to be deferred until
378
+ accessed. This can fail with NameError when annotations reference types
379
+ imported under TYPE_CHECKING. Since we only need parameter names (not
380
+ annotations), we use ``annotation_format=Format.STRING`` to avoid evaluation.
381
+
382
+ See: https://github.com/streamlit/streamlit/issues/14324
383
+ """
384
+ params = type_util.get_func_parameters(func)
385
+ return tuple(
386
+ p.name
387
+ for p in params
388
+ if p.kind
389
+ in {inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD}
390
+ )
391
+
392
+
393
+ def _get_arg_keywords(func: Callable[..., Any]) -> list[str]:
394
+ """Return argument names from a function's signature.
395
+
396
+ This returns argument names matching the behavior of getfullargspec().args:
397
+ - Both POSITIONAL_ONLY and POSITIONAL_OR_KEYWORD parameters (not keyword-only)
398
+ - Includes 'self' for bound methods
399
+
400
+ Uses caching to avoid repeated expensive inspect.signature() calls.
401
+
402
+ Note: The underlying LRU cache holds strong references to function objects.
403
+ This is fine for typical Streamlit usage with module-level functions, but
404
+ dynamically created callables (e.g., closures, partials) may be retained
405
+ until evicted from the cache.
406
+ """
407
+ # For bound methods, use __func__ as cache key: this ensures cache hits
408
+ # across different bound instances of the same method, and
409
+ # get_func_parameters(__func__) already includes 'self'.
410
+ if inspect.ismethod(func):
411
+ return list(_get_arg_keywords_cached(func.__func__))
412
+ return list(_get_arg_keywords_cached(func))
413
+
414
+
415
+ def _get_command_telemetry(
416
+ _command_func: Callable[..., Any], _command_name: str, *args: Any, **kwargs: Any
417
+ ) -> Command:
418
+ """Get telemetry information for the given callable and its arguments."""
419
+ arg_keywords = _get_arg_keywords(_command_func)
420
+ self_arg: Any | None = None
421
+ arguments: list[Argument] = []
422
+ is_method = inspect.ismethod(_command_func)
423
+ name = _command_name
424
+
425
+ for i, arg in enumerate(args):
426
+ pos = i
427
+ if is_method:
428
+ # If func is a method, ignore the first argument (self)
429
+ i += 1 # noqa: PLW2901
430
+
431
+ keyword = arg_keywords[i] if len(arg_keywords) > i else f"{i}"
432
+ if keyword == "self":
433
+ self_arg = arg
434
+ continue
435
+ argument = Argument(k=keyword, t=_get_type_name(arg), p=pos)
436
+
437
+ arg_metadata = _get_arg_metadata(arg)
438
+ if arg_metadata:
439
+ argument.m = arg_metadata
440
+ arguments.append(argument)
441
+ for kwarg, kwarg_value in kwargs.items():
442
+ argument = Argument(k=kwarg, t=_get_type_name(kwarg_value))
443
+
444
+ arg_metadata = _get_arg_metadata(kwarg_value)
445
+ if arg_metadata:
446
+ argument.m = arg_metadata
447
+ arguments.append(argument)
448
+
449
+ top_level_module = _get_top_level_module(_command_func)
450
+ if top_level_module != "streamlit":
451
+ # If the gather_metrics decorator is used outside of streamlit library
452
+ # we enforce a prefix to be added to the tracked command:
453
+ name = f"external:{top_level_module}:{name}"
454
+
455
+ if (
456
+ name == "create_instance"
457
+ and self_arg
458
+ and hasattr(self_arg, "name")
459
+ and self_arg.name
460
+ ):
461
+ name = f"component:{self_arg.name}"
462
+
463
+ if name == "_bidi_component" and len(args) > 1 and isinstance(args[1], str):
464
+ # Bound DeltaGenerator methods always receive `self` as args[0], so args[1]
465
+ # is the user-supplied component name.
466
+ component_name = args[1]
467
+ name = f"component_v2:{component_name}"
468
+
469
+ return Command(name=name, args=arguments)
470
+
471
+
472
+ def to_microseconds(seconds: float) -> int:
473
+ """Convert seconds into microseconds."""
474
+ return int(seconds * 1_000_000)
475
+
476
+
477
+ F = TypeVar("F", bound=Callable[..., Any])
478
+
479
+
480
+ @overload
481
+ def gather_metrics(
482
+ name: str,
483
+ func: F,
484
+ ) -> F: ...
485
+
486
+
487
+ @overload
488
+ def gather_metrics(
489
+ name: str,
490
+ func: None = None,
491
+ ) -> Callable[[F], F]: ...
492
+
493
+
494
+ def gather_metrics(name: str, func: F | None = None) -> Callable[[F], F] | F:
495
+ """Function decorator to add telemetry tracking to commands.
496
+
497
+ Parameters
498
+ ----------
499
+ name : str
500
+ The name to use for telemetry tracking.
501
+ func : callable or None
502
+ The function to track for telemetry. If ``None`` (default), returns a
503
+ decorator that can be applied to a function.
504
+
505
+ Examples
506
+ --------
507
+ >>> @st.gather_metrics("my_command")
508
+ ... def my_command(url):
509
+ ... return url
510
+ """
511
+
512
+ if not name:
513
+ _LOGGER.warning("gather_metrics: name is empty")
514
+ name = "undefined"
515
+
516
+ if func is None:
517
+ # Support passing the params via function decorator
518
+ def wrapper(f: F) -> F:
519
+ return gather_metrics(
520
+ name=name,
521
+ func=f,
522
+ )
523
+
524
+ return wrapper
525
+ # To make mypy type narrow F | None -> F
526
+ non_optional_func = func
527
+
528
+ @wraps(non_optional_func)
529
+ def wrapped_func(*args: Any, **kwargs: Any) -> Any:
530
+ from timeit import default_timer as timer
531
+
532
+ exec_start = timer()
533
+ ctx = get_script_run_ctx(suppress_warning=True)
534
+
535
+ tracking_activated = (
536
+ ctx is not None
537
+ and ctx.gather_usage_stats
538
+ and not ctx.command_tracking_deactivated
539
+ and ctx.shared.tracked_commands_count
540
+ < _MAX_TRACKED_COMMANDS # Prevent too much memory usage
541
+ )
542
+
543
+ command_telemetry: Command | None = None
544
+ # This flag is needed to make sure that only the command (the outermost command)
545
+ # that deactivated tracking (via ctx.command_tracking_deactivated) is able to reset it
546
+ # again. This is important to prevent nested commands from reactivating tracking.
547
+ # At this point, we don't know yet if the command will deactivated tracking.
548
+ has_set_command_tracking_deactivated = False
549
+
550
+ if ctx and tracking_activated:
551
+ try:
552
+ command_telemetry = _get_command_telemetry(
553
+ non_optional_func, name, *args, **kwargs
554
+ )
555
+
556
+ ctx.shared.track_command(command_telemetry, _MAX_TRACKED_PER_COMMAND)
557
+ # Deactivate tracking to prevent calls inside already tracked commands
558
+ ctx.command_tracking_deactivated = True
559
+ # The ctx.command_tracking_deactivated flag was set to True,
560
+ # we also need to set has_set_command_tracking_deactivated to True
561
+ # to make sure that this command is able to reset it again.
562
+ has_set_command_tracking_deactivated = True
563
+ except Exception as ex:
564
+ # Always capture all exceptions since we want to make sure that
565
+ # the telemetry never causes any issues.
566
+ _LOGGER.debug("Failed to collect command telemetry", exc_info=ex)
567
+ try:
568
+ result = non_optional_func(*args, **kwargs)
569
+ except RerunException:
570
+ # Duplicated from below, because static analysis tools get confused
571
+ # by deferring the rethrow.
572
+ if tracking_activated and command_telemetry:
573
+ command_telemetry.time = to_microseconds(timer() - exec_start)
574
+ raise
575
+ finally:
576
+ # Activate tracking again if command executes without any exceptions
577
+ # we only want to do that if this command has set the
578
+ # flag to deactivate tracking.
579
+ if ctx and has_set_command_tracking_deactivated:
580
+ ctx.command_tracking_deactivated = False
581
+
582
+ if tracking_activated and command_telemetry:
583
+ # Set the execution time to the measured value
584
+ command_telemetry.time = to_microseconds(timer() - exec_start)
585
+
586
+ return result
587
+
588
+ with contextlib.suppress(AttributeError, NameError):
589
+ # Make this a well-behaved decorator by preserving important function
590
+ # attributes.
591
+ # NameError: Python 3.14 PEP 649 deferred annotation evaluation can raise
592
+ # NameError for TYPE_CHECKING-only imports in inspect.signature()
593
+ wrapped_func.__dict__.update(non_optional_func.__dict__)
594
+ wrapped_func.__signature__ = inspect.signature(non_optional_func) # type: ignore
595
+ return cast("F", wrapped_func)
596
+
597
+
598
+ def create_page_profile_message(
599
+ commands: Sequence[Command],
600
+ exec_time: int,
601
+ prep_time: int,
602
+ uncaught_exception: str | None = None,
603
+ ) -> ForwardMsg:
604
+ """Create and return the full PageProfile ForwardMsg."""
605
+ msg = ForwardMsg()
606
+ page_profile = msg.page_profile
607
+
608
+ page_profile.commands.extend(commands)
609
+ page_profile.exec_time = exec_time
610
+ page_profile.prep_time = prep_time
611
+
612
+ page_profile.headless = config.get_option("server.headless")
613
+
614
+ # Include the server mode for metrics tracking
615
+ if config._server_mode:
616
+ page_profile.server_mode = config._server_mode
617
+
618
+ # Collect all config options that have been manually set
619
+ config_options: set[str] = set()
620
+ if config._config_options:
621
+ for option_name in config._config_options:
622
+ if not config.is_manually_set(option_name):
623
+ # We only care about manually defined options
624
+ continue
625
+
626
+ config_option = config._config_options[option_name]
627
+ config_options.add(
628
+ f"{option_name}:default" if config_option.is_default else option_name
629
+ )
630
+
631
+ page_profile.config.extend(config_options)
632
+
633
+ # Check the predefined set of modules for attribution
634
+ attributions: set[str] = {
635
+ attribution
636
+ for attribution in _ATTRIBUTIONS_TO_CHECK
637
+ if attribution in sys.modules
638
+ }
639
+
640
+ page_profile.os = str(sys.platform)
641
+ page_profile.timezone = str(time.tzname)
642
+ page_profile.attributions.extend(attributions)
643
+
644
+ if uncaught_exception:
645
+ page_profile.uncaught_exception = uncaught_exception
646
+
647
+ app_dir: str | None = None
648
+ if ctx := get_script_run_ctx():
649
+ page_profile.is_fragment_run = bool(ctx.fragment_ids_this_run)
650
+ if ctx.main_script_path:
651
+ app_dir = os.path.dirname(ctx.main_script_path)
652
+
653
+ # Skill/agent detection lives in ``streamlit.web.skills`` (co-located with
654
+ # the installer it must stay aligned with); imported lazily to avoid a
655
+ # module-load dependency from runtime onto web.
656
+ from streamlit.web import skills
657
+
658
+ page_profile.installed_skills.extend(skills.detect_installed_skills(app_dir))
659
+ page_profile.installed_agents.extend(skills.detect_installed_agents())
660
+
661
+ return msg
venv/Lib/site-packages/streamlit/runtime/outside_container_wrapper.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass
18
+ from typing import TYPE_CHECKING
19
+
20
+ if TYPE_CHECKING:
21
+ from streamlit.delta_generator import DeltaGenerator
22
+ from streamlit.proto import Block_pb2
23
+
24
+
25
+ @dataclass
26
+ class OutsideContainerWrapper:
27
+ """Cached implicit wrapper between an outside container and a fragment's writes.
28
+
29
+ Attributes
30
+ ----------
31
+ delta_generator : DeltaGenerator
32
+ The wrapper DeltaGenerator that the fragment writes into.
33
+ creation_delta_path : list[int]
34
+ The delta path at which the wrapper was originally created, retained so
35
+ the wrapper's ``add_block`` delta can be re-emitted on each fragment rerun.
36
+ block_proto : Block_pb2.Block
37
+ The Block proto for the wrapper, also retained for re-emission.
38
+ creating_fragment_id : str | None
39
+ The fragment whose scope created the outside container (``None`` for the
40
+ main script). Drives per-fragment eviction when that scope reruns.
41
+ """
42
+
43
+ delta_generator: DeltaGenerator
44
+ creation_delta_path: list[int]
45
+ block_proto: Block_pb2.Block
46
+ creating_fragment_id: str | None
venv/Lib/site-packages/streamlit/runtime/pages_manager.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import threading
18
+ from pathlib import Path
19
+ from typing import TYPE_CHECKING, Any
20
+
21
+ from streamlit.util import calc_hash
22
+
23
+ if TYPE_CHECKING:
24
+ from streamlit.runtime.scriptrunner.script_cache import ScriptCache
25
+ from streamlit.source_util import PageHash, PageInfo, PageName, ScriptPath
26
+
27
+
28
+ class PagesManager:
29
+ """
30
+ PagesManager is responsible for managing the set of pages that make up
31
+ the entire application. At the start we assume the main script is the
32
+ only page. As the script runs, the main script can call `st.navigation`
33
+ to set the set of pages that make up the app.
34
+ """
35
+
36
+ uses_pages_directory: bool | None = None
37
+
38
+ def __init__(
39
+ self,
40
+ main_script_path: ScriptPath,
41
+ script_cache: ScriptCache | None = None,
42
+ **kwargs: Any,
43
+ ) -> None:
44
+ self._lock = threading.Lock()
45
+ self._main_script_path = main_script_path
46
+ self._main_script_hash: PageHash = calc_hash(main_script_path)
47
+ self._script_cache = script_cache
48
+ self._intended_page_script_hash: PageHash | None = None
49
+ self._intended_page_name: PageName | None = None
50
+ self._current_page_script_hash: PageHash = ""
51
+ self._pages: dict[PageHash, PageInfo] | None = None
52
+ # A relic of v1 of Multipage apps, we performed special handling
53
+ # for apps with a pages directory. We will keep this flag around
54
+ # for now to maintain the behavior for apps that were created with
55
+ # the pages directory feature.
56
+ #
57
+ # NOTE: we will update the feature if the flag has not been set
58
+ # this means that if users use v2 behavior, the flag will
59
+ # always be set to False
60
+ if PagesManager.uses_pages_directory is None:
61
+ PagesManager.uses_pages_directory = Path(
62
+ self.main_script_parent / "pages"
63
+ ).exists()
64
+
65
+ @property
66
+ def main_script_path(self) -> ScriptPath:
67
+ return self._main_script_path
68
+
69
+ @property
70
+ def main_script_parent(self) -> Path:
71
+ return Path(self._main_script_path).parent
72
+
73
+ @property
74
+ def main_script_hash(self) -> PageHash:
75
+ return self._main_script_hash
76
+
77
+ @property
78
+ def current_page_script_hash(self) -> PageHash:
79
+ return self._current_page_script_hash
80
+
81
+ @property
82
+ def intended_page_name(self) -> PageName | None:
83
+ return self._intended_page_name
84
+
85
+ @property
86
+ def intended_page_script_hash(self) -> PageHash | None:
87
+ return self._intended_page_script_hash
88
+
89
+ def set_current_page_script_hash(self, page_script_hash: PageHash) -> None:
90
+ self._current_page_script_hash = page_script_hash
91
+
92
+ def get_main_page(self) -> PageInfo:
93
+ return {
94
+ "script_path": self._main_script_path,
95
+ "page_script_hash": self._main_script_hash,
96
+ }
97
+
98
+ def set_script_intent(
99
+ self, page_script_hash: PageHash, page_name: PageName
100
+ ) -> None:
101
+ # Not lock-protected: attribute assignment is atomic in both GIL and
102
+ # free-threaded CPython, and intent is always set before script
103
+ # execution begins (not concurrently with set_pages_and_resolve).
104
+ self._intended_page_script_hash = page_script_hash
105
+ self._intended_page_name = page_name
106
+
107
+ def get_initial_active_script(self, page_script_hash: PageHash) -> PageInfo | None:
108
+ return {
109
+ # We always run the main script in V2 as it's the common code
110
+ "script_path": self.main_script_path,
111
+ "page_script_hash": page_script_hash
112
+ or self.main_script_hash, # Default Hash
113
+ }
114
+
115
+ def get_pages(self) -> dict[PageHash, PageInfo]:
116
+ """Return a snapshot of the current page registry.
117
+
118
+ Lock-protected for free-threaded Python (PEP 703) where
119
+ iterating a dict during concurrent mutation is unsafe.
120
+ Returns a shallow copy so callers can safely iterate.
121
+
122
+ If pages are not set, returns a default page info where the main
123
+ script path is the executing script and the page script hash/name
124
+ reflects the intended page requested.
125
+ """
126
+ with self._lock:
127
+ if self._pages is not None:
128
+ return dict(self._pages)
129
+ return {
130
+ self.main_script_hash: {
131
+ "page_script_hash": self.intended_page_script_hash or "",
132
+ "page_name": self.intended_page_name or "",
133
+ "icon": "",
134
+ "script_path": self.main_script_path,
135
+ }
136
+ }
137
+
138
+ def _set_pages(self, pages: dict[PageHash, PageInfo]) -> None:
139
+ """Internal method for setting pages. Use set_pages_and_resolve() instead."""
140
+ with self._lock:
141
+ self._pages = pages
142
+
143
+ def set_pages_and_resolve(
144
+ self,
145
+ pages: dict[PageHash, PageInfo],
146
+ fallback_page_hash: PageHash = "",
147
+ ) -> PageInfo | None:
148
+ """Atomically set the page registry and resolve the current page.
149
+
150
+ Both operations are performed under a single lock, ensuring the page
151
+ resolution sees the pages that were just set even under concurrent
152
+ access.
153
+
154
+ Parameters
155
+ ----------
156
+ pages : dict[PageHash, PageInfo]
157
+ The page registry to set.
158
+ fallback_page_hash : PageHash
159
+ The fallback page hash to use if the intended page is not found.
160
+
161
+ Returns
162
+ -------
163
+ PageInfo | None
164
+ The resolved page info, or None if no matching page is found.
165
+ """
166
+ with self._lock:
167
+ self._pages = pages
168
+ return self._resolve_page_script(fallback_page_hash)
169
+
170
+ def _resolve_page_script(
171
+ self, fallback_page_hash: PageHash = ""
172
+ ) -> PageInfo | None:
173
+ """Internal resolver — caller must hold self._lock.
174
+
175
+ Resolves the page script based on intended_page_script_hash or
176
+ intended_page_name, falling back to fallback_page_hash if needed.
177
+ """
178
+ if self._pages is None:
179
+ return None
180
+
181
+ if self.intended_page_script_hash:
182
+ # If a page hash is specified, we assume a page should exist.
183
+ # Return the matching page or fall back to the default page hash.
184
+ return self._pages.get(
185
+ self.intended_page_script_hash,
186
+ self._pages.get(fallback_page_hash, None),
187
+ )
188
+ if self.intended_page_name:
189
+ # If a user navigates directly to a non-main page of an app,
190
+ # the page name can identify the page script to run.
191
+ # Note: The lambda captures self.intended_page_name at execution
192
+ # time. This is safe because attribute reads are atomic in both
193
+ # GIL and free-threaded CPython, and set_script_intent is always
194
+ # called before script execution begins.
195
+ return next(
196
+ filter(
197
+ # There seems to be this weird bug with mypy where it
198
+ # thinks that p can be None (which is impossible given the
199
+ # types of pages), so we add `p and` at the beginning of
200
+ # the predicate to circumvent this.
201
+ lambda p: p and (p["url_pathname"] == self.intended_page_name),
202
+ self._pages.values(),
203
+ ),
204
+ None,
205
+ )
206
+
207
+ return self._pages.get(fallback_page_hash, None)
208
+
209
+ def get_page_script_byte_code(self, script_path: str) -> Any:
210
+ if self._script_cache is None:
211
+ # Returning an empty string for an empty script
212
+ return ""
213
+
214
+ return self._script_cache.get_bytecode(script_path)
venv/Lib/site-packages/streamlit/runtime/parallel_coordinator.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """ParallelFragmentCoordinator and supporting helpers.
16
+
17
+ Manages a thread pool for parallel fragment execution. The coordinator
18
+ receives the caller's ``ScriptRunContext`` explicitly via ``submit()``
19
+ so that worker threads can access the correct context.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import contextlib
25
+ import contextvars
26
+ import threading
27
+ from concurrent.futures import ThreadPoolExecutor
28
+ from typing import TYPE_CHECKING, Any
29
+
30
+ from streamlit.runtime.scriptrunner_utils.exceptions import (
31
+ RerunException,
32
+ StopException,
33
+ )
34
+ from streamlit.runtime.scriptrunner_utils.script_run_context_attr import (
35
+ SCRIPT_RUN_CONTEXT_ATTR_NAME,
36
+ )
37
+
38
+ if TYPE_CHECKING:
39
+ from collections.abc import Callable, Iterator
40
+
41
+ from streamlit.runtime.scriptrunner_utils.script_run_context import (
42
+ ScriptRunContext,
43
+ )
44
+
45
+
46
+ @contextlib.contextmanager
47
+ def _scoped_ctx_attach(ctx: ScriptRunContext | None) -> Iterator[None]:
48
+ """Bind *ctx* as the active ScriptRunContext on the current thread for
49
+ the duration of the block; restore the prior binding on exit.
50
+
51
+ Used by ``ParallelFragmentCoordinator.submit()`` so a pool thread that
52
+ executes successive submissions sees the right ctx for each call and
53
+ never carries a stale ctx across submissions.
54
+ """
55
+ thread = threading.current_thread()
56
+ prev = getattr(thread, SCRIPT_RUN_CONTEXT_ATTR_NAME, None)
57
+ setattr(thread, SCRIPT_RUN_CONTEXT_ATTR_NAME, ctx)
58
+ try:
59
+ yield
60
+ finally:
61
+ if prev is None:
62
+ try:
63
+ delattr(thread, SCRIPT_RUN_CONTEXT_ATTR_NAME)
64
+ except AttributeError:
65
+ pass
66
+ else:
67
+ setattr(thread, SCRIPT_RUN_CONTEXT_ATTR_NAME, prev)
68
+
69
+
70
+ class ParallelFragmentCoordinator:
71
+ """Manages the lifecycle of parallel fragment workers for one script run.
72
+
73
+ Owned by ScriptRunContext (created in ctx.reset()) and exposed as
74
+ ctx.parallel_coordinator. The coordinator is single-use: a fresh
75
+ instance is created at the start of every script run, joined or drained
76
+ before the run ends, and discarded.
77
+
78
+ Workers submitted via :meth:`submit` run inside a
79
+ ``contextvars.copy_context()`` snapshot of the caller's context with a
80
+ scoped ``ScriptRunContext`` attach so ``get_script_run_ctx()`` and
81
+ ``ThreadState.get()`` return the parent's values. Worker-side
82
+ ``ThreadState.update()`` writes stay local to the copied context.
83
+ """
84
+
85
+ def __init__(
86
+ self,
87
+ yield_check: Callable[[], None],
88
+ max_workers: int | None = None,
89
+ poll_interval: float = 0.1,
90
+ ) -> None:
91
+ if max_workers is not None and max_workers < 1:
92
+ raise ValueError(
93
+ f"runner.parallelMaxWorkers must be None or a positive "
94
+ f"integer, got {max_workers!r}"
95
+ )
96
+ self._executor = ThreadPoolExecutor(max_workers=max_workers)
97
+ self._outstanding = 0
98
+ self._join_condition = threading.Condition(threading.Lock())
99
+ self._stop_event = threading.Event()
100
+ self._worker_exception: RerunException | StopException | None = None
101
+ self._exception_lock = threading.Lock()
102
+ self._yield_check = yield_check
103
+ self._poll_interval = poll_interval
104
+
105
+ def submit(
106
+ self,
107
+ fn: Callable[..., Any],
108
+ ctx: ScriptRunContext | None,
109
+ *args: Any,
110
+ ) -> None:
111
+ """Submit a worker function to the thread pool.
112
+
113
+ Captures the caller's full ``contextvars.Context`` (which includes
114
+ ``FragmentThreadState``) at submit time. The worker runs inside
115
+ ``copy_context().run(...)`` with a scoped ctx attach so
116
+ ``get_script_run_ctx()`` and ``ThreadState.get()`` return the parent's
117
+ values for the duration of the call. Worker-side
118
+ ``ThreadState.update()`` writes stay local to the captured copy — they
119
+ never leak back to the parent thread.
120
+
121
+ Increments the outstanding counter before submitting so a nested
122
+ submit() from inside a running worker is visible to join() before
123
+ the parent's tracked() decrement runs. May be called from any
124
+ thread (main thread or worker threads for nested fragments).
125
+
126
+ Parameters
127
+ ----------
128
+ fn : Callable[..., Any]
129
+ The worker function to execute in the thread pool.
130
+ ctx : ScriptRunContext | None
131
+ The ScriptRunContext to propagate to the worker thread so that
132
+ ``get_script_run_ctx()`` returns the correct context inside the
133
+ worker.
134
+ *args : Any
135
+ Positional arguments forwarded to ``fn``.
136
+ """
137
+ captured = contextvars.copy_context()
138
+
139
+ with self._join_condition:
140
+ self._outstanding += 1
141
+
142
+ def tracked() -> None:
143
+ try:
144
+ with _scoped_ctx_attach(ctx):
145
+ captured.run(fn, *args)
146
+ finally:
147
+ with self._join_condition:
148
+ self._outstanding -= 1
149
+ self._join_condition.notify_all()
150
+
151
+ try:
152
+ self._executor.submit(tracked)
153
+ except RuntimeError:
154
+ with self._join_condition:
155
+ self._outstanding -= 1
156
+ self._join_condition.notify_all()
157
+ raise
158
+
159
+ def request_stop(self) -> None:
160
+ """Record an st.stop() from a worker. First writer wins."""
161
+ with self._exception_lock:
162
+ if self._worker_exception is None:
163
+ self._worker_exception = StopException()
164
+ self._stop_event.set()
165
+ self.notify_yield_waiters()
166
+
167
+ def request_rerun(self, exc: RerunException) -> None:
168
+ """Record an st.rerun(scope='app') from a worker. First writer wins."""
169
+ with self._exception_lock:
170
+ if self._worker_exception is None:
171
+ self._worker_exception = exc
172
+ self._stop_event.set()
173
+ self.notify_yield_waiters()
174
+
175
+ def should_stop(self) -> bool:
176
+ """Whether worker threads should cooperatively exit at their next
177
+ yield point.
178
+ """
179
+ return self._stop_event.is_set()
180
+
181
+ @property
182
+ def worker_exception(self) -> RerunException | StopException | None:
183
+ """The exception stored by the first worker to call request_stop()
184
+ or request_rerun().
185
+ """
186
+ with self._exception_lock:
187
+ return self._worker_exception
188
+
189
+ def _raise_if_worker_exception(self) -> None:
190
+ """Re-raise the stored worker exception if one exists."""
191
+ stored = self.worker_exception
192
+ if stored is not None:
193
+ raise stored
194
+
195
+ def notify_yield_waiters(self) -> None:
196
+ """Wake the thread blocked in :meth:`join` so ``yield_check`` runs promptly.
197
+
198
+ Called from workers (:meth:`request_stop` / :meth:`request_rerun`) and from
199
+ ``ScriptRunner`` when a rerun/stop request is enqueued from another thread
200
+ while the script thread is blocked inside :meth:`join`.
201
+ """
202
+ with self._join_condition:
203
+ self._join_condition.notify_all()
204
+
205
+ def join(self) -> None:
206
+ """Block until all outstanding work completes.
207
+
208
+ Uses ``_join_condition`` so the script thread wakes immediately when a
209
+ worker finishes (via ``notify_all`` on ``_outstanding`` decrement) or when
210
+ :meth:`notify_yield_waiters` is called. Falls back to
211
+ ``poll_interval`` as a worst-case ceiling so ``yield_check()`` still runs
212
+ periodically even when ``_outstanding`` is unchanged (e.g. one slow
213
+ fragment still running).
214
+
215
+ If a worker stored an exception, raises it instead of returning normally.
216
+ If join() raises (worker exception or yield-check exception), the
217
+ executor is left running and the caller is responsible for calling
218
+ drain() to shut down in-flight workers.
219
+ """
220
+ while True:
221
+ with self._join_condition:
222
+ if self._outstanding == 0:
223
+ break
224
+ self._yield_check()
225
+ self._raise_if_worker_exception()
226
+ with self._join_condition:
227
+ if self._outstanding > 0:
228
+ self._join_condition.wait(timeout=self._poll_interval)
229
+ self._raise_if_worker_exception()
230
+ self._executor.shutdown(wait=False)
231
+
232
+ def drain(self) -> None:
233
+ """Cleanup join after cancellation.
234
+
235
+ Sets the stop event so workers at their next yield point exit, then
236
+ shuts down the executor synchronously, cancelling queued futures.
237
+ Does NOT call _yield_check — safe to call from except blocks
238
+ without risking recursive RerunException/StopException.
239
+ """
240
+ self._stop_event.set()
241
+ self._executor.shutdown(wait=True, cancel_futures=True)
venv/Lib/site-packages/streamlit/runtime/runtime.py ADDED
@@ -0,0 +1,788 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import sys
19
+ import time
20
+ import traceback
21
+ from dataclasses import dataclass, field
22
+ from enum import Enum
23
+ from typing import TYPE_CHECKING, Any, Final, NamedTuple
24
+
25
+ from streamlit.components.lib.local_component_registry import LocalComponentRegistry
26
+ from streamlit.components.v2.component_manager import BidiComponentManager
27
+ from streamlit.logger import get_logger
28
+ from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
29
+ from streamlit.runtime.app_session import AppSession
30
+ from streamlit.runtime.caching import (
31
+ get_data_cache_stats_provider,
32
+ get_resource_cache_stats_provider,
33
+ )
34
+ from streamlit.runtime.caching.storage.local_disk_cache_storage import (
35
+ LocalDiskCacheStorageManager,
36
+ )
37
+ from streamlit.runtime.media_file_manager import MediaFileManager
38
+ from streamlit.runtime.memory_session_storage import MemorySessionStorage
39
+ from streamlit.runtime.runtime_util import MESSAGE_FLUSH_INTERVAL_SECS
40
+ from streamlit.runtime.script_data import ScriptData
41
+ from streamlit.runtime.scriptrunner.script_cache import ScriptCache
42
+ from streamlit.runtime.session_manager import (
43
+ ActiveSessionInfo,
44
+ SessionClient,
45
+ SessionClientDisconnectedError,
46
+ SessionManager,
47
+ SessionStorage,
48
+ )
49
+ from streamlit.runtime.state import (
50
+ SCRIPT_RUN_WITHOUT_ERRORS_KEY,
51
+ SessionStateStatProvider,
52
+ )
53
+ from streamlit.runtime.stats import (
54
+ StatsManager,
55
+ StatsProvider,
56
+ )
57
+ from streamlit.runtime.websocket_session_manager import WebsocketSessionManager
58
+
59
+ if TYPE_CHECKING:
60
+ from collections.abc import Awaitable
61
+
62
+ from streamlit.components.types.base_component_registry import BaseComponentRegistry
63
+ from streamlit.proto.BackMsg_pb2 import BackMsg
64
+ from streamlit.runtime.caching.storage import CacheStorageManager
65
+ from streamlit.runtime.media_file_storage import MediaFileStorage
66
+ from streamlit.runtime.scriptrunner_utils.script_run_context import (
67
+ OnScriptErrorHandler,
68
+ UserInfoType,
69
+ )
70
+ from streamlit.runtime.uploaded_file_manager import UploadedFileManager
71
+
72
+ # Wait for the script run result for 60s and if no result is available give up
73
+ SCRIPT_RUN_CHECK_TIMEOUT: Final = 60
74
+
75
+ # On Windows, periodically check for signals when blocked in asyncio.wait()
76
+ # This ensures Ctrl+C can be processed even when no sessions are connected
77
+ _SIGNAL_CHECK_INTERVAL: Final = 0.5 if sys.platform == "win32" else None
78
+
79
+ _LOGGER: Final = get_logger(__name__)
80
+
81
+
82
+ class RuntimeStoppedError(Exception):
83
+ """Raised by operations on a Runtime instance that is stopped."""
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class RuntimeConfig:
88
+ """Config options for StreamlitRuntime."""
89
+
90
+ # The filesystem path of the Streamlit script to run.
91
+ script_path: str
92
+
93
+ # The storage backend for Streamlit's MediaFileManager.
94
+ media_file_storage: MediaFileStorage
95
+
96
+ # The upload file manager
97
+ uploaded_file_manager: UploadedFileManager
98
+
99
+ # The cache storage backend for Streamlit's st.cache_data.
100
+ cache_storage_manager: CacheStorageManager = field(
101
+ default_factory=LocalDiskCacheStorageManager
102
+ )
103
+
104
+ # The ComponentRegistry instance to use.
105
+ component_registry: BaseComponentRegistry = field(
106
+ default_factory=LocalComponentRegistry
107
+ )
108
+
109
+ # The BidiComponentManager instance to use for v2 components.
110
+ bidi_component_registry: BidiComponentManager = field(
111
+ default_factory=BidiComponentManager
112
+ )
113
+
114
+ # The SessionManager class to be used.
115
+ session_manager_class: type[SessionManager] = WebsocketSessionManager
116
+
117
+ # The SessionStorage instance for the SessionManager to use.
118
+ session_storage: SessionStorage = field(default_factory=MemorySessionStorage)
119
+
120
+ # True if the command used to start Streamlit was `streamlit hello`.
121
+ is_hello: bool = False
122
+
123
+ # Callback to invoke when an uncaught exception occurs in user script code.
124
+ on_script_error: OnScriptErrorHandler | None = None
125
+
126
+ # TODO(vdonato): Eventually add a new fragment_storage_class field enabling the code
127
+ # creating a new Streamlit Runtime to configure the FragmentStorage instances
128
+ # created by each new AppSession. We choose not to do this for now to avoid adding
129
+ # additional complexity to RuntimeConfig/SessionManager/etc when it's unlikely
130
+ # we'll have a custom implementation of this class anytime soon.
131
+
132
+
133
+ class RuntimeState(Enum):
134
+ INITIAL = "INITIAL"
135
+ NO_SESSIONS_CONNECTED = "NO_SESSIONS_CONNECTED"
136
+ ONE_OR_MORE_SESSIONS_CONNECTED = "ONE_OR_MORE_SESSIONS_CONNECTED"
137
+ STOPPING = "STOPPING"
138
+ STOPPED = "STOPPED"
139
+
140
+
141
+ class AsyncObjects(NamedTuple):
142
+ """Container for all asyncio objects that Runtime manages.
143
+ These cannot be initialized until the Runtime's eventloop is assigned.
144
+ """
145
+
146
+ # The eventloop that Runtime is running on.
147
+ eventloop: asyncio.AbstractEventLoop
148
+
149
+ # Set after Runtime.stop() is called. Never cleared.
150
+ must_stop: asyncio.Event
151
+
152
+ # Set when a client connects; cleared when we have no connected clients.
153
+ has_connection: asyncio.Event
154
+
155
+ # Set after a ForwardMsg is enqueued; cleared when we flush ForwardMsgs.
156
+ need_send_data: asyncio.Event
157
+
158
+ # Completed when the Runtime has started.
159
+ started: asyncio.Future[None]
160
+
161
+ # Completed when the Runtime has stopped.
162
+ stopped: asyncio.Future[None]
163
+
164
+
165
+ class Runtime:
166
+ _instance: Runtime | None = None
167
+
168
+ @classmethod
169
+ def instance(cls) -> Runtime:
170
+ """Return the singleton Runtime instance. Raise an Error if the
171
+ Runtime hasn't been created yet.
172
+ """
173
+ if cls._instance is None:
174
+ raise RuntimeError("Runtime hasn't been created!")
175
+ return cls._instance
176
+
177
+ @classmethod
178
+ def exists(cls) -> bool:
179
+ """True if the singleton Runtime instance has been created.
180
+
181
+ When a Streamlit app is running in "raw mode" - that is, when the
182
+ app is run via `python app.py` instead of `streamlit run app.py` -
183
+ the Runtime will not exist, and various Streamlit functions need
184
+ to adapt.
185
+ """
186
+ return cls._instance is not None
187
+
188
+ def __init__(self, config: RuntimeConfig) -> None:
189
+ """Create a Runtime instance. It won't be started yet.
190
+
191
+ Runtime is *not* thread-safe. Its public methods are generally
192
+ safe to call only on the same thread that its event loop runs on.
193
+
194
+ Parameters
195
+ ----------
196
+ config
197
+ Config options.
198
+ """
199
+ if Runtime._instance is not None:
200
+ raise RuntimeError("Runtime instance already exists!")
201
+ Runtime._instance = self
202
+
203
+ # Will be created when we start.
204
+ self._async_objs: AsyncObjects | None = None
205
+
206
+ # The task that runs our main loop. We need to save a reference
207
+ # to it so that it doesn't get garbage collected while running.
208
+ self._loop_coroutine_task: asyncio.Task[None] | None = None
209
+
210
+ self._main_script_path = config.script_path
211
+ self._is_hello = config.is_hello
212
+
213
+ self._state = RuntimeState.INITIAL
214
+
215
+ # Initialize managers
216
+ self._component_registry = config.component_registry
217
+ self._bidi_component_registry = config.bidi_component_registry
218
+ self._uploaded_file_mgr = config.uploaded_file_manager
219
+ self._media_file_mgr = MediaFileManager(storage=config.media_file_storage)
220
+ self._cache_storage_manager = config.cache_storage_manager
221
+ self._script_cache = ScriptCache()
222
+
223
+ # Discover and register components for CCv2 from installed packages
224
+ self._bidi_component_registry.discover_and_register_components()
225
+
226
+ # Build kwargs, only including on_script_error when set to maintain
227
+ # backwards compatibility with custom SessionManager subclasses that
228
+ # may not accept this parameter yet.
229
+ session_mgr_kwargs: dict[str, Any] = {
230
+ "session_storage": config.session_storage,
231
+ "uploaded_file_manager": self._uploaded_file_mgr,
232
+ "script_cache": self._script_cache,
233
+ "message_enqueued_callback": self._enqueued_some_message,
234
+ }
235
+ if config.on_script_error is not None:
236
+ session_mgr_kwargs["on_script_error"] = config.on_script_error
237
+
238
+ self._session_mgr = config.session_manager_class(**session_mgr_kwargs)
239
+
240
+ self._stats_mgr = StatsManager()
241
+ self._stats_mgr.register_provider(get_data_cache_stats_provider())
242
+ self._stats_mgr.register_provider(get_resource_cache_stats_provider())
243
+ if self._uploaded_file_mgr is not None:
244
+ self._stats_mgr.register_provider(self._uploaded_file_mgr)
245
+ # Register media file storage for stats if it implements StatsProvider
246
+ if isinstance(config.media_file_storage, StatsProvider):
247
+ self._stats_mgr.register_provider(config.media_file_storage)
248
+ self._stats_mgr.register_provider(SessionStateStatProvider(self._session_mgr))
249
+
250
+ # Register session manager for session event metrics if it implements StatsProvider
251
+ if isinstance(self._session_mgr, StatsProvider):
252
+ self._stats_mgr.register_provider(self._session_mgr)
253
+
254
+ @property
255
+ def state(self) -> RuntimeState:
256
+ return self._state
257
+
258
+ @property
259
+ def component_registry(self) -> BaseComponentRegistry:
260
+ return self._component_registry
261
+
262
+ @property
263
+ def bidi_component_registry(self) -> BidiComponentManager:
264
+ return self._bidi_component_registry
265
+
266
+ @property
267
+ def uploaded_file_mgr(self) -> UploadedFileManager:
268
+ return self._uploaded_file_mgr
269
+
270
+ @property
271
+ def cache_storage_manager(self) -> CacheStorageManager:
272
+ return self._cache_storage_manager
273
+
274
+ @property
275
+ def media_file_mgr(self) -> MediaFileManager:
276
+ return self._media_file_mgr
277
+
278
+ @property
279
+ def stats_mgr(self) -> StatsManager:
280
+ return self._stats_mgr
281
+
282
+ @property
283
+ def stopped(self) -> Awaitable[None]:
284
+ """A Future that completes when the Runtime's run loop has exited."""
285
+ return self._get_async_objs().stopped
286
+
287
+ # NOTE: A few Runtime methods listed as threadsafe (get_client and
288
+ # is_active_session) currently rely on the implementation detail that
289
+ # WebsocketSessionManager's get_active_session_info and is_active_session methods
290
+ # happen to be threadsafe. This may change with future SessionManager implementations,
291
+ # at which point we'll need to formalize our thread safety rules for each
292
+ # SessionManager method.
293
+ def get_client(self, session_id: str) -> SessionClient | None:
294
+ """Get the SessionClient for the given session_id, or None
295
+ if no such session exists.
296
+
297
+ Notes
298
+ -----
299
+ Threading: SAFE. May be called on any thread.
300
+ """
301
+ session_info = self._session_mgr.get_active_session_info(session_id)
302
+ if session_info is None:
303
+ return None
304
+ return session_info.client
305
+
306
+ def clear_user_info_for_session(self, session_id: str) -> None:
307
+ """Clear the user_info for the given session_id.
308
+
309
+ Notes
310
+ -----
311
+ Threading: SAFE. May be called on any thread.
312
+ """
313
+ session_info = self._session_mgr.get_session_info(session_id)
314
+ if session_info is not None:
315
+ session_info.session.clear_user_info()
316
+
317
+ async def start(self) -> None:
318
+ """Start the runtime. This must be called only once, before
319
+ any other functions are called.
320
+
321
+ When this coroutine returns, Streamlit is ready to accept new sessions.
322
+
323
+ Notes
324
+ -----
325
+ Threading: UNSAFE. Must be called on the eventloop thread.
326
+ """
327
+
328
+ # Create our AsyncObjects. We need to have a running eventloop to
329
+ # instantiate our various synchronization primitives.
330
+ async_objs = AsyncObjects(
331
+ eventloop=asyncio.get_running_loop(),
332
+ must_stop=asyncio.Event(),
333
+ has_connection=asyncio.Event(),
334
+ need_send_data=asyncio.Event(),
335
+ started=asyncio.Future(),
336
+ stopped=asyncio.Future(),
337
+ )
338
+ self._async_objs = async_objs
339
+
340
+ self._loop_coroutine_task = asyncio.create_task(
341
+ self._loop_coroutine(), name="Runtime.loop_coroutine"
342
+ )
343
+
344
+ await async_objs.started
345
+
346
+ def stop(self) -> None:
347
+ """Request that Streamlit close all sessions and stop running.
348
+ Note that Streamlit won't stop running immediately.
349
+
350
+ Notes
351
+ -----
352
+ Threading: SAFE. May be called from any thread.
353
+ """
354
+
355
+ async_objs = self._get_async_objs()
356
+
357
+ def stop_on_eventloop() -> None:
358
+ if self._state in {RuntimeState.STOPPING, RuntimeState.STOPPED}:
359
+ return
360
+
361
+ _LOGGER.debug("Runtime stopping...")
362
+ self._set_state(RuntimeState.STOPPING)
363
+ async_objs.must_stop.set()
364
+
365
+ async_objs.eventloop.call_soon_threadsafe(stop_on_eventloop)
366
+
367
+ def is_active_session(self, session_id: str) -> bool:
368
+ """True if the session_id belongs to an active session.
369
+
370
+ Notes
371
+ -----
372
+ Threading: SAFE. May be called on any thread.
373
+ """
374
+ return self._session_mgr.is_active_session(session_id)
375
+
376
+ def connect_session(
377
+ self,
378
+ client: SessionClient,
379
+ user_info: UserInfoType,
380
+ existing_session_id: str | None = None,
381
+ session_id_override: str | None = None,
382
+ ) -> str:
383
+ """Create a new session (or connect to an existing one) and return its unique ID.
384
+
385
+ Parameters
386
+ ----------
387
+ client
388
+ A concrete SessionClient implementation for communicating with
389
+ the session's client.
390
+ user_info
391
+ A dict that contains information about the session's user. For now,
392
+ it only (optionally) contains the user's email address.
393
+
394
+ {
395
+ "email": "example@example.com"
396
+ }
397
+ existing_session_id
398
+ The ID of an existing session to reconnect to. If one is not provided, a new
399
+ session is created. Note that whether the Runtime's SessionManager supports
400
+ reconnecting to an existing session depends on the SessionManager that this
401
+ runtime is configured with.
402
+ session_id_override
403
+ The ID to assign to a new session being created with this method. Setting
404
+ this can be useful when the service that a Streamlit Runtime is running in
405
+ wants to tie the lifecycle of a Streamlit session to some other session-like
406
+ object that it manages. Only one of existing_session_id and
407
+ session_id_override should be set.
408
+
409
+ Returns
410
+ -------
411
+ str
412
+ The session's unique string ID.
413
+
414
+ Notes
415
+ -----
416
+ Threading: UNSAFE. Must be called on the eventloop thread.
417
+ """
418
+ if existing_session_id and session_id_override: # pragma: no cover - defensive
419
+ raise RuntimeError(
420
+ "Only one of existing_session_id and session_id_override should be set. "
421
+ "This should never happen."
422
+ )
423
+
424
+ if self._state in {RuntimeState.STOPPING, RuntimeState.STOPPED}:
425
+ raise RuntimeStoppedError(f"Can't connect_session (state={self._state})")
426
+
427
+ session_id = self._session_mgr.connect_session(
428
+ client=client,
429
+ script_data=ScriptData(self._main_script_path, self._is_hello),
430
+ user_info=user_info,
431
+ existing_session_id=existing_session_id,
432
+ session_id_override=session_id_override,
433
+ )
434
+ self._set_state(RuntimeState.ONE_OR_MORE_SESSIONS_CONNECTED)
435
+ self._get_async_objs().has_connection.set()
436
+
437
+ return session_id
438
+
439
+ def create_session(
440
+ self,
441
+ client: SessionClient,
442
+ user_info: UserInfoType,
443
+ existing_session_id: str | None = None,
444
+ session_id_override: str | None = None,
445
+ ) -> str:
446
+ """Create a new session (or connect to an existing one) and return its unique ID.
447
+
448
+ Notes
449
+ -----
450
+ This method is simply an alias for connect_session added for backwards
451
+ compatibility.
452
+ """
453
+ _LOGGER.warning("create_session is deprecated! Use connect_session instead.")
454
+ return self.connect_session(
455
+ client=client,
456
+ user_info=user_info,
457
+ existing_session_id=existing_session_id,
458
+ session_id_override=session_id_override,
459
+ )
460
+
461
+ def close_session(self, session_id: str) -> None:
462
+ """Close and completely shut down a session.
463
+
464
+ This differs from disconnect_session in that it always completely shuts down a
465
+ session, permanently losing any associated state (session state, uploaded files,
466
+ etc.).
467
+
468
+ This function may be called multiple times for the same session,
469
+ which is not an error. (Subsequent calls just no-op.)
470
+
471
+ Parameters
472
+ ----------
473
+ session_id
474
+ The session's unique ID.
475
+
476
+ Notes
477
+ -----
478
+ Threading: UNSAFE. Must be called on the eventloop thread.
479
+ """
480
+ session_info = self._session_mgr.get_session_info(session_id)
481
+ if session_info:
482
+ self._session_mgr.close_session(session_id)
483
+ self._on_session_disconnected()
484
+
485
+ def disconnect_session(self, session_id: str) -> None:
486
+ """Disconnect a session. It will stop producing ForwardMsgs.
487
+
488
+ Differs from close_session because disconnected sessions can be reconnected to
489
+ for a brief window (depending on the SessionManager/SessionStorage
490
+ implementations used by the runtime).
491
+
492
+ This function may be called multiple times for the same session,
493
+ which is not an error. (Subsequent calls just no-op.)
494
+
495
+ Parameters
496
+ ----------
497
+ session_id
498
+ The session's unique ID.
499
+
500
+ Notes
501
+ -----
502
+ Threading: UNSAFE. Must be called on the eventloop thread.
503
+ """
504
+ session_info = self._session_mgr.get_active_session_info(session_id)
505
+ if session_info:
506
+ self._session_mgr.disconnect_session(session_id)
507
+ self._on_session_disconnected()
508
+
509
+ def handle_backmsg(self, session_id: str, msg: BackMsg) -> None:
510
+ """Send a BackMsg to an active session.
511
+
512
+ Parameters
513
+ ----------
514
+ session_id
515
+ The session's unique ID.
516
+ msg
517
+ The BackMsg to deliver to the session.
518
+
519
+ Notes
520
+ -----
521
+ Threading: UNSAFE. Must be called on the eventloop thread.
522
+ """
523
+ if self._state in {RuntimeState.STOPPING, RuntimeState.STOPPED}:
524
+ raise RuntimeStoppedError(f"Can't handle_backmsg (state={self._state})")
525
+
526
+ session_info = self._session_mgr.get_active_session_info(session_id)
527
+ if session_info is None:
528
+ _LOGGER.debug(
529
+ "Discarding BackMsg for disconnected session (id=%s)", session_id
530
+ )
531
+ return
532
+
533
+ session_info.session.handle_backmsg(msg)
534
+
535
+ def handle_backmsg_deserialization_exception(
536
+ self, session_id: str, exc: BaseException
537
+ ) -> None:
538
+ """Handle an Exception raised during deserialization of a BackMsg.
539
+
540
+ Parameters
541
+ ----------
542
+ session_id
543
+ The session's unique ID.
544
+ exc
545
+ The Exception.
546
+
547
+ Notes
548
+ -----
549
+ Threading: UNSAFE. Must be called on the eventloop thread.
550
+ """
551
+ if self._state in {RuntimeState.STOPPING, RuntimeState.STOPPED}:
552
+ raise RuntimeStoppedError(
553
+ f"Can't handle_backmsg_deserialization_exception (state={self._state})"
554
+ )
555
+
556
+ session_info = self._session_mgr.get_active_session_info(session_id)
557
+ if session_info is None:
558
+ _LOGGER.debug(
559
+ "Discarding BackMsg Exception for disconnected session (id=%s)",
560
+ session_id,
561
+ )
562
+ return
563
+
564
+ session_info.session.handle_backmsg_exception(exc)
565
+
566
+ @property
567
+ async def is_ready_for_browser_connection(self) -> tuple[bool, str]:
568
+ if self._state not in {
569
+ RuntimeState.INITIAL,
570
+ RuntimeState.STOPPING,
571
+ RuntimeState.STOPPED,
572
+ }:
573
+ return True, "ok"
574
+
575
+ return False, "unavailable"
576
+
577
+ async def does_script_run_without_error(self) -> tuple[bool, str]:
578
+ """Load and execute the app's script to verify it runs without an error.
579
+
580
+ Returns
581
+ -------
582
+ (True, "ok") if the script completes without error, or (False, err_msg)
583
+ if the script raises an exception.
584
+
585
+ Notes
586
+ -----
587
+ Threading: UNSAFE. Must be called on the eventloop thread.
588
+ """
589
+ # NOTE: We create an AppSession directly here instead of using the
590
+ # SessionManager intentionally. This isn't a "real" session and is only being
591
+ # used to test that the script runs without error.
592
+ session = AppSession(
593
+ script_data=ScriptData(self._main_script_path, self._is_hello),
594
+ uploaded_file_manager=self._uploaded_file_mgr,
595
+ script_cache=self._script_cache,
596
+ message_enqueued_callback=self._enqueued_some_message,
597
+ user_info={"email": "test@example.com"},
598
+ )
599
+
600
+ try:
601
+ session.request_rerun(None)
602
+
603
+ now = time.perf_counter()
604
+ while ( # noqa: ASYNC110
605
+ SCRIPT_RUN_WITHOUT_ERRORS_KEY not in session.session_state
606
+ and (time.perf_counter() - now) < SCRIPT_RUN_CHECK_TIMEOUT
607
+ ):
608
+ await asyncio.sleep(0.1)
609
+
610
+ if SCRIPT_RUN_WITHOUT_ERRORS_KEY not in session.session_state:
611
+ return False, "timeout"
612
+
613
+ ok = session.session_state[SCRIPT_RUN_WITHOUT_ERRORS_KEY]
614
+ msg = "ok" if ok else "error"
615
+
616
+ return ok, msg
617
+ finally:
618
+ session.shutdown()
619
+
620
+ def _set_state(self, new_state: RuntimeState) -> None:
621
+ _LOGGER.debug("Runtime state: %s -> %s", self._state, new_state)
622
+ self._state = new_state
623
+
624
+ async def _loop_coroutine(self) -> None:
625
+ """The main Runtime loop.
626
+
627
+ This function won't exit until `stop` is called.
628
+
629
+ Notes
630
+ -----
631
+ Threading: UNSAFE. Must be called on the eventloop thread.
632
+ """
633
+
634
+ async_objs = self._get_async_objs()
635
+
636
+ try:
637
+ if self._state == RuntimeState.INITIAL:
638
+ self._set_state(RuntimeState.NO_SESSIONS_CONNECTED)
639
+ elif self._state == RuntimeState.ONE_OR_MORE_SESSIONS_CONNECTED:
640
+ pass
641
+ else:
642
+ raise RuntimeError(f"Bad Runtime state at start: {self._state}") # noqa: TRY301
643
+
644
+ # Signal that we're started and ready to accept sessions
645
+ async_objs.started.set_result(None)
646
+
647
+ while not async_objs.must_stop.is_set():
648
+ if self._state == RuntimeState.NO_SESSIONS_CONNECTED: # type: ignore[comparison-overlap]
649
+ # mypy 1.4 incorrectly thinks this if-clause is unreachable,
650
+ # because it thinks self._state must be INITIAL | ONE_OR_MORE_SESSIONS_CONNECTED.
651
+
652
+ # Wait for new websocket connections (new sessions):
653
+ done_tasks, pending_tasks = await asyncio.wait( # type: ignore[unreachable]
654
+ (
655
+ asyncio.create_task(async_objs.must_stop.wait()),
656
+ asyncio.create_task(async_objs.has_connection.wait()),
657
+ ),
658
+ return_when=asyncio.FIRST_COMPLETED,
659
+ # On Windows, use a timeout to ensure signal handlers can be processed
660
+ timeout=_SIGNAL_CHECK_INTERVAL,
661
+ )
662
+ # Clean up pending tasks to avoid memory leaks
663
+ for task in pending_tasks:
664
+ task.cancel()
665
+
666
+ # If we timed out (Windows only), continue the loop to check must_stop
667
+ if not done_tasks and _SIGNAL_CHECK_INTERVAL is not None:
668
+ continue
669
+ elif self._state == RuntimeState.ONE_OR_MORE_SESSIONS_CONNECTED:
670
+ async_objs.need_send_data.clear()
671
+
672
+ for active_session_info in self._session_mgr.list_active_sessions():
673
+ msg_list = active_session_info.session.flush_browser_queue()
674
+ for msg in msg_list:
675
+ try:
676
+ self._send_message(active_session_info, msg)
677
+ except SessionClientDisconnectedError:
678
+ self._session_mgr.disconnect_session(
679
+ active_session_info.session.id
680
+ )
681
+
682
+ # Yield for a tick after sending a message.
683
+ await asyncio.sleep(0)
684
+
685
+ # Yield briefly between session message flushing cycles.
686
+ await asyncio.sleep(MESSAGE_FLUSH_INTERVAL_SECS)
687
+ else:
688
+ # Break out of the thread loop if we encounter any other state.
689
+ break
690
+
691
+ # Wait for new proto messages that need to be sent out:
692
+ done_tasks, pending_tasks = await asyncio.wait(
693
+ (
694
+ asyncio.create_task(async_objs.must_stop.wait()),
695
+ asyncio.create_task(async_objs.need_send_data.wait()),
696
+ ),
697
+ return_when=asyncio.FIRST_COMPLETED,
698
+ # On Windows, use a timeout to ensure signal handlers can be processed
699
+ timeout=_SIGNAL_CHECK_INTERVAL,
700
+ )
701
+ # We need to cancel the pending tasks (the `must_stop` one in most situations).
702
+ # Otherwise, this would stack up one waiting task per loop
703
+ # (e.g. per forward message). These tasks cannot be garbage collected
704
+ # causing an increase in memory (-> memory leak).
705
+ for task in pending_tasks:
706
+ task.cancel()
707
+
708
+ # If we timed out (Windows only), continue to check must_stop
709
+ if not done_tasks and _SIGNAL_CHECK_INTERVAL is not None:
710
+ continue
711
+
712
+ # Shut down all AppSessions.
713
+ for session_info in self._session_mgr.list_sessions():
714
+ # NOTE: We want to fully shut down sessions when the runtime stops for
715
+ # now, but this may change in the future if/when our notion of a session
716
+ # is no longer so tightly coupled to a browser tab.
717
+ self._session_mgr.close_session(session_info.session.id)
718
+
719
+ self._set_state(RuntimeState.STOPPED)
720
+ async_objs.stopped.set_result(None)
721
+
722
+ except Exception as e:
723
+ async_objs.stopped.set_exception(e)
724
+ traceback.print_exc()
725
+ _LOGGER.info(
726
+ """
727
+ Please report this bug at https://github.com/streamlit/streamlit/issues.
728
+ """
729
+ )
730
+
731
+ def _send_message(self, session_info: ActiveSessionInfo, msg: ForwardMsg) -> None:
732
+ """Send a message to a client.
733
+ If the client is likely to have already cached the message, we may
734
+ instead send a "reference" message that contains only the hash of the
735
+ message.
736
+
737
+ Parameters
738
+ ----------
739
+ session_info : ActiveSessionInfo
740
+ The ActiveSessionInfo associated with websocket
741
+ msg : ForwardMsg
742
+ The message to send to the client
743
+
744
+ Notes
745
+ -----
746
+ Threading: UNSAFE. Must be called on the eventloop thread.
747
+ """
748
+
749
+ # If this was a `script_finished` message, we increment the
750
+ # script_run_count for this session
751
+ if msg.WhichOneof("type") == "script_finished" and (
752
+ msg.script_finished == ForwardMsg.FINISHED_SUCCESSFULLY
753
+ ):
754
+ session_info.script_run_count += 1
755
+
756
+ # Ship it off!
757
+ session_info.client.write_forward_msg(msg)
758
+
759
+ def _enqueued_some_message(self) -> None:
760
+ """Callback called by AppSession after the AppSession has enqueued a
761
+ message. Sets the "needs_send_data" event, which causes our core
762
+ loop to wake up and flush client message queues.
763
+
764
+ Notes
765
+ -----
766
+ Threading: SAFE. May be called on any thread.
767
+ """
768
+ async_objs = self._get_async_objs()
769
+ async_objs.eventloop.call_soon_threadsafe(async_objs.need_send_data.set)
770
+
771
+ def _get_async_objs(self) -> AsyncObjects:
772
+ """Return our AsyncObjects instance. If the Runtime hasn't been
773
+ started, this will raise an error.
774
+ """
775
+ if self._async_objs is None:
776
+ raise RuntimeError("Runtime hasn't started yet!")
777
+ return self._async_objs
778
+
779
+ def _on_session_disconnected(self) -> None:
780
+ """Set the runtime state to NO_SESSIONS_CONNECTED if the last active
781
+ session was disconnected.
782
+ """
783
+ if (
784
+ self._state == RuntimeState.ONE_OR_MORE_SESSIONS_CONNECTED
785
+ and self._session_mgr.num_active_sessions() == 0
786
+ ):
787
+ self._get_async_objs().has_connection.clear()
788
+ self._set_state(RuntimeState.NO_SESSIONS_CONNECTED)
venv/Lib/site-packages/streamlit/runtime/runtime_util.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Runtime-related utility functions."""
16
+
17
+ from __future__ import annotations
18
+
19
+ from logging import getLogger
20
+ from typing import TYPE_CHECKING, Any, Final, cast
21
+
22
+ from streamlit import config
23
+ from streamlit.errors import MarkdownFormattedException, StreamlitAPIException
24
+
25
+ if TYPE_CHECKING:
26
+ from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
27
+
28
+ _LOGGER: Final = getLogger(__name__)
29
+
30
+ # The interval (in seconds) between message flush cycles in the runtime event loop.
31
+ # Also reused by callers that need to wait for outstanding messages to be delivered
32
+ # before requesting a rerun (e.g. `st.switch_page`).
33
+ #
34
+ # Message coalescing is implemented at the queue level (`_maybe_compose_delta_msgs`),
35
+ # but this interval is the window during which it can happen. A small non-zero value
36
+ # is important for single-element placeholders like `st.empty` and `st.skeleton`:
37
+ # when a placeholder is shown and then replaced within the same run, both deltas
38
+ # share a delta_path and coalesce into the final element, so the browser never
39
+ # renders the intermediate state. A too-small interval can flush the placeholder
40
+ # first and briefly unmount/remount the real element (e.g. flash a skeleton) on
41
+ # reruns.
42
+ MESSAGE_FLUSH_INTERVAL_SECS: Final[float] = 0.005
43
+
44
+
45
+ class MessageSizeError(MarkdownFormattedException):
46
+ """Exception raised when a websocket message is larger than the configured limit."""
47
+
48
+ def __init__(self, failed_msg_str: Any) -> None:
49
+ msg = self._get_message(failed_msg_str)
50
+ super().__init__(msg)
51
+
52
+ def _get_message(self, failed_msg_str: Any) -> str:
53
+ # This needs to have zero indentation otherwise the markdown will render incorrectly.
54
+ return (
55
+ f"""
56
+ **Data of size {len(failed_msg_str) / 1e6:.1f} MB exceeds the message size limit of
57
+ {get_max_message_size_bytes() / 1e6} MB.**
58
+
59
+ This is often caused by a large chart or dataframe. Please decrease the amount of data sent
60
+ to the browser, or increase the limit by setting the config option `server.maxMessageSize`.
61
+ [Click here to learn more about config options](https://docs.streamlit.io/develop/api-reference/configuration/config.toml).
62
+
63
+ _Note that increasing the limit may lead to long loading times and large memory consumption
64
+ of the client's browser and the Streamlit server._
65
+ """
66
+ ).strip("\n")
67
+
68
+
69
+ class WidgetStateSizeError(MarkdownFormattedException):
70
+ """Exception raised when client-sent widget state is larger than the limit."""
71
+
72
+ def __init__(self, failed_msg_size: int) -> None:
73
+ msg = self._get_message(failed_msg_size)
74
+ super().__init__(msg)
75
+
76
+ def _get_message(self, failed_msg_size: int) -> str:
77
+ # This needs to have zero indentation otherwise the markdown will render incorrectly.
78
+ return (
79
+ f"""
80
+ **Widget state of size {failed_msg_size / 1e6:.1f} MB exceeds the widget state size limit of
81
+ {get_max_widget_state_size_bytes() / 1e6} MB.**
82
+
83
+ This can happen when a widget or custom component sends a large value to Streamlit.
84
+ Please decrease the amount of data sent from the browser, or increase the limit by
85
+ setting the config option `server.maxWidgetStateSize`.
86
+ [Click here to learn more about config options](https://docs.streamlit.io/develop/api-reference/configuration/config.toml).
87
+
88
+ _Note that increasing the limit may lead to long loading times and large memory consumption
89
+ of the Streamlit server._
90
+ """
91
+ ).strip("\n")
92
+
93
+
94
+ class BadDurationStringError(StreamlitAPIException):
95
+ """Raised when a bad duration argument string is passed."""
96
+
97
+ def __init__(self, duration: str) -> None:
98
+ MarkdownFormattedException.__init__(
99
+ self,
100
+ "TTL string doesn't look right. It should be formatted as"
101
+ f"`'1d2h34m'` or `2 days`, for example. Got: {duration}",
102
+ )
103
+
104
+
105
+ def serialize_forward_msg(msg: ForwardMsg) -> bytes:
106
+ """Serialize a ForwardMsg to send to a client.
107
+
108
+ If the message is too large, it will be converted to an exception message
109
+ instead.
110
+ """
111
+
112
+ msg_str = msg.SerializeToString()
113
+
114
+ if len(msg_str) > get_max_message_size_bytes():
115
+ # Overwrite the offending ForwardMsg.delta with an error to display.
116
+ # This assumes that the size limit wasn't exceeded due to metadata.
117
+ from streamlit.elements import exception
118
+
119
+ msg_size_error = MessageSizeError(msg_str)
120
+ _LOGGER.warning(
121
+ "Websocket message size limit exceeded. Showing error to the user: %s",
122
+ msg_size_error,
123
+ )
124
+ exception.marshall(msg.delta.new_element.exception, msg_size_error)
125
+ # Deactivate caching for this error message:
126
+ msg.metadata.cacheable = False
127
+ msg_str = msg.SerializeToString()
128
+
129
+ return msg_str
130
+
131
+
132
+ # This needs to be initialized lazily to avoid calling config.get_option() and
133
+ # thus initializing config options when this file is first imported.
134
+ _max_message_size_bytes: int | None = None
135
+ _max_widget_state_size_bytes: int | None = None
136
+
137
+
138
+ def get_max_message_size_bytes() -> int:
139
+ """Returns the max websocket message size in bytes.
140
+
141
+ This will lazyload the value from the config and store it in the global symbol table.
142
+ """
143
+ global _max_message_size_bytes # noqa: PLW0603
144
+
145
+ if _max_message_size_bytes is None:
146
+ _max_message_size_bytes = config.get_option("server.maxMessageSize") * int(1e6)
147
+
148
+ return cast("int", _max_message_size_bytes)
149
+
150
+
151
+ def get_max_widget_state_size_bytes() -> int:
152
+ """Returns the max client-sent message size in bytes.
153
+
154
+ This limit is applied both to raw inbound WebSocket frames in the Starlette
155
+ handler and to the aggregate widget state protobuf in the runtime layer.
156
+
157
+ This will lazyload the value from the config and store it in the global symbol table.
158
+ """
159
+ global _max_widget_state_size_bytes # noqa: PLW0603
160
+
161
+ if _max_widget_state_size_bytes is None:
162
+ _max_widget_state_size_bytes = config.get_option(
163
+ "server.maxWidgetStateSize"
164
+ ) * int(1e6)
165
+
166
+ return cast("int", _max_widget_state_size_bytes)
venv/Lib/site-packages/streamlit/runtime/script_data.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ from dataclasses import dataclass, field
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ScriptData:
23
+ """Contains parameters related to running a script."""
24
+
25
+ main_script_path: str
26
+ is_hello: bool = False
27
+ script_folder: str = field(init=False)
28
+ name: str = field(init=False)
29
+
30
+ def __post_init__(self) -> None:
31
+ """Set some computed values derived from main_script_path.
32
+
33
+ The usage of object.__setattr__ is necessary because trying to set
34
+ self.script_folder or self.name normally, even within the __init__ method, will
35
+ explode since we declared this dataclass to be frozen.
36
+
37
+ We do this in __post_init__ so that we can use the auto-generated __init__
38
+ method that most dataclasses use.
39
+ """
40
+ main_script_path = os.path.abspath(self.main_script_path)
41
+ script_folder = os.path.dirname(main_script_path)
42
+ object.__setattr__(self, "script_folder", script_folder)
43
+
44
+ basename = os.path.basename(main_script_path)
45
+ name = str(os.path.splitext(basename)[0])
46
+ object.__setattr__(self, "name", name)
venv/Lib/site-packages/streamlit/runtime/scriptrunner/__init__.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from streamlit.runtime.scriptrunner.script_runner import ScriptRunner, ScriptRunnerEvent
16
+ from streamlit.runtime.scriptrunner_utils.exceptions import (
17
+ RerunException,
18
+ StopException,
19
+ )
20
+ from streamlit.runtime.scriptrunner_utils.script_requests import RerunData
21
+ from streamlit.runtime.scriptrunner_utils.script_run_context import (
22
+ ScriptRunContext,
23
+ add_script_run_ctx,
24
+ enqueue_message,
25
+ get_script_run_ctx,
26
+ )
27
+
28
+ __all__ = [
29
+ "RerunData",
30
+ "RerunException",
31
+ "ScriptRunContext",
32
+ "ScriptRunner",
33
+ "ScriptRunnerEvent",
34
+ "StopException",
35
+ "add_script_run_ctx",
36
+ "enqueue_message",
37
+ "get_script_run_ctx",
38
+ ]
venv/Lib/site-packages/streamlit/runtime/scriptrunner/__pycache__/__init__.cpython-314.pyc ADDED
Binary file (759 Bytes). View file
 
venv/Lib/site-packages/streamlit/runtime/scriptrunner/__pycache__/exec_code.cpython-314.pyc ADDED
Binary file (5.79 kB). View file
 
venv/Lib/site-packages/streamlit/runtime/scriptrunner/__pycache__/magic.cpython-314.pyc ADDED
Binary file (10.9 kB). View file
 
venv/Lib/site-packages/streamlit/runtime/scriptrunner/__pycache__/magic_funcs.cpython-314.pyc ADDED
Binary file (960 Bytes). View file
 
venv/Lib/site-packages/streamlit/runtime/scriptrunner/__pycache__/script_cache.cpython-314.pyc ADDED
Binary file (3.31 kB). View file
 
venv/Lib/site-packages/streamlit/runtime/scriptrunner/__pycache__/script_runner.cpython-314.pyc ADDED
Binary file (33.1 kB). View file
 
venv/Lib/site-packages/streamlit/runtime/scriptrunner/exec_code.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import sys
18
+ from typing import TYPE_CHECKING, Any, Literal
19
+
20
+ from streamlit import util
21
+ from streamlit.delta_generator_singletons import (
22
+ context_dg_stack,
23
+ get_default_dg_stack_value,
24
+ )
25
+ from streamlit.error_util import handle_user_script_exception
26
+ from streamlit.errors import FragmentHandledException
27
+ from streamlit.runtime.scriptrunner_utils.exceptions import (
28
+ RerunException,
29
+ StopException,
30
+ )
31
+
32
+ if TYPE_CHECKING:
33
+ from collections.abc import Callable
34
+ from types import TracebackType
35
+
36
+ from streamlit.runtime.scriptrunner_utils.script_requests import RerunData
37
+ from streamlit.runtime.scriptrunner_utils.script_run_context import ScriptRunContext
38
+
39
+
40
+ class modified_sys_path: # noqa: N801
41
+ """A context for prepending a directory to sys.path for a second.
42
+
43
+ Code inspired by IPython:
44
+ Source: https://github.com/ipython/ipython/blob/master/IPython/utils/syspathcontext.py#L42
45
+ """
46
+
47
+ def __init__(self, main_script_path: str) -> None:
48
+ self._main_script_path = main_script_path
49
+ self._added_path = False
50
+
51
+ def __repr__(self) -> str:
52
+ return util.repr_(self)
53
+
54
+ def __enter__(self) -> None:
55
+ if self._main_script_path not in sys.path:
56
+ sys.path.insert(0, self._main_script_path)
57
+ self._added_path = True
58
+
59
+ def __exit__(
60
+ self,
61
+ typ: type[BaseException] | None,
62
+ exc: BaseException | None,
63
+ tb: TracebackType | None,
64
+ ) -> Literal[False]:
65
+ if self._added_path:
66
+ try:
67
+ sys.path.remove(self._main_script_path)
68
+ except ValueError:
69
+ # It's already removed.
70
+ pass
71
+
72
+ # Returning False causes any exceptions to be re-raised.
73
+ return False
74
+
75
+
76
+ def exec_func_with_error_handling(
77
+ func: Callable[[], Any], ctx: ScriptRunContext
78
+ ) -> tuple[
79
+ Any | None,
80
+ bool,
81
+ RerunData | None,
82
+ bool,
83
+ Exception | None,
84
+ ]:
85
+ """Execute the passed function wrapped in a try/except block.
86
+
87
+ This function is called by the script runner to execute the user's script or
88
+ fragment reruns, but also for the execution of fragment code in context of a normal
89
+ app run. This wrapper ensures that handle_uncaught_exception messages show up in the
90
+ correct context.
91
+
92
+ Parameters
93
+ ----------
94
+ func : callable
95
+ The function to execute wrapped in the try/except block.
96
+ ctx : ScriptRunContext
97
+ The context in which the script is being run.
98
+
99
+ Returns
100
+ -------
101
+ tuple
102
+ A tuple containing:
103
+ - The result of the passed function.
104
+ - A boolean indicating whether the script ran without errors (RerunException and
105
+ StopException don't count as errors).
106
+ - The RerunData instance belonging to a RerunException if the script was
107
+ interrupted by a RerunException.
108
+ - A boolean indicating whether the script was stopped prematurely (False for
109
+ RerunExceptions, True for all other exceptions).
110
+ - The uncaught exception if one occurred, None otherwise
111
+ """
112
+ run_without_errors = True
113
+
114
+ # This will be set to a RerunData instance if our execution
115
+ # is interrupted by a RerunException.
116
+ rerun_exception_data: RerunData | None = None
117
+
118
+ # If the script stops early, we don't want to remove unseen widgets,
119
+ # so we track this to potentially skip session state cleanup later.
120
+ premature_stop: bool = False
121
+
122
+ # The result of the passed function
123
+ result: Any | None = None
124
+
125
+ # The uncaught exception if one occurred, None otherwise
126
+ uncaught_exception: Exception | None = None
127
+
128
+ try:
129
+ result = func()
130
+ except RerunException as e:
131
+ rerun_exception_data = e.rerun_data
132
+
133
+ # Since the script is about to rerun, we may need to reset our cursors/dg_stack
134
+ # so that we write to the right place in the app. For full script runs, this
135
+ # needs to happen in case the same thread reruns our script (a different thread
136
+ # would automatically come with fresh cursors/dg_stack values). For fragments,
137
+ # it doesn't matter either way since the fragment resets these values from its
138
+ # snapshot before execution.
139
+ ctx.cursors.clear()
140
+ context_dg_stack.set(get_default_dg_stack_value())
141
+
142
+ # Interruption due to a rerun is usually from `st.rerun()`, which
143
+ # we want to count as a script completion so triggers reset.
144
+ # It is also possible for this to happen if fast reruns is off,
145
+ # but this is very rare.
146
+ premature_stop = False
147
+
148
+ except StopException:
149
+ # This is thrown when the script executes `st.stop()`.
150
+ # We don't have to do anything here.
151
+ premature_stop = True
152
+ except FragmentHandledException:
153
+ run_without_errors = False
154
+ premature_stop = True
155
+ except Exception as ex:
156
+ run_without_errors = False
157
+ premature_stop = True
158
+ uncaught_exception = ex
159
+ handle_user_script_exception(ex, ctx.on_script_error)
160
+
161
+ return (
162
+ result,
163
+ run_without_errors,
164
+ rerun_exception_data,
165
+ premature_stop,
166
+ uncaught_exception,
167
+ )
venv/Lib/site-packages/streamlit/runtime/scriptrunner/magic.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import ast
18
+ import sys
19
+ from typing import Any, Final
20
+
21
+ from streamlit import config
22
+
23
+ # When a Streamlit app is magicified, we insert a `magic_funcs` import near the top of
24
+ # its module's AST: import streamlit.runtime.scriptrunner.magic_funcs as __streamlitmagic__
25
+ MAGIC_MODULE_NAME: Final = "__streamlitmagic__"
26
+
27
+
28
+ def add_magic(code: str, script_path: str) -> Any:
29
+ """Modifies the code to support magic Streamlit commands.
30
+
31
+ Parameters
32
+ ----------
33
+ code : str
34
+ The Python code.
35
+ script_path : str
36
+ The path to the script file.
37
+
38
+ Returns
39
+ -------
40
+ ast.Module
41
+ The syntax tree for the code.
42
+
43
+ """
44
+ # Pass script_path so we get pretty exceptions.
45
+ tree = ast.parse(code, script_path, "exec")
46
+
47
+ file_ends_in_semicolon = _does_file_end_in_semicolon(tree, code)
48
+
49
+ _modify_ast_subtree(
50
+ tree, is_root=True, file_ends_in_semicolon=file_ends_in_semicolon
51
+ )
52
+
53
+ return tree
54
+
55
+
56
+ def _modify_ast_subtree(
57
+ tree: Any,
58
+ body_attr: str = "body",
59
+ is_root: bool = False,
60
+ file_ends_in_semicolon: bool = False,
61
+ ) -> None:
62
+ """Parses magic commands and modifies the given AST (sub)tree."""
63
+
64
+ body = getattr(tree, body_attr)
65
+
66
+ for i, node in enumerate(body):
67
+ node_type = type(node)
68
+
69
+ # Recursively parses the content of the statements
70
+ # `with` as well as function definitions.
71
+ # Also covers their async counterparts
72
+ if (
73
+ node_type is ast.FunctionDef
74
+ or node_type is ast.With
75
+ or node_type is ast.AsyncFunctionDef
76
+ or node_type is ast.AsyncWith
77
+ ):
78
+ _modify_ast_subtree(node)
79
+
80
+ # Recursively parses the content of the statements
81
+ # `for` and `while`.
82
+ # Also covers their async counterparts
83
+ elif (
84
+ node_type is ast.For or node_type is ast.While or node_type is ast.AsyncFor
85
+ ):
86
+ _modify_ast_subtree(node)
87
+ _modify_ast_subtree(node, "orelse")
88
+
89
+ # Recursively parses methods in a class.
90
+ elif node_type is ast.ClassDef:
91
+ for inner_node in node.body:
92
+ if type(inner_node) in {ast.FunctionDef, ast.AsyncFunctionDef}:
93
+ _modify_ast_subtree(inner_node)
94
+
95
+ # Recursively parses the contents of try statements,
96
+ # all their handlers (except and else) and the finally body
97
+ elif node_type is ast.Try or (
98
+ sys.version_info >= (3, 11) and node_type is ast.TryStar
99
+ ):
100
+ _modify_ast_subtree(node)
101
+ _modify_ast_subtree(node, body_attr="finalbody")
102
+ _modify_ast_subtree(node, body_attr="orelse")
103
+ for handler_node in node.handlers:
104
+ _modify_ast_subtree(handler_node)
105
+
106
+ # Recursively parses if blocks, as well as their else/elif blocks
107
+ # (else/elif are both mapped to orelse)
108
+ # it intentionally does not parse the test expression.
109
+ elif node_type is ast.If:
110
+ _modify_ast_subtree(node)
111
+ _modify_ast_subtree(node, "orelse")
112
+
113
+ elif sys.version_info >= (3, 10) and node_type is ast.Match:
114
+ for case_node in node.cases:
115
+ _modify_ast_subtree(case_node)
116
+
117
+ # Convert standalone expression nodes to st.write
118
+ elif node_type is ast.Expr:
119
+ value = _get_st_write_from_expr(
120
+ node,
121
+ i,
122
+ parent_type=type(tree),
123
+ is_root=is_root,
124
+ is_last_expr=(i == len(body) - 1),
125
+ file_ends_in_semicolon=file_ends_in_semicolon,
126
+ )
127
+ if value is not None:
128
+ node.value = value
129
+
130
+ if is_root:
131
+ # Import Streamlit so we can use it in the new_value above.
132
+ _insert_import_statement(tree)
133
+
134
+ ast.fix_missing_locations(tree)
135
+
136
+
137
+ def _insert_import_statement(tree: Any) -> None:
138
+ """Insert Streamlit import statement at the top(ish) of the tree."""
139
+
140
+ st_import = _build_st_import_statement()
141
+
142
+ # If the 0th node is already an import statement, put the Streamlit
143
+ # import below that, so we don't break "from __future__ import".
144
+ if tree.body and type(tree.body[0]) in {ast.ImportFrom, ast.Import}:
145
+ tree.body.insert(1, st_import)
146
+
147
+ # If the 0th node is a docstring and the 1st is an import statement,
148
+ # put the Streamlit import below those, so we don't break "from
149
+ # __future__ import".
150
+ elif (
151
+ len(tree.body) > 1
152
+ and (
153
+ type(tree.body[0]) is ast.Expr
154
+ and _is_string_constant_node(tree.body[0].value)
155
+ )
156
+ and type(tree.body[1]) in {ast.ImportFrom, ast.Import}
157
+ ):
158
+ tree.body.insert(2, st_import)
159
+
160
+ else:
161
+ tree.body.insert(0, st_import)
162
+
163
+
164
+ def _build_st_import_statement() -> ast.Import:
165
+ """Build AST node for `import magic_funcs as __streamlitmagic__`."""
166
+ return ast.Import(
167
+ names=[
168
+ ast.alias(
169
+ name="streamlit.runtime.scriptrunner.magic_funcs",
170
+ asname=MAGIC_MODULE_NAME,
171
+ )
172
+ ]
173
+ )
174
+
175
+
176
+ def _build_st_write_call(nodes: list[Any]) -> ast.Call:
177
+ """Build AST node for `__streamlitmagic__.transparent_write(*nodes)`."""
178
+ return ast.Call(
179
+ func=ast.Attribute(
180
+ attr="transparent_write",
181
+ value=ast.Name(id=MAGIC_MODULE_NAME, ctx=ast.Load()),
182
+ ctx=ast.Load(),
183
+ ),
184
+ args=nodes,
185
+ keywords=[],
186
+ )
187
+
188
+
189
+ def _get_st_write_from_expr(
190
+ node: Any,
191
+ i: int,
192
+ parent_type: Any,
193
+ is_root: bool,
194
+ is_last_expr: bool,
195
+ file_ends_in_semicolon: bool,
196
+ ) -> ast.Call | None:
197
+ # Don't wrap function calls
198
+ # (Unless the function call happened at the end of the root node, AND
199
+ # magic.displayLastExprIfNoSemicolon is True. This allows us to support notebook-like
200
+ # behavior, where we display the last function in a cell)
201
+ if type(node.value) is ast.Call and not _is_displayable_last_expr(
202
+ is_root, is_last_expr, file_ends_in_semicolon
203
+ ):
204
+ return None
205
+
206
+ # Don't wrap DocString nodes
207
+ # (Unless magic.displayRootDocString, in which case we do wrap the root-level
208
+ # docstring with st.write. This allows us to support notebook-like behavior
209
+ # where you can have a cell with a markdown string)
210
+ if _is_docstring_node(
211
+ node.value, i, parent_type
212
+ ) and not _should_display_docstring_like_node_anyway(is_root):
213
+ return None
214
+
215
+ # Don't wrap yield nodes
216
+ if type(node.value) is ast.Yield or type(node.value) is ast.YieldFrom:
217
+ return None
218
+
219
+ # Don't wrap await nodes
220
+ if type(node.value) is ast.Await:
221
+ return None
222
+
223
+ # If tuple, call st.write(*the_tuple). This allows us to add a comma at the end of a
224
+ # statement to turn it into an expression that should be
225
+ # st-written. Ex: "np.random.randn(1000, 2),"
226
+ args = node.value.elts if type(node.value) is ast.Tuple else [node.value]
227
+ return _build_st_write_call(args)
228
+
229
+
230
+ def _is_string_constant_node(node: Any) -> bool:
231
+ return isinstance(node, ast.Constant) and isinstance(node.value, str)
232
+
233
+
234
+ def _is_docstring_node(node: Any, node_index: int, parent_type: Any) -> bool:
235
+ return (
236
+ node_index == 0
237
+ and _is_string_constant_node(node)
238
+ and parent_type in {ast.FunctionDef, ast.AsyncFunctionDef, ast.Module}
239
+ )
240
+
241
+
242
+ def _does_file_end_in_semicolon(tree: Any, code: str) -> bool:
243
+ file_ends_in_semicolon = False
244
+
245
+ # Avoid spending time with this operation if magic.displayLastExprIfNoSemicolon is
246
+ # not set.
247
+ if config.get_option("magic.displayLastExprIfNoSemicolon"):
248
+ if len(tree.body) == 0:
249
+ return False
250
+
251
+ last_line_num = getattr(tree.body[-1], "end_lineno", None)
252
+
253
+ if last_line_num is not None:
254
+ last_line_str: str = code.split("\n")[last_line_num - 1]
255
+ file_ends_in_semicolon = last_line_str.strip(" ").endswith(";")
256
+
257
+ return file_ends_in_semicolon
258
+
259
+
260
+ def _is_displayable_last_expr(
261
+ is_root: bool, is_last_expr: bool, file_ends_in_semicolon: bool
262
+ ) -> bool:
263
+ return (
264
+ # This is a "displayable last expression" if...
265
+ # ...it's actually the last expression...
266
+ is_last_expr
267
+ # ...in the root scope...
268
+ and is_root
269
+ # ...it does not end in a semicolon...
270
+ and not file_ends_in_semicolon
271
+ # ...and this config option is telling us to show it
272
+ and config.get_option("magic.displayLastExprIfNoSemicolon")
273
+ )
274
+
275
+
276
+ def _should_display_docstring_like_node_anyway(is_root: bool) -> bool:
277
+ return config.get_option("magic.displayRootDocString") and is_root
venv/Lib/site-packages/streamlit/runtime/scriptrunner/magic_funcs.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import Any
18
+
19
+ from streamlit.runtime.metrics_util import gather_metrics
20
+
21
+
22
+ @gather_metrics("magic")
23
+ def transparent_write(*args: Any) -> Any:
24
+ """The function that gets magic-ified into Streamlit apps.
25
+ This is just st.write, but returns the arguments you passed to it.
26
+ """
27
+ import streamlit as st
28
+
29
+ st.write(*args)
30
+ if len(args) == 1:
31
+ return args[0]
32
+ return args
venv/Lib/site-packages/streamlit/runtime/scriptrunner/script_cache.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import os.path
18
+ import threading
19
+ from typing import Any
20
+
21
+ from streamlit import config
22
+ from streamlit.runtime.scriptrunner import magic
23
+ from streamlit.source_util import open_python_file
24
+
25
+
26
+ class ScriptCache:
27
+ """Thread-safe cache of Python script bytecode."""
28
+
29
+ def __init__(self) -> None:
30
+ # Mapping of script_path: bytecode
31
+ self._cache: dict[str, Any] = {}
32
+ self._lock = threading.Lock()
33
+
34
+ def clear(self) -> None:
35
+ """Remove all entries from the cache.
36
+
37
+ Notes
38
+ -----
39
+ Threading: SAFE. May be called on any thread.
40
+ """
41
+ with self._lock:
42
+ self._cache.clear()
43
+
44
+ def get_bytecode(self, script_path: str) -> Any:
45
+ """Return the bytecode for the Python script at the given path.
46
+
47
+ If the bytecode is not already in the cache, the script will be
48
+ compiled first.
49
+
50
+ Raises
51
+ ------
52
+ Any Exception raised while reading or compiling the script.
53
+
54
+ Notes
55
+ -----
56
+ Threading: SAFE. May be called on any thread.
57
+ """
58
+
59
+ script_path = os.path.abspath(script_path)
60
+
61
+ with self._lock:
62
+ bytecode = self._cache.get(script_path, None)
63
+ if bytecode is not None:
64
+ # Fast path: the code is already cached.
65
+ return bytecode
66
+
67
+ # Populate the cache
68
+ with open_python_file(script_path) as f:
69
+ filebody = f.read()
70
+
71
+ if config.get_option("runner.magicEnabled"):
72
+ filebody = magic.add_magic(filebody, script_path)
73
+
74
+ bytecode = compile( # type: ignore
75
+ filebody,
76
+ # Pass in the file path so it can show up in exceptions.
77
+ script_path,
78
+ # We're compiling entire blocks of Python, so we need "exec"
79
+ # mode (as opposed to "eval" or "single").
80
+ mode="exec",
81
+ # Don't inherit any flags or "future" statements.
82
+ flags=0,
83
+ dont_inherit=1,
84
+ # Use the default optimization options.
85
+ optimize=-1,
86
+ )
87
+
88
+ self._cache[script_path] = bytecode
89
+ return bytecode
venv/Lib/site-packages/streamlit/runtime/scriptrunner/script_runner.py ADDED
@@ -0,0 +1,937 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import gc
18
+ import sys
19
+ import threading
20
+ import types
21
+ from contextlib import contextmanager
22
+ from enum import Enum
23
+ from timeit import default_timer as timer
24
+ from typing import TYPE_CHECKING, Any, Final, Literal, cast
25
+
26
+ from blinker import Signal
27
+
28
+ from streamlit import config, runtime, util
29
+ from streamlit.errors import FragmentStorageKeyError
30
+ from streamlit.logger import get_logger
31
+ from streamlit.proto.ClientState_pb2 import ClientState
32
+ from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
33
+ from streamlit.runtime.metrics_util import (
34
+ create_page_profile_message,
35
+ to_microseconds,
36
+ )
37
+ from streamlit.runtime.pages_manager import PagesManager
38
+ from streamlit.runtime.scriptrunner.exec_code import (
39
+ exec_func_with_error_handling,
40
+ modified_sys_path,
41
+ )
42
+ from streamlit.runtime.scriptrunner_utils.exceptions import (
43
+ RerunException,
44
+ StopException,
45
+ )
46
+ from streamlit.runtime.scriptrunner_utils.script_requests import (
47
+ RerunData,
48
+ ScriptRequests,
49
+ ScriptRequestType,
50
+ )
51
+ from streamlit.runtime.scriptrunner_utils.script_run_context import (
52
+ ScriptRunContext,
53
+ UserInfoType,
54
+ add_script_run_ctx,
55
+ get_script_run_ctx,
56
+ )
57
+ from streamlit.runtime.state import (
58
+ SCRIPT_RUN_WITHOUT_ERRORS_KEY,
59
+ SafeSessionState,
60
+ SessionState,
61
+ )
62
+ from streamlit.source_util import page_sort_key
63
+
64
+ if TYPE_CHECKING:
65
+ from collections.abc import Callable, Generator
66
+
67
+ from streamlit.runtime.fragment import FragmentStorage
68
+ from streamlit.runtime.parallel_coordinator import ParallelFragmentCoordinator
69
+ from streamlit.runtime.scriptrunner.script_cache import ScriptCache
70
+ from streamlit.runtime.scriptrunner_utils.script_run_context import (
71
+ OnScriptErrorHandler,
72
+ )
73
+ from streamlit.runtime.uploaded_file_manager import UploadedFileManager
74
+ from streamlit.watcher.local_sources_watcher import LocalSourcesWatcher
75
+
76
+ _LOGGER: Final = get_logger(__name__)
77
+
78
+
79
+ class ScriptRunnerEvent(Enum):
80
+ # "Control" events. These are emitted when the ScriptRunner's state changes.
81
+
82
+ # The script started running.
83
+ SCRIPT_STARTED = "SCRIPT_STARTED"
84
+
85
+ # The script run stopped because of a compile error.
86
+ SCRIPT_STOPPED_WITH_COMPILE_ERROR = "SCRIPT_STOPPED_WITH_COMPILE_ERROR"
87
+
88
+ # The script run stopped because it ran to completion, or was
89
+ # interrupted by the user.
90
+ SCRIPT_STOPPED_WITH_SUCCESS = "SCRIPT_STOPPED_WITH_SUCCESS"
91
+
92
+ # The script run stopped in order to start a script run with newer widget state.
93
+ SCRIPT_STOPPED_FOR_RERUN = "SCRIPT_STOPPED_FOR_RERUN"
94
+
95
+ # The script run corresponding to a fragment ran to completion, or was interrupted
96
+ # by the user.
97
+ FRAGMENT_STOPPED_WITH_SUCCESS = "FRAGMENT_STOPPED_WITH_SUCCESS"
98
+
99
+ # The ScriptRunner is done processing the ScriptEventQueue and
100
+ # is shut down.
101
+ SHUTDOWN = "SHUTDOWN"
102
+
103
+ # "Data" events. These are emitted when the ScriptRunner's script has
104
+ # data to send to the frontend.
105
+
106
+ # The script has a ForwardMsg to send to the frontend.
107
+ ENQUEUE_FORWARD_MSG = "ENQUEUE_FORWARD_MSG"
108
+
109
+
110
+ """
111
+ Note [Threading]
112
+ There are two kinds of threads in Streamlit, the main thread and script threads.
113
+ The main thread is started by invoking the Streamlit CLI, and bootstraps the
114
+ framework and runs the Uvicorn webserver.
115
+ A script thread is created by a ScriptRunner when it starts. The script thread
116
+ is where the ScriptRunner executes, including running the user script itself,
117
+ processing messages to/from the frontend, and all the Streamlit library function
118
+ calls in the user script.
119
+ It is possible for the user script to spawn its own threads, which could call
120
+ Streamlit functions. We restrict the ScriptRunner's execution control to the
121
+ script thread. Calling Streamlit functions from other threads is unlikely to
122
+ work correctly due to lack of ScriptRunContext, so we may add a guard against
123
+ it in the future.
124
+ """
125
+
126
+
127
+ # For projects that have a pages folder, we assume that this is a script that
128
+ # is designed to leverage our original v1 version of multi-page apps. This
129
+ # function will be called to run the script in lieu of the main script. This
130
+ # function simulates the v1 setup using the modern v2 commands (st.navigation)
131
+ def _mpa_v1(main_script_path: str) -> None:
132
+ from pathlib import Path
133
+
134
+ from streamlit.commands.navigation import PageType, _navigation
135
+ from streamlit.navigation.page import StreamlitPage
136
+
137
+ # Select the folder that should be used for the pages:
138
+ resolved_main_script_path: Final = Path(main_script_path).resolve()
139
+ pages_folder: Final = resolved_main_script_path.parent / "pages"
140
+
141
+ # Read out the my_pages folder and create a page for every script:
142
+ pages = sorted(
143
+ [
144
+ page
145
+ for page in pages_folder.glob("*.py")
146
+ if page.name.endswith(".py")
147
+ and not page.name.startswith(".")
148
+ and page.name != "__init__.py"
149
+ ],
150
+ key=page_sort_key,
151
+ )
152
+
153
+ # Use this script as the main page and
154
+ main_page = StreamlitPage(resolved_main_script_path, default=True)
155
+ all_pages = [main_page] + [
156
+ StreamlitPage(pages_folder / page.name) for page in pages
157
+ ]
158
+ # Initialize the navigation with all the pages:
159
+ position: Literal["sidebar", "hidden", "top"] = (
160
+ "hidden"
161
+ if config.get_option("client.showSidebarNavigation") is False
162
+ else "sidebar"
163
+ )
164
+ page = _navigation(
165
+ cast("list[PageType]", all_pages),
166
+ position=position,
167
+ expanded=False,
168
+ )
169
+
170
+ page.run()
171
+
172
+
173
+ class ScriptRunner:
174
+ def __init__(
175
+ self,
176
+ session_id: str,
177
+ main_script_path: str,
178
+ session_state: SessionState,
179
+ uploaded_file_mgr: UploadedFileManager,
180
+ script_cache: ScriptCache,
181
+ initial_rerun_data: RerunData,
182
+ user_info: UserInfoType,
183
+ fragment_storage: FragmentStorage,
184
+ pages_manager: PagesManager,
185
+ on_script_error: OnScriptErrorHandler | None = None,
186
+ local_sources_watcher: LocalSourcesWatcher | None = None,
187
+ ) -> None:
188
+ """Initialize the ScriptRunner.
189
+
190
+ (The ScriptRunner won't start executing until start() is called.)
191
+
192
+ Parameters
193
+ ----------
194
+ session_id
195
+ The AppSession's id.
196
+
197
+ main_script_path
198
+ Path to our main app script.
199
+
200
+ session_state
201
+ The AppSession's SessionState instance.
202
+
203
+ uploaded_file_mgr
204
+ The File manager to store the data uploaded by the file_uploader widget.
205
+
206
+ script_cache
207
+ A ScriptCache instance.
208
+
209
+ initial_rerun_data
210
+ RerunData to initialize this ScriptRunner with.
211
+
212
+ user_info
213
+ A dict that contains information about the current user. For now,
214
+ it only contains the user's email address.
215
+
216
+ {
217
+ "email": "example@example.com"
218
+ }
219
+
220
+ Information about the current user is optionally provided when a
221
+ websocket connection is initialized via the "X-Streamlit-User" header.
222
+
223
+ fragment_storage
224
+ The AppSession's FragmentStorage instance.
225
+
226
+ on_script_error
227
+ Callback to invoke when an uncaught exception occurs in user script code.
228
+ Returns True to suppress the default exception display, or False/None
229
+ to show the exception normally.
230
+
231
+ local_sources_watcher
232
+ The session's file watcher, if any. Its ``on_script_run`` hook is
233
+ called at the start of each script run (on the script thread)
234
+ before any user code executes.
235
+ """
236
+ self._session_id = session_id
237
+ self._main_script_path = main_script_path
238
+ self._session_state = SafeSessionState(
239
+ session_state, yield_callback=self._maybe_handle_execution_control_request
240
+ )
241
+ self._uploaded_file_mgr = uploaded_file_mgr
242
+ self._script_cache = script_cache
243
+ self._user_info = user_info
244
+ self._fragment_storage = fragment_storage
245
+ self._on_script_error = on_script_error
246
+
247
+ self._pages_manager = pages_manager
248
+ self._local_sources_watcher = local_sources_watcher
249
+ self._requests = ScriptRequests()
250
+ self._requests.request_rerun(initial_rerun_data)
251
+
252
+ self.on_event = Signal(
253
+ doc="""Emitted when a ScriptRunnerEvent occurs.
254
+
255
+ This signal is generally emitted on the ScriptRunner's script
256
+ thread (which is *not* the same thread that the ScriptRunner was
257
+ created on).
258
+
259
+ Parameters
260
+ ----------
261
+ sender: ScriptRunner
262
+ The sender of the event (this ScriptRunner).
263
+
264
+ event : ScriptRunnerEvent
265
+
266
+ forward_msg : ForwardMsg | None
267
+ The ForwardMsg to send to the frontend. Set only for the
268
+ ENQUEUE_FORWARD_MSG event.
269
+
270
+ exception : BaseException | None
271
+ Our compile error. Set only for the
272
+ SCRIPT_STOPPED_WITH_COMPILE_ERROR event.
273
+
274
+ widget_states : streamlit.proto.WidgetStates_pb2.WidgetStates | None
275
+ The ScriptRunner's final WidgetStates. Set only for the
276
+ SHUTDOWN event.
277
+ """
278
+ )
279
+
280
+ # Set to true while we're executing. Used by
281
+ # _maybe_handle_execution_control_request.
282
+ self._execing = False
283
+
284
+ # This is initialized in the start() method
285
+ self._script_thread: threading.Thread | None = None
286
+
287
+ # Coordinator blocking the script thread in join(); other threads poke
288
+ # notify_yield_waiters() when rerun/stop is enqueued during that window.
289
+ # Lock-protected so this is safe under free-threaded Python (PEP 703).
290
+ self._join_wake_lock = threading.Lock()
291
+ self._join_wake_coordinator: ParallelFragmentCoordinator | None = None
292
+
293
+ def __repr__(self) -> str:
294
+ return util.repr_(self)
295
+
296
+ def request_stop(self) -> None:
297
+ """Request that the ScriptRunner stop running its script and
298
+ shut down. The ScriptRunner will handle this request when it reaches
299
+ an interrupt point.
300
+
301
+ Safe to call from any thread.
302
+ """
303
+ self._requests.request_stop()
304
+ self._wake_parallel_join_barrier_if_waiting()
305
+
306
+ def request_rerun(self, rerun_data: RerunData) -> bool:
307
+ """Request that the ScriptRunner interrupt its currently-running
308
+ script and restart it.
309
+
310
+ If the ScriptRunner has been stopped, this request can't be honored:
311
+ return False.
312
+
313
+ Otherwise, record the request and return True. The ScriptRunner will
314
+ handle the rerun request as soon as it reaches an interrupt point.
315
+
316
+ Safe to call from any thread.
317
+ """
318
+ rv = self._requests.request_rerun(rerun_data)
319
+ self._wake_parallel_join_barrier_if_waiting()
320
+ return rv
321
+
322
+ def _wake_parallel_join_barrier_if_waiting(self) -> None:
323
+ """If the script thread is blocked in ParallelFragmentCoordinator.join(), wake it.
324
+
325
+ Rerun/stop requests can arrive on other threads; join() sleeps on a
326
+ Condition bounded by poll_interval unless notified.
327
+ """
328
+ with self._join_wake_lock:
329
+ coord = self._join_wake_coordinator
330
+ if coord is not None:
331
+ coord.notify_yield_waiters()
332
+
333
+ def start(self) -> None:
334
+ """Start a new thread to process the ScriptEventQueue.
335
+
336
+ This must be called only once.
337
+
338
+ """
339
+ if self._script_thread is not None:
340
+ raise RuntimeError("ScriptRunner was already started")
341
+
342
+ self._script_thread = threading.Thread(
343
+ target=self._run_script_thread,
344
+ name="ScriptRunner.scriptThread",
345
+ )
346
+ self._script_thread.start()
347
+
348
+ def _get_script_run_ctx(self) -> ScriptRunContext:
349
+ """Get the ScriptRunContext for the current thread.
350
+
351
+ Returns
352
+ -------
353
+ ScriptRunContext
354
+ The ScriptRunContext for the current thread.
355
+
356
+ Raises
357
+ ------
358
+ AssertionError
359
+ If called outside of a ScriptRunner thread.
360
+ RuntimeError
361
+ If there is no ScriptRunContext for the current thread.
362
+
363
+ """
364
+ if not self._is_in_script_thread():
365
+ raise RuntimeError(
366
+ "ScriptRunner._get_script_run_ctx must be called from the script thread."
367
+ )
368
+
369
+ ctx = get_script_run_ctx()
370
+ if ctx is None:
371
+ # This should never be possible on the script_runner thread.
372
+ raise RuntimeError(
373
+ "ScriptRunner thread has a null ScriptRunContext. "
374
+ "Something has gone very wrong!"
375
+ )
376
+ return ctx
377
+
378
+ def _run_script_thread(self) -> None:
379
+ """The entry point for the script thread.
380
+
381
+ Processes the ScriptRequestQueue, which will at least contain the RERUN
382
+ request that will trigger the first script-run.
383
+
384
+ When the ScriptRequestQueue is empty, or when a SHUTDOWN request is
385
+ dequeued, this function will exit and its thread will terminate.
386
+ """
387
+ if not self._is_in_script_thread():
388
+ raise RuntimeError(
389
+ "ScriptRunner._run_script_thread must be called from the script thread."
390
+ )
391
+
392
+ _LOGGER.debug("Beginning script thread")
393
+
394
+ # Create and attach the thread's ScriptRunContext
395
+ ctx = ScriptRunContext(
396
+ session_id=self._session_id,
397
+ _enqueue=self._enqueue_forward_msg,
398
+ script_requests=self._requests,
399
+ query_string="",
400
+ session_state=self._session_state,
401
+ uploaded_file_mgr=self._uploaded_file_mgr,
402
+ main_script_path=self._main_script_path,
403
+ user_info=self._user_info,
404
+ gather_usage_stats=bool(config.get_option("browser.gatherUsageStats")),
405
+ fragment_storage=self._fragment_storage,
406
+ pages_manager=self._pages_manager,
407
+ context_info=None,
408
+ on_script_error=self._on_script_error,
409
+ )
410
+ add_script_run_ctx(threading.current_thread(), ctx)
411
+
412
+ request = self._requests.on_scriptrunner_ready()
413
+ while request.type == ScriptRequestType.RERUN:
414
+ # When the script thread starts, we'll have a pending rerun
415
+ # request that we'll handle immediately. When the script finishes,
416
+ # it's possible that another request has come in that we need to
417
+ # handle, which is why we call _run_script in a loop.
418
+ self._run_script(request.rerun_data)
419
+ request = self._requests.on_scriptrunner_ready()
420
+
421
+ if request.type != ScriptRequestType.STOP: # pragma: no cover - defensive
422
+ raise RuntimeError(
423
+ f"Unrecognized ScriptRequestType: {request.type}. This should never happen."
424
+ )
425
+
426
+ # Send a SHUTDOWN event before exiting, so some state can be saved
427
+ # for use in a future script run when not triggered by the client.
428
+ client_state = ClientState()
429
+ client_state.query_string = ctx.query_string
430
+ client_state.page_script_hash = ctx.page_script_hash
431
+ if ctx.context_info:
432
+ client_state.context_info.CopyFrom(ctx.context_info)
433
+ self.on_event.send(
434
+ self, event=ScriptRunnerEvent.SHUTDOWN, client_state=client_state
435
+ )
436
+
437
+ def _is_in_script_thread(self) -> bool:
438
+ """True if the calling function is running in the script thread."""
439
+ return self._script_thread == threading.current_thread()
440
+
441
+ def _enqueue_forward_msg(self, msg: ForwardMsg) -> None:
442
+ """Enqueue a ForwardMsg to our browser queue.
443
+ This private function is called by ScriptRunContext only.
444
+
445
+ It may be called from the script thread OR the main thread.
446
+ """
447
+ # Whenever we enqueue a ForwardMsg, we also handle any pending
448
+ # execution control request. This means that a script can be
449
+ # cleanly interrupted and stopped inside most `st.foo` calls.
450
+ self._maybe_handle_execution_control_request()
451
+
452
+ # Pass the message to our associated AppSession.
453
+ self.on_event.send(
454
+ self, event=ScriptRunnerEvent.ENQUEUE_FORWARD_MSG, forward_msg=msg
455
+ )
456
+
457
+ def _maybe_handle_execution_control_request(self) -> None:
458
+ """Check our current ScriptRequestState to see if we have a
459
+ pending STOP or RERUN request.
460
+
461
+ This function is called every time the app script enqueues a
462
+ ForwardMsg, which means that most `st.foo` commands - which generally
463
+ involve sending a ForwardMsg to the frontend - act as implicit
464
+ yield points in the script's execution.
465
+ """
466
+ if not self._is_in_script_thread():
467
+ # We can only handle execution_control_request if we're on the
468
+ # script execution thread. However, this function also runs from
469
+ # parallel fragment worker threads, since deltas enqueued there
470
+ # flow through _enqueue_forward_msg. On a worker thread we can't
471
+ # service script-level rerun/stop requests, but we do check the
472
+ # coordinator so a cooperatively-cancelled worker raises at its
473
+ # next yield point.
474
+ ctx = get_script_run_ctx(suppress_warning=True)
475
+ if (
476
+ ctx is not None
477
+ and ctx.parallel_coordinator is not None
478
+ and ctx.parallel_coordinator.should_stop()
479
+ ):
480
+ raise StopException()
481
+ return
482
+
483
+ if not self._execing:
484
+ # If the _execing flag is not set, we're not actually inside
485
+ # an exec() call. This happens when our script exec() completes,
486
+ # we change our state to STOPPED, and a statechange-listener
487
+ # enqueues a new ForwardEvent
488
+ return
489
+
490
+ # Re-raise any worker-stored exception before consulting _requests.
491
+ # Worker-initiated cancellation takes precedence because it
492
+ # captured user intent in-band.
493
+ ctx = get_script_run_ctx(suppress_warning=True)
494
+ if ctx is not None and ctx.parallel_coordinator is not None:
495
+ worker_exc = ctx.parallel_coordinator.worker_exception
496
+ if worker_exc is not None:
497
+ raise worker_exc
498
+
499
+ request = self._requests.on_scriptrunner_yield()
500
+ if request is None:
501
+ # No RERUN or STOP request.
502
+ return
503
+
504
+ if request.type == ScriptRequestType.RERUN:
505
+ raise RerunException(request.rerun_data)
506
+
507
+ if request.type != ScriptRequestType.STOP: # pragma: no cover - defensive
508
+ raise RuntimeError(
509
+ f"Unrecognized ScriptRequestType: {request.type}. This should never happen."
510
+ )
511
+ raise StopException()
512
+
513
+ @contextmanager
514
+ def _set_execing_flag(self) -> Generator[None, None, None]:
515
+ """A context for setting the ScriptRunner._execing flag.
516
+
517
+ Used by _maybe_handle_execution_control_request to ensure that
518
+ we only handle requests while we're inside an exec() call
519
+ """
520
+ if self._execing:
521
+ raise RuntimeError("Nested set_execing_flag call")
522
+ self._execing = True
523
+ try:
524
+ yield
525
+ finally:
526
+ self._execing = False
527
+
528
+ def _run_script(self, rerun_data: RerunData) -> None:
529
+ """Run our script.
530
+
531
+ Parameters
532
+ ----------
533
+ rerun_data: RerunData
534
+ The RerunData to use.
535
+
536
+ """
537
+
538
+ if not self._is_in_script_thread():
539
+ raise RuntimeError(
540
+ "ScriptRunner._run_script must be called from the script thread."
541
+ )
542
+
543
+ # An explicit loop instead of recursion to avoid stack overflows
544
+ while True:
545
+ if self._local_sources_watcher is not None:
546
+ self._local_sources_watcher.on_script_run()
547
+
548
+ _LOGGER.debug("Running script")
549
+ start_time: float = timer()
550
+ prep_time: float = 0 # This will be overwritten once preparations are done.
551
+
552
+ if not rerun_data.fragment_id_queue:
553
+ # Don't clear session refs for media files if we're running a fragment.
554
+ # Otherwise, we're likely to remove files that still have corresponding
555
+ # download buttons/links to them present in the app, which will result
556
+ # in a 404 should the user click on them.
557
+ runtime.get_instance().media_file_mgr.clear_session_refs()
558
+
559
+ self._pages_manager.set_script_intent(
560
+ rerun_data.page_script_hash, rerun_data.page_name
561
+ )
562
+ active_script = self._pages_manager.get_initial_active_script(
563
+ rerun_data.page_script_hash
564
+ )
565
+ main_page_info = self._pages_manager.get_main_page()
566
+
567
+ page_script_hash = (
568
+ active_script["page_script_hash"]
569
+ if active_script is not None
570
+ else main_page_info["page_script_hash"]
571
+ )
572
+
573
+ ctx = self._get_script_run_ctx()
574
+ # Clear widget state on page change. This normally happens implicitly
575
+ # in the script run cleanup steps, but doing it explicitly ensures
576
+ # it happens even if a script run was interrupted.
577
+ previous_page_script_hash = ctx.page_script_hash
578
+ if previous_page_script_hash != page_script_hash:
579
+ # Page changed, enforce reset widget state where possible.
580
+ # This enforcement matters when a new script thread is started
581
+ # before the previous script run is completed (from user
582
+ # interaction). Use the widget ids from the rerun data to
583
+ # maintain some widget state, as the rerun data should
584
+ # contain the latest widget ids from the frontend.
585
+ widget_ids: frozenset[str] = frozenset()
586
+
587
+ if (
588
+ rerun_data.widget_states is not None
589
+ and rerun_data.widget_states.widgets is not None
590
+ ):
591
+ widget_ids = frozenset(
592
+ w.id for w in rerun_data.widget_states.widgets
593
+ )
594
+
595
+ # For MPA page transitions: filter query params BEFORE cleanup.
596
+ # This uses existing bindings to remove params from other pages,
597
+ # ensuring st.query_params is accurate when the new page runs.
598
+ # (st.query_params in user code will reflect the correct params for the new page)
599
+ main_script_hash = self._pages_manager.main_script_hash
600
+ valid_script_hashes = {main_script_hash, page_script_hash}
601
+ with self._session_state.query_params() as qp:
602
+ qp.populate_from_query_string(
603
+ rerun_data.query_string, valid_script_hashes
604
+ )
605
+ # Set initial params from FILTERED state for widget seeding.
606
+ # This prevents stale params from previous pages from seeding
607
+ # widgets on the new page if keys collide.
608
+ qp.set_initial_query_params_from_current()
609
+
610
+ # Now safe to do normal cleanup - filtering already done
611
+ self._session_state.on_script_finished(widget_ids)
612
+
613
+ fragment_ids_this_run: list[str] | None = None
614
+ if rerun_data.fragment_id_queue:
615
+ fragment_ids_this_run = self._fragment_storage.order_fragment_ids(
616
+ rerun_data.fragment_id_queue
617
+ )
618
+
619
+ ctx.reset(
620
+ query_string=rerun_data.query_string,
621
+ page_script_hash=page_script_hash,
622
+ fragment_ids_this_run=fragment_ids_this_run,
623
+ cached_message_hashes=rerun_data.cached_message_hashes,
624
+ context_info=rerun_data.context_info,
625
+ yield_check=self._maybe_handle_execution_control_request,
626
+ )
627
+ with self._join_wake_lock:
628
+ self._join_wake_coordinator = ctx.parallel_coordinator
629
+
630
+ self.on_event.send(
631
+ self,
632
+ event=ScriptRunnerEvent.SCRIPT_STARTED,
633
+ page_script_hash=page_script_hash,
634
+ fragment_ids_this_run=fragment_ids_this_run,
635
+ pages=self._pages_manager.get_pages(),
636
+ )
637
+
638
+ # Compile the script. Any errors thrown here will be surfaced
639
+ # to the user via a modal dialog in the frontend, and won't result
640
+ # in their previous script elements disappearing.
641
+ try:
642
+ if active_script is not None:
643
+ script_path = active_script["script_path"]
644
+ else:
645
+ # page must not be found
646
+ script_path = main_page_info["script_path"]
647
+
648
+ # At this point, we know that either
649
+ # * the script corresponding to the hash requested no longer
650
+ # exists, or
651
+ # * we were not able to find a script with the requested page
652
+ # name.
653
+ # In both of these cases, we want to send a page_not_found
654
+ # message to the frontend.
655
+ msg = ForwardMsg()
656
+ msg.page_not_found.page_name = rerun_data.page_name
657
+ ctx.enqueue(msg)
658
+
659
+ code = self._script_cache.get_bytecode(script_path)
660
+
661
+ except Exception as ex:
662
+ # We got a compile error. Send an error event and bail immediately.
663
+ _LOGGER.exception("Script compilation error", exc_info=ex)
664
+ self._session_state[SCRIPT_RUN_WITHOUT_ERRORS_KEY] = False
665
+ with self._join_wake_lock:
666
+ self._join_wake_coordinator = None
667
+ self.on_event.send(
668
+ self,
669
+ event=ScriptRunnerEvent.SCRIPT_STOPPED_WITH_COMPILE_ERROR,
670
+ exception=ex,
671
+ )
672
+ return
673
+
674
+ # If we get here, we've successfully compiled our script. The next step
675
+ # is to run it. Errors thrown during execution will be shown to the
676
+ # user as ExceptionElements.
677
+
678
+ # Create fake module. This gives us a name global namespace to
679
+ # execute the code in.
680
+ module = self._new_module("__main__")
681
+
682
+ # Install the fake module as the __main__ module. This allows
683
+ # the pickle module to work inside the user's code, since it now
684
+ # can know the module where the pickled objects stem from.
685
+ # IMPORTANT: This means we can't use "if __name__ == '__main__'" in
686
+ # our code, as it will point to the wrong module!!!
687
+ sys.modules["__main__"] = module
688
+
689
+ # Add special variables to the module's globals dict.
690
+ # Note: The following is a requirement for the CodeHasher to
691
+ # work correctly. The CodeHasher is scoped to
692
+ # files contained in the directory of __main__.__file__, which we
693
+ # assume is the main script directory.
694
+ module.__dict__["__file__"] = script_path
695
+
696
+ def code_to_exec(
697
+ code: str = code,
698
+ module: types.ModuleType = module,
699
+ ctx: ScriptRunContext = ctx,
700
+ rerun_data: RerunData = rerun_data,
701
+ fragment_ids_this_run: list[str] | None = fragment_ids_this_run,
702
+ ) -> None:
703
+ with (
704
+ modified_sys_path(self._main_script_path),
705
+ self._set_execing_flag(),
706
+ ):
707
+ # Run callbacks for widgets whose values have changed.
708
+ if rerun_data.widget_states is not None:
709
+ self._session_state.on_script_will_rerun(
710
+ rerun_data.widget_states
711
+ )
712
+
713
+ ctx.on_script_start()
714
+
715
+ if fragment_ids_this_run:
716
+ for fragment_id in fragment_ids_this_run:
717
+ registration_sequence_before = (
718
+ self._fragment_storage.registration_sequence()
719
+ )
720
+ try:
721
+ wrapped_fragment = self._fragment_storage.lookup(
722
+ fragment_id
723
+ )
724
+ except FragmentStorageKeyError:
725
+ # This can happen if the fragment_id is removed from the
726
+ # storage before the script runner gets to it. In this
727
+ # case, the fragment is simply skipped.
728
+ # Also, only log an error if the fragment is not an
729
+ # auto_rerun to avoid noise. If it is an auto_rerun, we
730
+ # might have a race condition where the fragment_id is
731
+ # removed but the webapp sends a rerun request before
732
+ # the removal information has reached the web app
733
+ # (see https://github.com/streamlit/streamlit/issues/9080).
734
+ if not rerun_data.is_auto_rerun:
735
+ _LOGGER.warning(
736
+ "Couldn't find fragment with id %s."
737
+ " This can happen if the fragment does not"
738
+ " exist anymore when this request is processed,"
739
+ " for example because a full app rerun happened"
740
+ " that did not register the fragment."
741
+ " Usually this doesn't happen or no action is"
742
+ " required, so its mainly for debugging.",
743
+ fragment_id,
744
+ )
745
+ continue
746
+
747
+ try:
748
+ wrapped_fragment()
749
+ except (RerunException, StopException):
750
+ # The wrapped_fragment function is executed
751
+ # inside of a exec_func_with_error_handling call, so
752
+ # there is a correct handler for these exceptions.
753
+ raise
754
+ except Exception: # noqa: S110
755
+ # Ignore exceptions raised by fragments here as we don't
756
+ # want to stop the execution of other fragments. The
757
+ # error itself is already rendered within the wrapped
758
+ # fragment.
759
+ pass
760
+ finally:
761
+ # Cleanup always uses what was actually re-registered
762
+ # during this attempt, regardless of how the fragment
763
+ # exited (normal return, RerunException, StopException,
764
+ # or a swallowed user exception). Children that the
765
+ # fragment did not get a chance to re-register will be
766
+ # dropped here and re-created on the next rerun.
767
+ registered_ids = (
768
+ self._fragment_storage.ids_registered_after(
769
+ registration_sequence_before
770
+ )
771
+ )
772
+ removed_fragment_ids = (
773
+ self._fragment_storage.clear_stale_descendants(
774
+ fragment_id,
775
+ registered_ids,
776
+ )
777
+ )
778
+ # Tell the frontend to cancel auto-rerun timers for
779
+ # fragments that were evicted (e.g. a nested
780
+ # ``run_every`` child that is no longer rendered), so
781
+ # they don't keep sending stale rerun requests.
782
+ if removed_fragment_ids:
783
+ stop_msg = ForwardMsg()
784
+ stop_msg.stop_auto_rerun.fragment_ids.extend(
785
+ removed_fragment_ids
786
+ )
787
+ ctx.enqueue(stop_msg)
788
+
789
+ else:
790
+ # Drop wrappers from the previous run before the main
791
+ # script recreates its outside containers as new DG
792
+ # objects. Clearing here (rather than after the script
793
+ # body) lets the wrappers created during this run survive
794
+ # for the fragment reruns that follow it.
795
+ self._fragment_storage.clear_outside_wrappers()
796
+
797
+ # Expect parallel_coordinator to be initialized;
798
+ # cast makes this clear to the type checker.
799
+ coordinator = cast(
800
+ "ParallelFragmentCoordinator",
801
+ ctx.parallel_coordinator,
802
+ )
803
+ try:
804
+ if PagesManager.uses_pages_directory:
805
+ _mpa_v1(self._main_script_path)
806
+ else:
807
+ exec(code, module.__dict__) # noqa: S102
808
+ coordinator.join()
809
+ except BaseException:
810
+ # Always drain so in-flight worker fragments
811
+ # don't outlive the script run, regardless of
812
+ # whether the escape was a script-control
813
+ # exception, an uncaught user error, or an
814
+ # interrupt.
815
+ coordinator.drain()
816
+ raise
817
+ self._fragment_storage.clear(
818
+ new_fragment_ids=ctx.shared.new_fragment_ids.snapshot()
819
+ )
820
+
821
+ self._session_state.maybe_check_serializable()
822
+ # check for control requests, e.g. rerun requests have arrived
823
+ self._maybe_handle_execution_control_request()
824
+
825
+ prep_time = timer() - start_time
826
+ (
827
+ _,
828
+ run_without_errors,
829
+ rerun_exception_data,
830
+ premature_stop,
831
+ uncaught_exception,
832
+ ) = exec_func_with_error_handling(code_to_exec, ctx)
833
+ # setting the session state here triggers a yield-callback call
834
+ # which reads self._requests and checks for rerun data
835
+ self._session_state[SCRIPT_RUN_WITHOUT_ERRORS_KEY] = run_without_errors
836
+
837
+ if rerun_exception_data:
838
+ # The handling for when a full script run or a fragment is stopped early
839
+ # is the same, so we only have one ScriptRunnerEvent for this scenario.
840
+ finished_event = ScriptRunnerEvent.SCRIPT_STOPPED_FOR_RERUN
841
+ elif rerun_data.fragment_id_queue:
842
+ finished_event = ScriptRunnerEvent.FRAGMENT_STOPPED_WITH_SUCCESS
843
+ else:
844
+ finished_event = ScriptRunnerEvent.SCRIPT_STOPPED_WITH_SUCCESS
845
+
846
+ if ctx.gather_usage_stats:
847
+ try:
848
+ # Create and send page profile information
849
+ ctx.enqueue(
850
+ create_page_profile_message(
851
+ commands=ctx.shared.tracked_commands,
852
+ exec_time=to_microseconds(timer() - start_time),
853
+ prep_time=to_microseconds(prep_time),
854
+ uncaught_exception=(
855
+ type(uncaught_exception).__name__
856
+ if uncaught_exception
857
+ else None
858
+ ),
859
+ )
860
+ )
861
+ except Exception as ex:
862
+ # Always capture all exceptions since we want to make sure that
863
+ # the telemetry never causes any issues.
864
+ _LOGGER.debug("Failed to create page profile", exc_info=ex)
865
+ self._on_script_finished(ctx, finished_event, premature_stop)
866
+
867
+ # # Use _log_if_error() to make sure we never ever ever stop running the
868
+ # # script without meaning to.
869
+ _log_if_error(_clean_problem_modules)
870
+
871
+ if rerun_exception_data is not None:
872
+ rerun_data = rerun_exception_data
873
+ else:
874
+ break
875
+
876
+ def _on_script_finished(
877
+ self, ctx: ScriptRunContext, event: ScriptRunnerEvent, premature_stop: bool
878
+ ) -> None:
879
+ """Called when our script finishes executing, even if it finished
880
+ early with an exception. We perform post-run cleanup here.
881
+ """
882
+ with self._join_wake_lock:
883
+ self._join_wake_coordinator = None
884
+
885
+ # Tell session_state to update itself in response
886
+ if not premature_stop:
887
+ self._session_state.on_script_finished(
888
+ ctx.shared.widget_ids_this_run.snapshot()
889
+ )
890
+
891
+ # Signal that the script has finished. (We use SCRIPT_STOPPED_WITH_SUCCESS
892
+ # even if we were stopped with an exception.)
893
+ self.on_event.send(self, event=event)
894
+
895
+ # Remove orphaned files now that the script has run and files in use
896
+ # are marked as active.
897
+ runtime.get_instance().media_file_mgr.remove_orphaned_files()
898
+
899
+ # Force garbage collection to run, to help avoid memory use building up
900
+ # This is usually not an issue, but sometimes GC takes time to kick in and
901
+ # causes apps to go over resource limits, and forcing it to run between
902
+ # script runs is low cost, since we aren't doing much work anyway.
903
+ if config.get_option("runner.postScriptGC"):
904
+ gc.collect(2)
905
+
906
+ def _new_module(self, name: str) -> types.ModuleType:
907
+ """Create a new module with the given name."""
908
+ return types.ModuleType(name)
909
+
910
+
911
+ def _clean_problem_modules() -> None:
912
+ """Some modules are stateful, so we have to clear their state."""
913
+
914
+ if "keras" in sys.modules:
915
+ try:
916
+ keras = sys.modules["keras"]
917
+ cast("Any", keras).backend.clear_session()
918
+ except Exception: # noqa: S110
919
+ # We don't want to crash the app if we can't clear the Keras session.
920
+ pass
921
+
922
+ if "matplotlib.pyplot" in sys.modules:
923
+ try:
924
+ plt = sys.modules["matplotlib.pyplot"]
925
+ cast("Any", plt).close("all")
926
+ except Exception: # noqa: S110
927
+ # We don't want to crash the app if we can't close matplotlib
928
+ pass
929
+
930
+
931
+ # The reason this is not a decorator is because we want to make it clear at the
932
+ # calling location that this function is being used.
933
+ def _log_if_error(fn: Callable[[], None]) -> None:
934
+ try:
935
+ fn()
936
+ except Exception as e:
937
+ _LOGGER.warning(e)
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """The modules in this package are separated from
16
+ the scriptrunner-package, because they are more or less
17
+ standalone and other modules import them quite frequently.
18
+ This separation helps us to remove dependency cycles.
19
+ """
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/__init__.cpython-314.pyc ADDED
Binary file (421 Bytes). View file
 
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/exceptions.cpython-314.pyc ADDED
Binary file (1.97 kB). View file
 
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/script_requests.cpython-314.pyc ADDED
Binary file (13 kB). View file
 
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/script_run_context.cpython-314.pyc ADDED
Binary file (20.9 kB). View file
 
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/script_run_context_attr.cpython-314.pyc ADDED
Binary file (692 Bytes). View file
 
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/shared_run_state.cpython-314.pyc ADDED
Binary file (5.48 kB). View file
 
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/__pycache__/thread_safe_set.cpython-314.pyc ADDED
Binary file (4.64 kB). View file
 
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/exceptions.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from streamlit.runtime.scriptrunner_utils.script_requests import RerunData
16
+ from streamlit.util import repr_
17
+
18
+
19
+ # We inherit from BaseException to avoid being caught by user code.
20
+ # For example, having it inherit from Exception might make st.rerun not
21
+ # work in a try/except block.
22
+ class ScriptControlException(BaseException): # NOSONAR
23
+ """Base exception for ScriptRunner."""
24
+
25
+
26
+ class StopException(ScriptControlException):
27
+ """Silently stop the execution of the user's script."""
28
+
29
+
30
+ class RerunException(ScriptControlException):
31
+ """Silently stop and rerun the user's script."""
32
+
33
+ def __init__(self, rerun_data: RerunData) -> None:
34
+ """Construct a RerunException.
35
+
36
+ Parameters
37
+ ----------
38
+ rerun_data : RerunData
39
+ The RerunData that should be used to rerun the script
40
+ """
41
+ self.rerun_data = rerun_data
42
+
43
+ def __repr__(self) -> str:
44
+ return repr_(self)
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/script_requests.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import threading
18
+ from dataclasses import dataclass, field, replace
19
+ from enum import Enum
20
+ from typing import TYPE_CHECKING, cast
21
+
22
+ from streamlit import util
23
+ from streamlit.proto.Common_pb2 import ChatInputValue as ChatInputValueProto
24
+ from streamlit.proto.WidgetStates_pb2 import WidgetState, WidgetStates
25
+
26
+ if TYPE_CHECKING:
27
+ from streamlit.proto.ClientState_pb2 import ContextInfo
28
+
29
+
30
+ class ScriptRequestType(Enum):
31
+ # The ScriptRunner should continue running its script.
32
+ CONTINUE = "CONTINUE"
33
+
34
+ # If the script is running, it should be stopped as soon
35
+ # as the ScriptRunner reaches an interrupt point.
36
+ # This is a terminal state.
37
+ STOP = "STOP"
38
+
39
+ # A script rerun has been requested. The ScriptRunner should
40
+ # handle this request as soon as it reaches an interrupt point.
41
+ RERUN = "RERUN"
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class RerunData:
46
+ """Data attached to RERUN requests. Immutable."""
47
+
48
+ query_string: str = ""
49
+ widget_states: WidgetStates | None = None
50
+ page_script_hash: str = ""
51
+ page_name: str = ""
52
+
53
+ # A single fragment_id to append to fragment_id_queue.
54
+ fragment_id: str | None = None
55
+ # The queue of fragment_ids waiting to be run.
56
+ fragment_id_queue: list[str] = field(default_factory=list)
57
+ is_fragment_scoped_rerun: bool = False
58
+ # set to true when a script is rerun by the fragment auto-rerun mechanism
59
+ is_auto_rerun: bool = False
60
+ # Hashes of messages that are cached in the client browser:
61
+ cached_message_hashes: frozenset[str] = field(default_factory=frozenset)
62
+ # context_info is used to store information from the user browser (e.g. timezone)
63
+ context_info: ContextInfo | None = None
64
+
65
+ def __repr__(self) -> str:
66
+ return util.repr_(self)
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class ScriptRequest:
71
+ """A STOP or RERUN request and associated data."""
72
+
73
+ type: ScriptRequestType
74
+ _rerun_data: RerunData | None = None
75
+
76
+ @property
77
+ def rerun_data(self) -> RerunData:
78
+ if self.type is not ScriptRequestType.RERUN:
79
+ raise RuntimeError("RerunData is only set for RERUN requests.")
80
+ return cast("RerunData", self._rerun_data)
81
+
82
+ def __repr__(self) -> str:
83
+ return util.repr_(self)
84
+
85
+
86
+ def _fragment_run_should_not_preempt_script(
87
+ fragment_id_queue: list[str],
88
+ is_fragment_scoped_rerun: bool,
89
+ ) -> bool:
90
+ """Returns whether the currently running script should be preempted due to a
91
+ fragment rerun.
92
+
93
+ Reruns corresponding to fragment runs that weren't caused by calls to
94
+ `st.rerun(scope="fragment")` should *not* cancel the current script run
95
+ as doing so will affect elements outside of the fragment.
96
+ """
97
+ return bool(fragment_id_queue) and not is_fragment_scoped_rerun
98
+
99
+
100
+ def _coalesce_widget_states(
101
+ old_states: WidgetStates | None, new_states: WidgetStates | None
102
+ ) -> WidgetStates | None:
103
+ """Coalesce an older WidgetStates into a newer one, and return a new
104
+ WidgetStates containing the result.
105
+
106
+ For most widget values, we just take the latest version.
107
+
108
+ However, any trigger_values (which are set by buttons) that are True in
109
+ `old_states` will be set to True in the coalesced result, so that button
110
+ presses don't go missing.
111
+ """
112
+ if not old_states and not new_states:
113
+ return None
114
+ if not old_states:
115
+ return new_states
116
+ if not new_states:
117
+ return old_states
118
+
119
+ states_by_id: dict[str, WidgetState] = {
120
+ wstate.id: wstate for wstate in new_states.widgets
121
+ }
122
+
123
+ trigger_value_types = [
124
+ ("trigger_value", False),
125
+ ("chat_input_value", ChatInputValueProto(data=None)),
126
+ ]
127
+ for old_state in old_states.widgets:
128
+ for trigger_value_type, unset_value in trigger_value_types:
129
+ if (
130
+ old_state.WhichOneof("value") == trigger_value_type
131
+ and getattr(old_state, trigger_value_type) != unset_value
132
+ ):
133
+ new_trigger_val = states_by_id.get(old_state.id)
134
+ # It should nearly always be the case that new_trigger_val is None
135
+ # here as trigger values are deleted from the client's WidgetStateManager
136
+ # as soon as a rerun_script BackMsg is sent to the server. Since it's
137
+ # impossible to test that the client sends us state in the expected
138
+ # format in a unit test, we test for this behavior in
139
+ # e2e_playwright/test_fragment_queue_test.py
140
+ if not new_trigger_val or (
141
+ # Ensure the corresponding new_state is also a trigger;
142
+ # otherwise, a widget that was previously a button/chat_input but no
143
+ # longer is could get a bad value.
144
+ new_trigger_val.WhichOneof("value") == trigger_value_type
145
+ # We only want to take the value of old_state if new_trigger_val is
146
+ # unset as the old value may be stale if a newer one was entered.
147
+ and getattr(new_trigger_val, trigger_value_type) == unset_value
148
+ ):
149
+ states_by_id[old_state.id] = old_state
150
+
151
+ coalesced = WidgetStates()
152
+ coalesced.widgets.extend(states_by_id.values())
153
+
154
+ return coalesced
155
+
156
+
157
+ class ScriptRequests:
158
+ """An interface for communicating with a ScriptRunner. Thread-safe.
159
+
160
+ AppSession makes requests of a ScriptRunner through this class, and
161
+ ScriptRunner handles those requests.
162
+ """
163
+
164
+ def __init__(self) -> None:
165
+ self._lock = threading.Lock()
166
+ self._state = ScriptRequestType.CONTINUE
167
+ self._rerun_data = RerunData()
168
+
169
+ def request_stop(self) -> None:
170
+ """Request that the ScriptRunner stop running. A stopped ScriptRunner
171
+ can't be used anymore. STOP requests succeed unconditionally.
172
+ """
173
+ with self._lock:
174
+ self._state = ScriptRequestType.STOP
175
+
176
+ def request_rerun(self, new_data: RerunData) -> bool:
177
+ """Request that the ScriptRunner rerun its script.
178
+
179
+ If the ScriptRunner has been stopped, this request can't be honored:
180
+ return False.
181
+
182
+ Otherwise, record the request and return True. The ScriptRunner will
183
+ handle the rerun request as soon as it reaches an interrupt point.
184
+ """
185
+
186
+ with self._lock:
187
+ if self._state == ScriptRequestType.STOP:
188
+ # We can't rerun after being stopped.
189
+ return False
190
+
191
+ if self._state == ScriptRequestType.CONTINUE:
192
+ # The script is currently running, and we haven't received a request to
193
+ # rerun it as of yet. We can handle a rerun request unconditionally so
194
+ # just change self._state and set self._rerun_data.
195
+ self._state = ScriptRequestType.RERUN
196
+
197
+ # Convert from a single fragment_id into fragment_id_queue.
198
+ if new_data.fragment_id:
199
+ new_data = replace(
200
+ new_data,
201
+ fragment_id=None,
202
+ fragment_id_queue=[new_data.fragment_id],
203
+ )
204
+
205
+ self._rerun_data = new_data
206
+ return True
207
+
208
+ if self._state == ScriptRequestType.RERUN:
209
+ # We already have an existing Rerun request, so we can coalesce the new
210
+ # rerun request into the existing one.
211
+
212
+ coalesced_states = _coalesce_widget_states(
213
+ self._rerun_data.widget_states, new_data.widget_states
214
+ )
215
+
216
+ if new_data.fragment_id:
217
+ # This RERUN request corresponds to a new fragment run. We append
218
+ # the new fragment ID to the end of the current fragment_id_queue if
219
+ # it isn't already contained in it.
220
+ fragment_id_queue = [*self._rerun_data.fragment_id_queue]
221
+
222
+ if new_data.fragment_id not in fragment_id_queue:
223
+ fragment_id_queue.append(new_data.fragment_id)
224
+ elif new_data.fragment_id_queue:
225
+ # new_data contains a new fragment_id_queue, so we just use it.
226
+ fragment_id_queue = new_data.fragment_id_queue
227
+ else:
228
+ # Otherwise, this is a request to rerun the full script, so we want
229
+ # to clear out any fragments we have queued to run since they'll all
230
+ # be run with the full script anyway.
231
+ fragment_id_queue = []
232
+
233
+ self._rerun_data = RerunData(
234
+ query_string=new_data.query_string,
235
+ widget_states=coalesced_states,
236
+ page_script_hash=new_data.page_script_hash,
237
+ page_name=new_data.page_name,
238
+ fragment_id_queue=fragment_id_queue,
239
+ cached_message_hashes=new_data.cached_message_hashes,
240
+ is_fragment_scoped_rerun=new_data.is_fragment_scoped_rerun,
241
+ is_auto_rerun=new_data.is_auto_rerun,
242
+ context_info=new_data.context_info,
243
+ )
244
+
245
+ return True
246
+
247
+ # We'll never get here
248
+ raise RuntimeError(f"Unrecognized ScriptRunnerState: {self._state}")
249
+
250
+ def on_scriptrunner_yield(self) -> ScriptRequest | None:
251
+ """Called by the ScriptRunner when it's at a yield point.
252
+
253
+ If we have no request or a RERUN request corresponding to one or more fragments
254
+ (that is not a fragment-scoped rerun), return None.
255
+
256
+ If we have a (full script or fragment-scoped) RERUN request, return the request
257
+ and set our internal state to CONTINUE.
258
+
259
+ If we have a STOP request, return the request and remain stopped.
260
+ """
261
+ if self._state == ScriptRequestType.CONTINUE or (
262
+ self._state == ScriptRequestType.RERUN
263
+ and _fragment_run_should_not_preempt_script(
264
+ self._rerun_data.fragment_id_queue,
265
+ self._rerun_data.is_fragment_scoped_rerun,
266
+ )
267
+ ):
268
+ # We avoid taking the lock in the common cases described above. If a STOP or
269
+ # preempting RERUN request is received after we've taken this code path, it
270
+ # will be handled at the next `on_scriptrunner_yield`, or when
271
+ # `on_scriptrunner_ready` is called.
272
+ return None
273
+
274
+ with self._lock:
275
+ if self._state == ScriptRequestType.RERUN:
276
+ # We already made this check in the fast-path above but need to do so
277
+ # again in case our state changed while we were waiting on the lock.
278
+ if _fragment_run_should_not_preempt_script(
279
+ self._rerun_data.fragment_id_queue,
280
+ self._rerun_data.is_fragment_scoped_rerun,
281
+ ):
282
+ return None
283
+
284
+ self._state = ScriptRequestType.CONTINUE
285
+ return ScriptRequest(ScriptRequestType.RERUN, self._rerun_data)
286
+
287
+ if self._state != ScriptRequestType.STOP: # pragma: no cover - defensive
288
+ raise RuntimeError(
289
+ f"Unrecognized ScriptRunnerState: {self._state}. This should never happen."
290
+ )
291
+ return ScriptRequest(ScriptRequestType.STOP)
292
+
293
+ def on_scriptrunner_ready(self) -> ScriptRequest:
294
+ """Called by the ScriptRunner when it's about to run its script for
295
+ the first time, and also after its script has successfully completed.
296
+
297
+ If we have a RERUN request, return the request and set
298
+ our internal state to CONTINUE.
299
+
300
+ If we have a STOP request or no request, set our internal state
301
+ to STOP.
302
+ """
303
+ with self._lock:
304
+ if self._state == ScriptRequestType.RERUN:
305
+ self._state = ScriptRequestType.CONTINUE
306
+ return ScriptRequest(ScriptRequestType.RERUN, self._rerun_data)
307
+
308
+ # If we don't have a rerun request, unconditionally change our
309
+ # state to STOP.
310
+ self._state = ScriptRequestType.STOP
311
+ return ScriptRequest(ScriptRequestType.STOP)
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/script_run_context.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import contextlib
18
+ import contextvars
19
+ import dataclasses
20
+ import threading
21
+ from collections.abc import Callable
22
+ from dataclasses import dataclass, field
23
+ from typing import (
24
+ TYPE_CHECKING,
25
+ Final,
26
+ TypeAlias,
27
+ TypedDict,
28
+ )
29
+
30
+ from typing_extensions import Unpack
31
+
32
+ from streamlit import config
33
+ from streamlit.errors import (
34
+ NoSessionContext,
35
+ )
36
+ from streamlit.logger import get_logger
37
+ from streamlit.runtime.forward_msg_cache import (
38
+ create_reference_msg,
39
+ populate_hash_if_needed,
40
+ )
41
+ from streamlit.runtime.parallel_coordinator import ParallelFragmentCoordinator
42
+ from streamlit.runtime.scriptrunner_utils.script_run_context_attr import (
43
+ SCRIPT_RUN_CONTEXT_ATTR_NAME,
44
+ )
45
+ from streamlit.runtime.scriptrunner_utils.shared_run_state import SharedRunState
46
+
47
+ if TYPE_CHECKING:
48
+ from collections.abc import Generator
49
+ from pathlib import Path
50
+
51
+ from streamlit.cursor import RunningCursor
52
+ from streamlit.proto.ClientState_pb2 import ContextInfo
53
+ from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
54
+ from streamlit.runtime.fragment import FragmentStorage
55
+ from streamlit.runtime.pages_manager import PagesManager
56
+ from streamlit.runtime.scriptrunner_utils.script_requests import ScriptRequests
57
+ from streamlit.runtime.state import SafeSessionState
58
+ from streamlit.runtime.uploaded_file_manager import UploadedFileManager
59
+
60
+ OnScriptErrorHandler: TypeAlias = Callable[[Exception], bool | None]
61
+
62
+ _LOGGER: Final = get_logger(__name__)
63
+
64
+ UserInfoType: TypeAlias = dict[str, str | bool | dict[str, str] | None]
65
+
66
+
67
+ # If true, it indicates that we are in a cached function that disallows the usage of
68
+ # widgets. Using contextvars to be thread-safe.
69
+ in_cached_function: contextvars.ContextVar[bool] = contextvars.ContextVar(
70
+ "in_cached_function", default=False
71
+ )
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class FragmentThreadState:
76
+ """Per-thread state for a fragment execution.
77
+
78
+ Frozen so that all mutations must go through ThreadState.update() or
79
+ ThreadState.scoped(), which rebind the ContextVar and guarantee context
80
+ isolation when using copy_context().
81
+ """
82
+
83
+ fragment_id: str | None = None
84
+ delta_path: tuple[int, ...] | None = None
85
+ in_fragment_callback: bool = False
86
+ active_script_hash: str = ""
87
+ # Set on parallel-fragment workers so wrapped_fragment() skips creating a
88
+ # second st.container(); the main thread already pre-allocated one before
89
+ # dispatching the worker. Cleared after first use.
90
+ pre_allocated_container_fragment_id: str | None = None
91
+ # True while executing inside a parallel fragment worker thread; used by
92
+ # _check_not_parallel_worker() to gate APIs that are unsafe during
93
+ # concurrent execution (e.g. st.dialog, st.switch_page).
94
+ is_parallel_worker: bool = False
95
+
96
+
97
+ class _FragmentThreadStateFields(TypedDict, total=False):
98
+ """Keyword-arg shape for ``ThreadState.{initialize, update, scoped}``.
99
+
100
+ Mirrors ``FragmentThreadState``'s fields. Using ``TypedDict + Unpack``
101
+ catches typos (e.g., ``fragmentid=`` vs ``fragment_id=``) and wrong
102
+ value types at type-check time rather than as a runtime ``TypeError``.
103
+ """
104
+
105
+ fragment_id: str | None
106
+ delta_path: tuple[int, ...] | None
107
+ in_fragment_callback: bool
108
+ active_script_hash: str
109
+ pre_allocated_container_fragment_id: str | None
110
+ is_parallel_worker: bool
111
+
112
+
113
+ _thread_state: contextvars.ContextVar[FragmentThreadState] = contextvars.ContextVar(
114
+ "fragment_thread_state",
115
+ )
116
+
117
+
118
+ class ThreadState:
119
+ """Encapsulates all access to the per-thread FragmentThreadState ContextVar.
120
+
121
+ The ContextVar ``_thread_state`` is module-private. External code interacts
122
+ exclusively through this class. The frozen dataclass ensures callers cannot
123
+ bypass the API — in-place mutation raises ``FrozenInstanceError``.
124
+ """
125
+
126
+ @staticmethod
127
+ def initialize(**kwargs: Unpack[_FragmentThreadStateFields]) -> None:
128
+ """Create a fresh FragmentThreadState and bind it in the current context.
129
+
130
+ Called from ``reset()`` at the start of every script run, and from
131
+ parallel fragment worker setup to seed the worker's copied context
132
+ with the parent's snapshot.
133
+ """
134
+ _thread_state.set(FragmentThreadState(**kwargs))
135
+
136
+ @staticmethod
137
+ def get() -> FragmentThreadState:
138
+ """Read the current context's FragmentThreadState.
139
+
140
+ Returns a frozen object — callers can read fields but cannot mutate
141
+ them. Raises ``RuntimeError`` if called before ``initialize()``.
142
+ """
143
+ try:
144
+ return _thread_state.get()
145
+ except LookupError:
146
+ raise RuntimeError(
147
+ "FragmentThreadState not initialized — "
148
+ "ScriptRunContext.reset() or add_script_run_ctx() must be "
149
+ "called on this thread first."
150
+ ) from None
151
+
152
+ @staticmethod
153
+ def update(**kwargs: Unpack[_FragmentThreadStateFields]) -> None:
154
+ """Update one or more fields on the current context's state.
155
+
156
+ Creates a new frozen dataclass via ``dataclasses.replace()`` and
157
+ rebinds the ContextVar, ensuring context isolation.
158
+ """
159
+ _thread_state.set(dataclasses.replace(ThreadState.get(), **kwargs))
160
+
161
+ @staticmethod
162
+ @contextlib.contextmanager
163
+ def scoped(
164
+ **overrides: Unpack[_FragmentThreadStateFields],
165
+ ) -> Generator[None, None, None]:
166
+ """Temporarily override fields, automatically restore on exit.
167
+
168
+ Uses ``ContextVar.reset(token)`` to atomically restore the entire
169
+ previous state. Used for nesting within a single thread (e.g. nested
170
+ fragments) where ``copy_context()`` is not involved.
171
+ """
172
+ token = _thread_state.set(dataclasses.replace(ThreadState.get(), **overrides))
173
+ try:
174
+ yield
175
+ finally:
176
+ _thread_state.reset(token)
177
+
178
+
179
+ @dataclass
180
+ class ScriptRunContext:
181
+ """A context object that contains data for a "script run" - that is,
182
+ data that's scoped to a single ScriptRunner execution (and therefore also
183
+ scoped to a single connected "session").
184
+
185
+ ScriptRunContext is used internally by virtually every `st.foo()` function.
186
+ It is accessed only from the script thread that's created by ScriptRunner,
187
+ or from app-created helper threads that have been "attached" to the
188
+ ScriptRunContext via `add_script_run_ctx`.
189
+
190
+ Streamlit code typically retrieves the active ScriptRunContext via the
191
+ `get_script_run_ctx` function.
192
+
193
+ Note: ``__post_init__`` adds a non-field ``_main_thread_ident`` used
194
+ by ``reset()``'s thread guard.
195
+ """
196
+
197
+ session_id: str
198
+ _enqueue: Callable[[ForwardMsg], None]
199
+ query_string: str
200
+ session_state: SafeSessionState
201
+ uploaded_file_mgr: UploadedFileManager
202
+ main_script_path: str
203
+ user_info: UserInfoType
204
+ fragment_storage: FragmentStorage
205
+ pages_manager: PagesManager
206
+ on_script_error: OnScriptErrorHandler | None = None
207
+
208
+ # Hashes of messages that are cached in the client browser:
209
+ cached_message_hashes: frozenset[str] = field(default_factory=frozenset)
210
+ context_info: ContextInfo | None = None
211
+ gather_usage_stats: bool = False
212
+ command_tracking_deactivated: bool = False
213
+ _has_script_started: bool = False
214
+ shared: SharedRunState = field(default_factory=SharedRunState)
215
+ cursors: dict[int, RunningCursor] = field(default_factory=dict)
216
+ script_requests: ScriptRequests | None = None
217
+ fragment_ids_this_run: list[str] | None = None
218
+ # we allow only one dialog to be open at the same time
219
+ has_dialog_opened: bool = False
220
+ parallel_coordinator: ParallelFragmentCoordinator | None = None
221
+
222
+ def __post_init__(self) -> None:
223
+ # Capture the main script thread's identity so reset() can refuse to
224
+ # run from worker threads.
225
+ self._main_thread_ident = threading.get_ident()
226
+
227
+ @property
228
+ def page_script_hash(self) -> str:
229
+ return self.pages_manager.current_page_script_hash
230
+
231
+ @property
232
+ def main_script_parent(self) -> Path:
233
+ return self.pages_manager.main_script_parent
234
+
235
+ @contextlib.contextmanager
236
+ def run_with_active_hash(self, page_hash: str) -> Generator[None, None, None]:
237
+ with ThreadState.scoped(active_script_hash=page_hash):
238
+ yield
239
+
240
+ def set_mpa_v2_page(self, page_script_hash: str) -> None:
241
+ ThreadState.update(active_script_hash=self.pages_manager.main_script_hash)
242
+ self.pages_manager.set_current_page_script_hash(page_script_hash)
243
+
244
+ def reset(
245
+ self,
246
+ query_string: str = "",
247
+ page_script_hash: str = "",
248
+ fragment_ids_this_run: list[str] | None = None,
249
+ cached_message_hashes: frozenset[str] | None = None,
250
+ context_info: ContextInfo | None = None,
251
+ # Checked by fragment workers to cease execution.
252
+ yield_check: Callable[[], None] = lambda: None,
253
+ ) -> None:
254
+ if threading.get_ident() != self._main_thread_ident:
255
+ raise RuntimeError(
256
+ "ScriptRunContext.reset() must only be called from the main "
257
+ "script thread"
258
+ )
259
+ # Check if this is a same-page rerun BEFORE updating page_script_hash
260
+ is_same_page = self.page_script_hash == page_script_hash
261
+
262
+ self.cursors = {}
263
+ self.shared.reset()
264
+ self.query_string = query_string
265
+ self.context_info = context_info
266
+ self.pages_manager.set_current_page_script_hash(page_script_hash)
267
+ ThreadState.initialize(
268
+ active_script_hash=self.pages_manager.main_script_hash,
269
+ )
270
+ self.parallel_coordinator = ParallelFragmentCoordinator(
271
+ yield_check=yield_check,
272
+ max_workers=config.get_option("runner.parallelMaxWorkers"),
273
+ )
274
+ self._has_script_started = False
275
+ self.command_tracking_deactivated: bool = False
276
+ self.fragment_ids_this_run = fragment_ids_this_run
277
+ self.has_dialog_opened = False
278
+ self.cached_message_hashes = frozenset(cached_message_hashes or ())
279
+
280
+ in_cached_function.set(False)
281
+
282
+ with self.session_state.query_params() as qp:
283
+ # For same-page reruns (widget interactions), populate _query_params from URL
284
+ # and set initial params for widget seeding.
285
+ # For page transitions, both populate_from_query_string() AND
286
+ # set_initial_query_params_from_current() are called in script_runner.py
287
+ # BEFORE reset() to ensure filtering is applied to both _query_params
288
+ # AND _initial_query_params, preventing stale params from previous pages
289
+ # from seeding widgets on the new page.
290
+ if is_same_page:
291
+ qp.set_initial_query_params(query_string)
292
+ qp.populate_from_query_string(query_string)
293
+
294
+ def on_script_start(self) -> None:
295
+ self._has_script_started = True
296
+
297
+ def enqueue(self, msg: ForwardMsg) -> None:
298
+ """Enqueue a ForwardMsg for this context's session."""
299
+ msg.metadata.active_script_hash = ThreadState.get().active_script_hash
300
+
301
+ # We populate the hash and cacheable field for all messages.
302
+ # Besides the forward message cache, the hash might also be used
303
+ # for other aspects within the frontend.
304
+ populate_hash_if_needed(msg)
305
+ msg_to_send = msg
306
+ if (
307
+ msg.metadata.cacheable
308
+ and msg.hash
309
+ and msg.hash in self.cached_message_hashes
310
+ ):
311
+ _LOGGER.debug("Sending cached message ref (hash=%s)", msg.hash)
312
+ msg_to_send = create_reference_msg(msg)
313
+
314
+ # Pass the message up to our associated ScriptRunner.
315
+ self._enqueue(msg_to_send)
316
+
317
+
318
+ # Thread-attached storage used by add_script_run_ctx:
319
+ # - Fields slot: parent FragmentThreadState snapshot, applied at run() time.
320
+ # - Install slot: sentinel that prevents thread.run from being wrapped
321
+ # more than once across repeated add_script_run_ctx() calls.
322
+ _FRAGMENT_THREAD_STATE_FIELDS_ATTR: Final = "_streamlit_fragment_thread_state_fields"
323
+ _FRAGMENT_THREAD_STATE_WRAP_INSTALLED_ATTR: Final = (
324
+ "_streamlit_fragment_thread_state_wrap_installed"
325
+ )
326
+
327
+
328
+ def add_script_run_ctx(
329
+ thread: threading.Thread | None = None, ctx: ScriptRunContext | None = None
330
+ ) -> threading.Thread:
331
+ """Attach the current ScriptRunContext to a thread and propagate the
332
+ parent's FragmentThreadState snapshot.
333
+
334
+ Normal usage: call from the parent thread, before the child starts.
335
+ Repeat attaches on the same not-yet-started thread are last-wins for
336
+ both ``ctx`` and the FragmentThreadState snapshot.
337
+
338
+ Self-attach fallback: when called from inside the thread it is
339
+ attaching to (current thread, or ``thread`` omitted with explicit
340
+ ``ctx``), ``ThreadState`` is seeded directly from ``ctx``. The
341
+ parent's ContextVar is not visible from another thread, so:
342
+
343
+ - ``fragment_id`` and ``delta_path`` are NOT propagated; worker
344
+ writes won't be stamped with the parent's ``fragment_id``.
345
+ - ``active_script_hash`` is seeded from
346
+ ``ctx.pages_manager.main_script_hash``. MPA v1 page bodies will
347
+ therefore see the main hash, not the page hash; migrate to MPA v2
348
+ / ``st.navigation`` if that matters. Locked in by
349
+ ``test_add_script_run_ctx_self_attach_uses_main_script_hash_not_page_hash``.
350
+
351
+ Parameters
352
+ ----------
353
+ thread : threading.Thread or None
354
+ Thread to attach to. Defaults to the current thread.
355
+ ctx : ScriptRunContext or None
356
+ Context to attach. Defaults to the caller's current
357
+ ScriptRunContext.
358
+
359
+ Returns
360
+ -------
361
+ threading.Thread
362
+ The same thread that was passed in, for chaining.
363
+
364
+ """
365
+ if thread is None:
366
+ thread = threading.current_thread()
367
+ if ctx is None:
368
+ ctx = get_script_run_ctx()
369
+ if ctx is not None:
370
+ setattr(thread, SCRIPT_RUN_CONTEXT_ATTR_NAME, ctx)
371
+
372
+ # ContextVars don't cross thread boundaries, so capture the parent's
373
+ # FragmentThreadState and initialize it when the child thread starts.
374
+ try:
375
+ parent_ts = ThreadState.get()
376
+ except RuntimeError:
377
+ parent_ts = None
378
+
379
+ if parent_ts is not None:
380
+ # Store the parent snapshot on the thread; the run() wrapper below
381
+ # reads it at start time. Repeat add_script_run_ctx() calls refresh
382
+ # the snapshot — last attach wins, matching the ctx attachment above.
383
+ setattr(
384
+ thread,
385
+ _FRAGMENT_THREAD_STATE_FIELDS_ATTR,
386
+ dataclasses.asdict(parent_ts),
387
+ )
388
+ # Skip the wrap if the target is already running: run() has
389
+ # already been called, and setting the sentinel here would
390
+ # pollute the main thread across tests.
391
+ if thread is not threading.current_thread() and not getattr(
392
+ thread, _FRAGMENT_THREAD_STATE_WRAP_INSTALLED_ATTR, False
393
+ ):
394
+ original_run = thread.run
395
+
396
+ def _run_with_thread_state(*args: object, **kwargs: object) -> None:
397
+ fields = getattr(thread, _FRAGMENT_THREAD_STATE_FIELDS_ATTR, None)
398
+ if fields is not None:
399
+ ThreadState.initialize(**fields)
400
+ original_run(*args, **kwargs)
401
+
402
+ thread.run = _run_with_thread_state # type: ignore[method-assign] # ty: ignore[invalid-assignment]
403
+ setattr(thread, _FRAGMENT_THREAD_STATE_WRAP_INSTALLED_ATTR, True)
404
+ elif ctx is not None and thread is threading.current_thread():
405
+ # Caller is attaching ctx from inside the currently-running
406
+ # thread, so the thread.run wrap above is moot. Seed ThreadState
407
+ # directly from ctx so subsequent ThreadState.get() /
408
+ # enqueue_message() calls don't crash. See the add_script_run_ctx
409
+ # docstring for the self-attach behaviour contract.
410
+ #
411
+ # Two callers exercise this branch:
412
+ # 1. ScriptRunner._run_script_thread, before ctx.reset() reseeds.
413
+ # 2. User code calling add_script_run_ctx(ctx=saved_ctx) from
414
+ # inside a worker thread (documented against, but a real
415
+ # pattern).
416
+ ThreadState.initialize(
417
+ active_script_hash=ctx.pages_manager.main_script_hash,
418
+ )
419
+
420
+ return thread
421
+
422
+
423
+ def get_script_run_ctx(suppress_warning: bool = False) -> ScriptRunContext | None:
424
+ """
425
+ Parameters
426
+ ----------
427
+ suppress_warning : bool
428
+ If True, don't log a warning if there's no ScriptRunContext.
429
+
430
+ Returns
431
+ -------
432
+ ScriptRunContext | None
433
+ The current thread's ScriptRunContext, or None if it doesn't have one.
434
+
435
+ """
436
+ thread = threading.current_thread()
437
+ ctx: ScriptRunContext | None = getattr(thread, SCRIPT_RUN_CONTEXT_ATTR_NAME, None)
438
+ if ctx is None and not suppress_warning:
439
+ # Only warn about a missing ScriptRunContext if suppress_warning is False, and
440
+ # we were started via `streamlit run`. Otherwise, the user is likely running a
441
+ # script "bare", and doesn't need to be warned about streamlit
442
+ # bits that are irrelevant when not connected to a session.
443
+ _LOGGER.warning(
444
+ "Thread '%s': missing ScriptRunContext! This warning can be ignored when "
445
+ "running in bare mode.",
446
+ thread.name,
447
+ )
448
+
449
+ return ctx
450
+
451
+
452
+ def enqueue_message(msg: ForwardMsg) -> None:
453
+ """Enqueues a ForwardMsg proto to send to the app."""
454
+ ctx = get_script_run_ctx()
455
+
456
+ if ctx is None:
457
+ raise NoSessionContext()
458
+
459
+ ts = ThreadState.get()
460
+ if ts.fragment_id and msg.WhichOneof("type") == "delta":
461
+ msg.delta.fragment_id = ts.fragment_id
462
+
463
+ ctx.enqueue(msg)
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/script_run_context_attr.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """The thread attribute name under which the active ScriptRunContext is stored.
16
+
17
+ This is a dependency-free leaf module so that both ``script_run_context`` and
18
+ ``parallel_coordinator`` can share the constant without importing each other.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from typing import Final
24
+
25
+ SCRIPT_RUN_CONTEXT_ATTR_NAME: Final = "streamlit_script_run_ctx"
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/shared_run_state.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import collections
18
+ import threading
19
+ from typing import TYPE_CHECKING
20
+
21
+ from streamlit.runtime.scriptrunner_utils.thread_safe_set import ThreadSafeSet
22
+
23
+ if TYPE_CHECKING:
24
+ from streamlit.proto.PageProfile_pb2 import Command
25
+
26
+
27
+ class SharedRunState:
28
+ """Thread-safe container for shared mutable state during a script run.
29
+
30
+ A single instance is shared across the main thread and all worker threads.
31
+ Callers access state only through synchronized methods — direct field
32
+ access to the underlying data structures is not exposed.
33
+ """
34
+
35
+ def __init__(self) -> None:
36
+ self.widget_ids_this_run: ThreadSafeSet[str] = ThreadSafeSet()
37
+ self.widget_user_keys_this_run: ThreadSafeSet[str] = ThreadSafeSet()
38
+ self.form_ids_this_run: ThreadSafeSet[str] = ThreadSafeSet()
39
+ self.new_fragment_ids: ThreadSafeSet[str] = ThreadSafeSet()
40
+
41
+ self._telemetry_lock = threading.Lock()
42
+ self._tracked_commands: list[Command] = []
43
+ self._tracked_commands_counter: collections.Counter[str] = collections.Counter()
44
+
45
+ def reset(self) -> None:
46
+ """Re-initialize all shared mutable state for a new script run.
47
+
48
+ Must only be called from the main script thread before parallel
49
+ dispatch.
50
+ """
51
+ self.widget_ids_this_run.clear()
52
+ self.widget_user_keys_this_run.clear()
53
+ self.form_ids_this_run.clear()
54
+ self.new_fragment_ids.clear()
55
+
56
+ with self._telemetry_lock:
57
+ self._tracked_commands = []
58
+ self._tracked_commands_counter = collections.Counter()
59
+
60
+ @property
61
+ def tracked_commands(self) -> tuple[Command, ...]:
62
+ """An immutable snapshot of tracked commands."""
63
+ with self._telemetry_lock:
64
+ return tuple(self._tracked_commands)
65
+
66
+ @property
67
+ def tracked_commands_count(self) -> int:
68
+ """The number of commands stored in the tracked list (capped)."""
69
+ with self._telemetry_lock:
70
+ return len(self._tracked_commands)
71
+
72
+ def track_command(self, command: Command, max_per_command: int) -> None:
73
+ """Atomically track a command.
74
+
75
+ Appends the command to the list if it is under the per-command cap, and
76
+ always updates the counter.
77
+ """
78
+ with self._telemetry_lock:
79
+ if self._tracked_commands_counter[command.name] < max_per_command:
80
+ self._tracked_commands.append(command)
81
+ self._tracked_commands_counter.update([command.name])
82
+
83
+ def command_count_for(self, name: str) -> int:
84
+ """Return how many times a command name has been tracked."""
85
+ with self._telemetry_lock:
86
+ return self._tracked_commands_counter[name]
venv/Lib/site-packages/streamlit/runtime/scriptrunner_utils/thread_safe_set.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import threading
18
+ from collections.abc import Hashable
19
+ from typing import Generic, NoReturn, TypeVar
20
+
21
+ T = TypeVar("T", bound=Hashable)
22
+
23
+
24
+ class ThreadSafeSet(Generic[T]):
25
+ """A thread-safe set wrapper that enforces controlled access via atomic methods.
26
+
27
+ This replaces bare ``set[str]`` fields where callers previously did non-atomic
28
+ check-then-add operations. The underlying set is never exposed directly —
29
+ callers interact only through ``check_and_add``, ``__contains__``, ``snapshot``,
30
+ and ``clear``. The ``snapshot`` method returns an immutable ``frozenset``,
31
+ enforcing the expectation that these sets are read-only once handed off to
32
+ downstream consumers (e.g. ``SessionState.on_script_finished``).
33
+ """
34
+
35
+ def __init__(self) -> None:
36
+ self._lock = threading.Lock()
37
+ self._data: set[T] = set()
38
+
39
+ def check_and_add(self, value: T) -> bool:
40
+ """Atomically check membership and add. Returns True if the value was new."""
41
+ with self._lock:
42
+ is_new = value not in self._data
43
+ self._data.add(value)
44
+ return is_new
45
+
46
+ def __contains__(self, value: object) -> bool:
47
+ with self._lock:
48
+ return value in self._data
49
+
50
+ def clear(self) -> None:
51
+ """Reset to empty."""
52
+ with self._lock:
53
+ self._data.clear()
54
+
55
+ def snapshot(self) -> frozenset[T]:
56
+ """Return an immutable copy for read-only consumers."""
57
+ with self._lock:
58
+ return frozenset(self._data)
59
+
60
+ def __deepcopy__(self, memo: dict[int, object]) -> NoReturn:
61
+ raise TypeError(
62
+ "ThreadSafeSet does not support deepcopy; "
63
+ "use .snapshot() for an immutable copy"
64
+ )
65
+
66
+ def __copy__(self) -> NoReturn:
67
+ raise TypeError(
68
+ "ThreadSafeSet does not support copy; use .snapshot() for an immutable copy"
69
+ )
venv/Lib/site-packages/streamlit/runtime/secrets.py ADDED
@@ -0,0 +1,652 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import threading
19
+ from collections.abc import Callable, ItemsView, Iterator, KeysView, Mapping, ValuesView
20
+ from copy import deepcopy
21
+ from typing import (
22
+ Any,
23
+ Final,
24
+ NoReturn,
25
+ )
26
+
27
+ from blinker import Signal
28
+
29
+ import streamlit.watcher.path_watcher
30
+ from streamlit import config, runtime
31
+ from streamlit.errors import StreamlitMaxRetriesError, StreamlitSecretNotFoundError
32
+ from streamlit.logger import get_logger
33
+
34
+ _LOGGER: Final = get_logger(__name__)
35
+
36
+ # Type alias for programmatic secrets values.
37
+ # Supported types: str, int, float, bool, lists, and nested dicts.
38
+ SecretsValue = (
39
+ str | int | float | bool | list["SecretsValue"] | dict[str, "SecretsValue"]
40
+ )
41
+
42
+ # Allowed scalar types for secrets values
43
+ _ALLOWED_SCALAR_TYPES: Final[frozenset[type]] = frozenset({str, int, float, bool})
44
+
45
+
46
+ def _validate_secrets_value(value: Any, path: str = "") -> None:
47
+ """Validate that a secrets value has an allowed type.
48
+
49
+ Parameters
50
+ ----------
51
+ value
52
+ The value to validate.
53
+ path
54
+ The path to this value (for error messages). Dict keys use dotted
55
+ notation (e.g. ``outer.inner``) and list elements use bracket indexing
56
+ (e.g. ``outer.inner[2]``).
57
+
58
+ Raises
59
+ ------
60
+ TypeError
61
+ If the value has an unsupported type.
62
+ """
63
+ if isinstance(value, dict):
64
+ for key, nested_value in value.items():
65
+ if not isinstance(key, str):
66
+ key_path = f"in '{path}'" if path else "at top level"
67
+ raise TypeError(
68
+ f"Dictionary keys in secrets must be strings, "
69
+ f"got {type(key).__name__!r} {key_path}."
70
+ )
71
+ nested_path = f"{path}.{key}" if path else key
72
+ _validate_secrets_value(nested_value, nested_path)
73
+ elif isinstance(value, list):
74
+ for index, nested_value in enumerate(value):
75
+ nested_path = f"{path}[{index}]" if path else f"[{index}]"
76
+ _validate_secrets_value(nested_value, nested_path)
77
+ # Use type() instead of isinstance() because bool is a subclass of int,
78
+ # and we need to distinguish them for os.environ promotion (bool excluded).
79
+ elif type(value) not in _ALLOWED_SCALAR_TYPES:
80
+ type_name = type(value).__name__
81
+ path_info = f" at '{path}'" if path else ""
82
+ raise TypeError(
83
+ f"Unsupported type '{type_name}'{path_info} in secrets. "
84
+ f"Allowed types are: str, int, float, bool, lists, and nested dicts."
85
+ )
86
+
87
+
88
+ class SecretErrorMessages:
89
+ """SecretErrorMessages stores all error messages we use for secrets to allow customization
90
+ for different environments.
91
+
92
+ For example Streamlit Cloud can customize the message to be different than the open source.
93
+
94
+ For internal use, may change in future releases without notice.
95
+ """
96
+
97
+ def __init__(self) -> None:
98
+ self.missing_attr_message: Callable[[str], str] = lambda attr_name: (
99
+ f'st.secrets has no attribute "{attr_name}". '
100
+ "Did you forget to add it to secrets.toml, mount it to secret directory, or the app settings "
101
+ "on Streamlit Cloud? More info: "
102
+ "https://docs.streamlit.io/deploy/streamlit-community-cloud/deploy-your-app/secrets-management"
103
+ )
104
+ self.missing_key_message: Callable[[str], str] = lambda key: (
105
+ f'st.secrets has no key "{key}". '
106
+ "Did you forget to add it to secrets.toml, mount it to secret directory, or the app settings "
107
+ "on Streamlit Cloud? More info: "
108
+ "https://docs.streamlit.io/deploy/streamlit-community-cloud/deploy-your-app/secrets-management"
109
+ )
110
+ self.no_secrets_found: Callable[[list[str]], str] = lambda file_paths: (
111
+ f"No secrets found. Valid paths for a secrets.toml file or secret directories are: {', '.join(file_paths)}"
112
+ )
113
+ self.error_parsing_file_at_path: Callable[[str, Exception], str] = (
114
+ lambda path, ex: f"Error parsing secrets file at {path}: {ex}"
115
+ )
116
+ self.subfolder_path_is_not_a_folder: Callable[[str], str] = (
117
+ lambda sub_folder_path: (
118
+ f"{sub_folder_path} is not a folder. "
119
+ "To use directory based secrets, mount every secret in a subfolder under the secret directory"
120
+ )
121
+ )
122
+ self.invalid_secret_path: Callable[[str], str] = lambda path: (
123
+ f"Invalid secrets path: {path}: path is not a .toml file or a directory"
124
+ )
125
+
126
+ def set_missing_attr_message(self, message: Callable[[str], str]) -> None:
127
+ """Set the missing attribute error message."""
128
+ self.missing_attr_message = message
129
+
130
+ def set_missing_key_message(self, message: Callable[[str], str]) -> None:
131
+ """Set the missing key error message."""
132
+ self.missing_key_message = message
133
+
134
+ def set_no_secrets_found_message(self, message: Callable[[list[str]], str]) -> None:
135
+ """Set the no secrets found error message."""
136
+ self.no_secrets_found = message
137
+
138
+ def set_error_parsing_file_at_path_message(
139
+ self, message: Callable[[str, Exception], str]
140
+ ) -> None:
141
+ """Set the error parsing file at path error message."""
142
+ self.error_parsing_file_at_path = message
143
+
144
+ def set_subfolder_path_is_not_a_folder_message(
145
+ self, message: Callable[[str], str]
146
+ ) -> None:
147
+ """Set the subfolder path is not a folder error message."""
148
+ self.subfolder_path_is_not_a_folder = message
149
+
150
+ def set_invalid_secret_path_message(self, message: Callable[[str], str]) -> None:
151
+ """Set the invalid secret path error message."""
152
+ self.invalid_secret_path = message
153
+
154
+ def get_missing_attr_message(self, attr_name: str) -> str:
155
+ """Get the missing attribute error message."""
156
+ return self.missing_attr_message(attr_name)
157
+
158
+ def get_missing_key_message(self, key: str) -> str:
159
+ """Get the missing key error message."""
160
+ return self.missing_key_message(key)
161
+
162
+ def get_no_secrets_found_message(self, file_paths: list[str]) -> str:
163
+ """Get the no secrets found error message."""
164
+ return self.no_secrets_found(file_paths)
165
+
166
+ def get_error_parsing_file_at_path_message(self, path: str, ex: Exception) -> str:
167
+ """Get the error parsing file at path error message."""
168
+ return self.error_parsing_file_at_path(path, ex)
169
+
170
+ def get_subfolder_path_is_not_a_folder_message(self, sub_folder_path: str) -> str:
171
+ """Get the subfolder path is not a folder error message."""
172
+ return self.subfolder_path_is_not_a_folder(sub_folder_path)
173
+
174
+ def get_invalid_secret_path_message(self, path: str) -> str:
175
+ """Get the invalid secret path error message."""
176
+ return self.invalid_secret_path(path)
177
+
178
+
179
+ secret_error_messages_singleton: Final = SecretErrorMessages()
180
+
181
+
182
+ def _convert_to_dict(obj: Mapping[str, Any] | AttrDict) -> dict[str, Any]:
183
+ """Convert Mapping or AttrDict objects to dictionaries."""
184
+ if isinstance(obj, AttrDict):
185
+ return obj.to_dict()
186
+ return {k: v.to_dict() if isinstance(v, AttrDict) else v for k, v in obj.items()}
187
+
188
+
189
+ def _missing_attr_error_message(attr_name: str) -> str:
190
+ return secret_error_messages_singleton.get_missing_attr_message(attr_name)
191
+
192
+
193
+ def _missing_key_error_message(key: str) -> str:
194
+ return secret_error_messages_singleton.get_missing_key_message(key)
195
+
196
+
197
+ class AttrDict(Mapping[str, Any]):
198
+ """We use AttrDict to wrap up dictionary values from secrets
199
+ to provide dot access to nested secrets.
200
+ """
201
+
202
+ def __init__(self, value: Mapping[str, Any]) -> None:
203
+ self.__dict__["__nested_secrets__"] = dict(value)
204
+
205
+ @staticmethod
206
+ def _maybe_wrap_in_attr_dict(value: Any) -> Any:
207
+ if not isinstance(value, Mapping):
208
+ return value
209
+ return AttrDict(value)
210
+
211
+ def __len__(self) -> int:
212
+ return len(self.__nested_secrets__)
213
+
214
+ def __iter__(self) -> Iterator[str]:
215
+ return iter(self.__nested_secrets__)
216
+
217
+ def __getitem__(self, key: str) -> Any:
218
+ try:
219
+ value = self.__nested_secrets__[key]
220
+ return self._maybe_wrap_in_attr_dict(value)
221
+ except KeyError:
222
+ raise KeyError(_missing_key_error_message(key))
223
+
224
+ def __getattr__(self, attr_name: str) -> Any:
225
+ try:
226
+ value = self.__nested_secrets__[attr_name]
227
+ return self._maybe_wrap_in_attr_dict(value)
228
+ except KeyError:
229
+ raise AttributeError(_missing_attr_error_message(attr_name))
230
+
231
+ def __repr__(self) -> str:
232
+ return repr(self.__nested_secrets__)
233
+
234
+ def __setitem__(self, key: str, value: Any) -> NoReturn:
235
+ raise TypeError("Secrets does not support item assignment.")
236
+
237
+ def __setattr__(self, key: str, value: Any) -> NoReturn:
238
+ raise TypeError("Secrets does not support attribute assignment.")
239
+
240
+ def to_dict(self) -> dict[str, Any]:
241
+ return deepcopy(self.__nested_secrets__)
242
+
243
+
244
+ class Secrets(Mapping[str, Any]):
245
+ """A dict-like class that stores secrets.
246
+ Parses secrets.toml on-demand. Cannot be externally mutated.
247
+
248
+ Safe to use from multiple threads.
249
+ """
250
+
251
+ def __init__(self) -> None:
252
+ # Our secrets dict.
253
+ self._secrets: Mapping[str, Any] | None = None
254
+ self._lock = threading.RLock()
255
+ self._file_watchers_installed = False
256
+ # Store programmatic secrets separately so they survive file-change reloads
257
+ self._programmatic_secrets: Mapping[str, SecretsValue] | None = None
258
+
259
+ self.file_change_listener = Signal(
260
+ doc="Emitted when a `secrets.toml` file has been changed."
261
+ )
262
+
263
+ def load_if_toml_exists(self) -> bool:
264
+ """Load secrets.toml files from disk if they exists. If none exist,
265
+ no exception will be raised. (If a file exists but is malformed,
266
+ an exception *will* be raised.).
267
+
268
+ Returns True if a secrets.toml file was successfully parsed, False otherwise.
269
+
270
+ Thread-safe.
271
+ """
272
+ try:
273
+ self._parse()
274
+
275
+ return True
276
+ except StreamlitSecretNotFoundError:
277
+ # No secrets.toml files exist. That's fine.
278
+ return False
279
+
280
+ def set_suppress_print_error_on_exception(
281
+ self, suppress_print_error_on_exception: bool
282
+ ) -> None:
283
+ """Left in place for compatibility with integrations until integration
284
+ code can be updated.
285
+ """
286
+
287
+ def _reset(self) -> None:
288
+ """Clear the secrets dictionary and remove any secrets that were
289
+ added to os.environ.
290
+
291
+ Thread-safe.
292
+ """
293
+ with self._lock:
294
+ if self._secrets is None:
295
+ return
296
+
297
+ for k, v in self._secrets.items():
298
+ self._maybe_delete_environment_variable(k, v)
299
+ self._secrets = None
300
+
301
+ def _parse_toml_file(self, path: str) -> tuple[Mapping[str, Any], bool]:
302
+ """Parse a TOML file and return the secrets as a dictionary."""
303
+ secrets = {}
304
+ found_secrets_file = False
305
+
306
+ try:
307
+ with open(path, encoding="utf-8") as f:
308
+ secrets_file_str = f.read()
309
+
310
+ found_secrets_file = True
311
+ except FileNotFoundError:
312
+ # the default config for secrets contains two paths. It's likely one of will not have secrets file.
313
+ return {}, False
314
+
315
+ import toml
316
+
317
+ try:
318
+ secrets.update(toml.loads(secrets_file_str))
319
+ except (TypeError, toml.TomlDecodeError) as ex:
320
+ msg = (
321
+ secret_error_messages_singleton.get_error_parsing_file_at_path_message(
322
+ path, ex
323
+ )
324
+ )
325
+ raise StreamlitSecretNotFoundError(msg) from ex
326
+
327
+ return secrets, found_secrets_file
328
+
329
+ def _parse_directory(self, path: str) -> tuple[Mapping[str, Any], bool]:
330
+ """Parse a directory for secrets. Directory style can be used to support Kubernetes secrets that are
331
+ mounted to folders.
332
+
333
+ Example structure:
334
+ - top_level_secret_folder
335
+ - user_pass_secret (folder)
336
+ - username (file), content: myuser
337
+ - password (file), content: mypassword
338
+ - my_plain_secret (folder)
339
+ - regular_secret (file), content: mysecret
340
+
341
+ See: https://kubernetes.io/docs/tasks/inject-data-application/distribute-credentials-secure/#create-a-pod-that-has-access-to-the-secret-data-through-a-volume
342
+ And: https://docs.snowflake.com/en/developer-guide/snowpark-container-services/additional-considerations-services-jobs#passing-secrets-in-local-container-files
343
+ """
344
+ secrets: dict[str, Any] = {}
345
+ found_secrets_file = False
346
+
347
+ for dirname in os.listdir(path):
348
+ sub_folder_path = os.path.join(path, dirname)
349
+ if not os.path.isdir(sub_folder_path):
350
+ error_msg = secret_error_messages_singleton.get_subfolder_path_is_not_a_folder_message(
351
+ sub_folder_path
352
+ )
353
+ raise StreamlitSecretNotFoundError(error_msg)
354
+ sub_secrets = {}
355
+
356
+ for filename in os.listdir(sub_folder_path):
357
+ file_path = os.path.join(sub_folder_path, filename)
358
+
359
+ # ignore folders
360
+ if os.path.isdir(file_path):
361
+ continue
362
+
363
+ with open(file_path, encoding="utf-8") as f:
364
+ sub_secrets[filename] = f.read().strip()
365
+ found_secrets_file = True
366
+
367
+ if len(sub_secrets) == 1:
368
+ # if there's just one file, collapse it so it's directly under `dirname`
369
+ secrets[dirname] = sub_secrets[next(iter(sub_secrets.keys()))]
370
+ else:
371
+ secrets[dirname] = sub_secrets
372
+
373
+ return secrets, found_secrets_file
374
+
375
+ def _parse_file_path(self, path: str) -> tuple[Mapping[str, Any], bool]:
376
+ if path.endswith(".toml"):
377
+ return self._parse_toml_file(path)
378
+
379
+ if os.path.isdir(path):
380
+ return self._parse_directory(path)
381
+
382
+ error_msg = secret_error_messages_singleton.get_invalid_secret_path_message(
383
+ path
384
+ )
385
+ raise StreamlitSecretNotFoundError(error_msg)
386
+
387
+ def _parse(self) -> Mapping[str, Any]:
388
+ """Parse our secrets.toml files if they're not already parsed.
389
+ This function is safe to call from multiple threads.
390
+
391
+ Raises
392
+ ------
393
+ StreamlitSecretNotFoundError
394
+ Raised if secrets.toml doesn't exist.
395
+
396
+ """
397
+ # Avoid taking a lock for the common case where secrets are already
398
+ # loaded.
399
+ secrets = self._secrets
400
+ if secrets is not None:
401
+ return secrets
402
+
403
+ with self._lock:
404
+ if self._secrets is not None:
405
+ return self._secrets
406
+
407
+ secrets = {}
408
+
409
+ file_paths = config.get_option("secrets.files")
410
+ found_secrets_file = False
411
+ for path in file_paths:
412
+ path_secrets, found_secrets_file_in_path = self._parse_file_path(path)
413
+ found_secrets_file = found_secrets_file or found_secrets_file_in_path
414
+ secrets.update(path_secrets)
415
+
416
+ if not found_secrets_file:
417
+ error_msg = (
418
+ secret_error_messages_singleton.get_no_secrets_found_message(
419
+ file_paths
420
+ )
421
+ )
422
+ raise StreamlitSecretNotFoundError(error_msg)
423
+
424
+ for k, v in secrets.items():
425
+ self._maybe_set_environment_variable(k, v)
426
+
427
+ self._secrets = secrets
428
+ self._maybe_install_file_watchers()
429
+
430
+ return self._secrets
431
+
432
+ def to_dict(self) -> dict[str, Any]:
433
+ """Converts the secrets store into a nested dictionary, where nested AttrDict objects are
434
+ also converted into dictionaries.
435
+ """
436
+ secrets = self._parse()
437
+ return _convert_to_dict(secrets)
438
+
439
+ def merge_programmatic_secrets(
440
+ self, programmatic_secrets: Mapping[str, SecretsValue]
441
+ ) -> None:
442
+ """Merge programmatic secrets into the secrets store.
443
+
444
+ Programmatic secrets are shallow-merged with file-based secrets at the
445
+ top level: entire top-level keys are replaced, not individual nested keys.
446
+
447
+ Parameters
448
+ ----------
449
+ programmatic_secrets
450
+ A dictionary of secrets to merge. Supported value types are:
451
+ ``str``, ``int``, ``float``, ``bool``, ``list``, and nested ``dict``.
452
+ Lists and dicts are validated recursively, so their elements must
453
+ themselves be supported secrets types.
454
+
455
+ Raises
456
+ ------
457
+ TypeError
458
+ If any value in the dictionary has an unsupported type.
459
+
460
+ Notes
461
+ -----
462
+ This method is intended to be called once during application startup,
463
+ after file-based secrets have been loaded. It is thread-safe.
464
+
465
+ Top-level ``str``, ``int``, and ``float`` values are promoted to
466
+ ``os.environ`` (as strings), matching the behavior of file-based secrets.
467
+ """
468
+ # Validate all keys are strings and values have allowed types
469
+ _validate_secrets_value(dict(programmatic_secrets))
470
+
471
+ with self._lock:
472
+ # Store programmatic secrets so they survive file-change reloads
473
+ self._programmatic_secrets = programmatic_secrets
474
+ self._apply_programmatic_secrets(programmatic_secrets)
475
+
476
+ def _apply_programmatic_secrets(
477
+ self, programmatic_secrets: Mapping[str, SecretsValue]
478
+ ) -> None:
479
+ """Apply programmatic secrets to the secrets store.
480
+
481
+ This is an internal helper that merges the given programmatic secrets
482
+ into `self._secrets`. It does NOT store them in `_programmatic_secrets`
483
+ (that is the caller's responsibility).
484
+
485
+ Must be called with `self._lock` held.
486
+ """
487
+ # Create a mutable copy of current secrets
488
+ current_secrets: dict[str, Any] = (
489
+ dict(self._secrets) if self._secrets is not None else {}
490
+ )
491
+
492
+ for key, value in programmatic_secrets.items():
493
+ # Remove old environment variable if the key existed
494
+ if key in current_secrets:
495
+ self._maybe_delete_environment_variable(key, current_secrets[key])
496
+
497
+ # Shallow-merge: replace entire top-level key (deep copy to prevent
498
+ # external mutation)
499
+ current_secrets[key] = deepcopy(value)
500
+
501
+ # Promote to os.environ if appropriate
502
+ self._maybe_set_environment_variable(key, value)
503
+
504
+ self._secrets = current_secrets
505
+
506
+ @staticmethod
507
+ def _maybe_set_environment_variable(k: Any, v: Any) -> None:
508
+ """Add the given key/value pair to os.environ if the value
509
+ is a string, int, or float.
510
+ """
511
+ value_type = type(v)
512
+ if value_type in {str, int, float}:
513
+ os.environ[k] = str(v)
514
+
515
+ @staticmethod
516
+ def _maybe_delete_environment_variable(k: Any, v: Any) -> None:
517
+ """Remove the given key/value pair from os.environ if the value
518
+ is a string, int, or float.
519
+ """
520
+ value_type = type(v)
521
+ # Compare with str(v) since os.environ values are always strings
522
+ if value_type in {str, int, float} and os.environ.get(k) == str(v):
523
+ del os.environ[k]
524
+
525
+ def _maybe_install_file_watchers(self) -> None:
526
+ with self._lock:
527
+ if self._file_watchers_installed:
528
+ return
529
+
530
+ file_paths = config.get_option("secrets.files")
531
+ for path in file_paths:
532
+ try:
533
+ if path.endswith(".toml"):
534
+ streamlit.watcher.path_watcher.watch_file(
535
+ path,
536
+ self._on_secrets_changed,
537
+ watcher_type="poll",
538
+ )
539
+ else:
540
+ streamlit.watcher.path_watcher.watch_dir(
541
+ path,
542
+ self._on_secrets_changed,
543
+ watcher_type="poll",
544
+ )
545
+ except (StreamlitMaxRetriesError, FileNotFoundError): # noqa: PERF203
546
+ # A user may only have one secrets.toml file defined, so we'd expect
547
+ # exceptions to be raised here when attempting to install a
548
+ # watcher on the nonexistent ones.
549
+ pass
550
+
551
+ # We set file_watchers_installed to True even if the installation attempt
552
+ # failed to avoid repeatedly trying to install it.
553
+ self._file_watchers_installed = True
554
+
555
+ def _on_secrets_changed(self, changed_file_path: str) -> None:
556
+ with self._lock:
557
+ _LOGGER.debug("Secret path %s changed, reloading", changed_file_path)
558
+ self._reset()
559
+ self._parse()
560
+ # Re-apply programmatic secrets so they survive file-change reloads
561
+ if self._programmatic_secrets:
562
+ self._apply_programmatic_secrets(self._programmatic_secrets)
563
+
564
+ # Emit a signal to notify receivers that the `secrets.toml` file
565
+ # has been changed.
566
+ self.file_change_listener.send()
567
+
568
+ def __getattr__(self, key: str) -> Any:
569
+ """Return the value with the given key. If no such key
570
+ exists, raise an AttributeError.
571
+
572
+ Thread-safe.
573
+ """
574
+ try:
575
+ value = self._parse()[key]
576
+ if not isinstance(value, Mapping):
577
+ return value
578
+ return AttrDict(value)
579
+ # We add FileNotFoundError since __getattr__ is expected to only raise
580
+ # AttributeError and mocking utilities expect that contract.
581
+ except (KeyError, FileNotFoundError):
582
+ raise AttributeError(_missing_attr_error_message(key))
583
+
584
+ def __getitem__(self, key: str) -> Any:
585
+ """Return the value with the given key. If no such key
586
+ exists, raise a KeyError.
587
+
588
+ Thread-safe.
589
+ """
590
+ try:
591
+ value = self._parse()[key]
592
+ if not isinstance(value, Mapping):
593
+ return value
594
+ return AttrDict(value)
595
+ except KeyError:
596
+ raise KeyError(_missing_key_error_message(key))
597
+
598
+ def __setattr__(self, key: str, value: Any) -> None:
599
+ # Allow internal attributes to be set
600
+ if key in {
601
+ "_secrets",
602
+ "_lock",
603
+ "_file_watchers_installed",
604
+ "_suppress_print_error_on_exception",
605
+ "_programmatic_secrets",
606
+ "file_change_listener",
607
+ "load_if_toml_exists",
608
+ }:
609
+ super().__setattr__(key, value)
610
+ else:
611
+ raise TypeError("Secrets does not support attribute assignment.")
612
+
613
+ def __repr__(self) -> str:
614
+ # If the runtime is NOT initialized, it is a method call outside
615
+ # the streamlit app, so we avoid reading the secrets file as it may not exist.
616
+ # If the runtime is initialized, display the contents of the file and
617
+ # the file must already exist.
618
+ """A string representation of the contents of the dict. Thread-safe."""
619
+ if not runtime.exists():
620
+ return f"{self.__class__.__name__}"
621
+ return repr(self._parse())
622
+
623
+ def __len__(self) -> int:
624
+ """The number of entries in the dict. Thread-safe."""
625
+ return len(self._parse())
626
+
627
+ def has_key(self, k: str) -> bool:
628
+ """True if the given key is in the dict. Thread-safe."""
629
+ return k in self._parse()
630
+
631
+ def keys(self) -> KeysView[str]:
632
+ """A view of the keys in the dict. Thread-safe."""
633
+ return self._parse().keys()
634
+
635
+ def values(self) -> ValuesView[Any]:
636
+ """A view of the values in the dict. Thread-safe."""
637
+ return self._parse().values()
638
+
639
+ def items(self) -> ItemsView[str, Any]:
640
+ """A view of the key-value items in the dict. Thread-safe."""
641
+ return self._parse().items()
642
+
643
+ def __contains__(self, key: Any) -> bool:
644
+ """True if the given key is in the dict. Thread-safe."""
645
+ return key in self._parse()
646
+
647
+ def __iter__(self) -> Iterator[str]:
648
+ """An iterator over the keys in the dict. Thread-safe."""
649
+ return iter(self._parse())
650
+
651
+
652
+ secrets_singleton: Final = Secrets()
venv/Lib/site-packages/streamlit/runtime/session_manager.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ from abc import abstractmethod
18
+ from dataclasses import dataclass
19
+ from typing import TYPE_CHECKING, Protocol, cast, runtime_checkable
20
+
21
+ if TYPE_CHECKING:
22
+ from collections.abc import Callable, Iterable, Mapping
23
+
24
+ from streamlit.proto.ForwardMsg_pb2 import ForwardMsg
25
+ from streamlit.runtime.app_session import AppSession
26
+ from streamlit.runtime.script_data import ScriptData
27
+ from streamlit.runtime.scriptrunner.script_cache import ScriptCache
28
+ from streamlit.runtime.scriptrunner_utils.script_run_context import (
29
+ OnScriptErrorHandler,
30
+ UserInfoType,
31
+ )
32
+ from streamlit.runtime.uploaded_file_manager import UploadedFileManager
33
+
34
+
35
+ class SessionClientDisconnectedError(Exception):
36
+ """Raised by operations on a disconnected SessionClient."""
37
+
38
+
39
+ @runtime_checkable
40
+ class ClientContext(Protocol):
41
+ """Context for the client WebSocket connection.
42
+
43
+ Provides a consistent interface for accessing headers, cookies, and client
44
+ info from the initial WebSocket handshake.
45
+ """
46
+
47
+ @property
48
+ def headers(self) -> Iterable[tuple[str, str]]:
49
+ """All headers as (name, value) tuples. Headers may be repeated."""
50
+ ...
51
+
52
+ @property
53
+ def cookies(self) -> Mapping[str, str]:
54
+ """Cookies as a name-to-value mapping."""
55
+ ...
56
+
57
+ @property
58
+ def remote_ip(self) -> str | None:
59
+ """The remote IP address of the client, or None if unavailable."""
60
+ ...
61
+
62
+
63
+ class SessionClient(Protocol):
64
+ """Interface for sending data to a session's client."""
65
+
66
+ @abstractmethod
67
+ def write_forward_msg(self, msg: ForwardMsg) -> None:
68
+ """Deliver a ForwardMsg to the client.
69
+
70
+ If the SessionClient has been disconnected, it should raise a
71
+ SessionClientDisconnectedError.
72
+ """
73
+ raise NotImplementedError # pragma: no cover - abstract
74
+
75
+ @property
76
+ def client_context(self) -> ClientContext | None:
77
+ """The client's connection context (headers, cookies, IP).
78
+
79
+ Returns None if request context information is not available.
80
+ """
81
+ return None # pragma: no cover - abstract
82
+
83
+
84
+ @dataclass
85
+ class ActiveSessionInfo:
86
+ """Type containing data related to an active session.
87
+
88
+ This type is nearly identical to SessionInfo. The difference is that when using it,
89
+ we are guaranteed that SessionClient is not None.
90
+ """
91
+
92
+ client: SessionClient
93
+ session: AppSession
94
+ # The number of times the script has been run for this session.
95
+ # At the moment, this is only used for testing and debugging purposes.
96
+ script_run_count: int = 0
97
+
98
+
99
+ @dataclass
100
+ class SessionInfo:
101
+ """Type containing data related to an AppSession."""
102
+
103
+ client: SessionClient | None
104
+ session: AppSession
105
+ # The number of times the script has been run for this session.
106
+ # At the moment, this is only used for testing and debugging purposes.
107
+ script_run_count: int = 0
108
+
109
+ def is_active(self) -> bool:
110
+ return self.client is not None
111
+
112
+ def to_active(self) -> ActiveSessionInfo:
113
+ if not self.is_active():
114
+ raise RuntimeError("A SessionInfo with no client cannot be active!")
115
+
116
+ # NOTE: The cast here (rather than copying this SessionInfo's fields into a new
117
+ # ActiveSessionInfo) is important as the Runtime expects to be able to mutate
118
+ # what's returned from get_active_session_info to increment script_run_count.
119
+ return cast("ActiveSessionInfo", self)
120
+
121
+
122
+ class SessionStorageError(Exception):
123
+ """Exception class for errors raised by SessionStorage.
124
+
125
+ The original error that causes a SessionStorageError to be (re)raised will generally
126
+ be an I/O error specific to the concrete SessionStorage implementation.
127
+ """
128
+
129
+
130
+ class SessionStorage(Protocol):
131
+ @abstractmethod
132
+ def get(self, session_id: str) -> SessionInfo | None:
133
+ """Return the SessionInfo corresponding to session_id, or None if one does not
134
+ exist.
135
+
136
+ Parameters
137
+ ----------
138
+ session_id
139
+ The unique ID of the session being fetched.
140
+
141
+ Returns
142
+ -------
143
+ SessionInfo or None
144
+
145
+ Raises
146
+ ------
147
+ SessionStorageError
148
+ Raised if an error occurs while attempting to fetch the session. This will
149
+ generally happen if there is an error with the underlying storage backend
150
+ (e.g. if we lose our connection to it).
151
+ """
152
+ raise NotImplementedError # pragma: no cover - abstract
153
+
154
+ @abstractmethod
155
+ def save(self, session_info: SessionInfo) -> None:
156
+ """Save the given session.
157
+
158
+ Parameters
159
+ ----------
160
+ session_info
161
+ The SessionInfo being saved.
162
+
163
+ Raises
164
+ ------
165
+ SessionStorageError
166
+ Raised if an error occurs while saving the given session.
167
+ """
168
+ raise NotImplementedError # pragma: no cover - abstract
169
+
170
+ @abstractmethod
171
+ def delete(self, session_id: str) -> None:
172
+ """Mark the session corresponding to session_id for deletion and stop tracking
173
+ it.
174
+
175
+ Note that:
176
+ - Calling delete on an ID corresponding to a nonexistent session is a no-op.
177
+ - Calling delete on an ID should cause the given session to no longer be
178
+ tracked by this SessionStorage, but exactly when and how the session's data
179
+ is eventually cleaned up is a detail left up to the implementation.
180
+
181
+ Parameters
182
+ ----------
183
+ session_id
184
+ The unique ID of the session to delete.
185
+
186
+ Raises
187
+ ------
188
+ SessionStorageError
189
+ Raised if an error occurs while attempting to delete the session.
190
+ """
191
+ raise NotImplementedError # pragma: no cover - abstract
192
+
193
+ @abstractmethod
194
+ def list(self) -> list[SessionInfo]: # ty: ignore[invalid-type-form]
195
+ """List all sessions tracked by this SessionStorage.
196
+
197
+ Returns
198
+ -------
199
+ List[SessionInfo]
200
+
201
+ Raises
202
+ ------
203
+ SessionStorageError
204
+ Raised if an error occurs while attempting to list sessions.
205
+ """
206
+ raise NotImplementedError # pragma: no cover - abstract
207
+
208
+
209
+ class SessionManager(Protocol):
210
+ """SessionManagers are responsible for encapsulating all session lifecycle behavior
211
+ that the Streamlit Runtime may care about.
212
+
213
+ A SessionManager must define the following required methods:
214
+ - __init__
215
+ - connect_session
216
+ - close_session
217
+ - get_session_info
218
+ - list_sessions
219
+
220
+ SessionManager implementations may also choose to define the notions of active and
221
+ inactive sessions. The precise definitions of active/inactive are left to the
222
+ concrete implementation. SessionManagers that wish to differentiate between active
223
+ and inactive sessions should have the required methods listed above operate on *all*
224
+ sessions. Additionally, they should define the following methods for working with
225
+ active sessions:
226
+ - disconnect_session
227
+ - get_active_session_info
228
+ - is_active_session
229
+ - list_active_sessions
230
+
231
+ When active session-related methods are left undefined, their default
232
+ implementations are the naturally corresponding required methods.
233
+
234
+ The Runtime, unless there's a good reason to do otherwise, should generally work
235
+ with the active-session versions of a SessionManager's methods. There isn't currently
236
+ a need for us to be able to operate on inactive sessions stored in SessionStorage
237
+ outside of the SessionManager itself. However, it's highly likely that we'll
238
+ eventually have to do so, which is why the abstractions allow for this now.
239
+
240
+ Notes
241
+ -----
242
+ Threading: All SessionManager methods are *not* threadsafe -- they must be called
243
+ from the runtime's eventloop thread.
244
+ """
245
+
246
+ @abstractmethod
247
+ def __init__(
248
+ self,
249
+ session_storage: SessionStorage,
250
+ uploaded_file_manager: UploadedFileManager,
251
+ script_cache: ScriptCache,
252
+ message_enqueued_callback: Callable[[], None] | None,
253
+ on_script_error: OnScriptErrorHandler | None = None,
254
+ ) -> None:
255
+ """Initialize a SessionManager with the given SessionStorage.
256
+
257
+ Parameters
258
+ ----------
259
+ session_storage
260
+ The SessionStorage instance backing this SessionManager.
261
+
262
+ uploaded_file_manager
263
+ Used to manage files uploaded by users via the Streamlit web client.
264
+
265
+ script_cache
266
+ ScriptCache instance. Caches user script bytecode.
267
+
268
+ message_enqueued_callback
269
+ A callback invoked after a message is enqueued to be sent to a web client.
270
+
271
+ on_script_error
272
+ Callback to invoke when an uncaught exception occurs in user script code.
273
+ Returns True to suppress the default exception display, or False/None
274
+ to show the exception normally.
275
+ """
276
+ raise NotImplementedError # pragma: no cover - abstract
277
+
278
+ @abstractmethod
279
+ def connect_session(
280
+ self,
281
+ client: SessionClient,
282
+ script_data: ScriptData,
283
+ user_info: UserInfoType,
284
+ existing_session_id: str | None = None,
285
+ session_id_override: str | None = None,
286
+ ) -> str:
287
+ """Create a new session or connect to an existing one.
288
+
289
+ Parameters
290
+ ----------
291
+ client
292
+ A concrete SessionClient implementation for communicating with
293
+ the session's client.
294
+ script_data
295
+ Contains parameters related to running a script.
296
+ user_info
297
+ A dict that contains information about the session's user. For now,
298
+ it only (optionally) contains the user's email address.
299
+
300
+ {
301
+ "email": "example@example.com"
302
+ }
303
+ existing_session_id
304
+ The ID of an existing session to reconnect to. If one is not provided, a new
305
+ session is created. Note that whether a SessionManager supports reconnecting
306
+ to an existing session is left up to the concrete SessionManager
307
+ implementation. Those that do not support reconnection should simply ignore
308
+ this argument.
309
+ session_id_override
310
+ The ID to assign to a new session being created with this method. Setting
311
+ this can be useful when the service that a Streamlit Runtime is running in
312
+ wants to tie the lifecycle of a Streamlit session to some other session-like
313
+ object that it manages. Only one of existing_session_id and
314
+ session_id_override should be set.
315
+
316
+ Returns
317
+ -------
318
+ str
319
+ The session's unique string ID.
320
+ """
321
+ raise NotImplementedError # pragma: no cover - abstract
322
+
323
+ @abstractmethod
324
+ def close_session(self, session_id: str) -> None:
325
+ """Close and completely delete the session with the given id.
326
+
327
+ This function may be called multiple times for the same session,
328
+ which is not an error. (Subsequent calls just no-op.)
329
+
330
+ Parameters
331
+ ----------
332
+ session_id
333
+ The session's unique ID.
334
+ """
335
+ raise NotImplementedError # pragma: no cover - abstract
336
+
337
+ @abstractmethod
338
+ def get_session_info(self, session_id: str) -> SessionInfo | None:
339
+ """Return the SessionInfo for the given id, or None if no such session
340
+ exists.
341
+
342
+ Parameters
343
+ ----------
344
+ session_id
345
+ The session's unique ID.
346
+
347
+ Returns
348
+ -------
349
+ SessionInfo or None
350
+ """
351
+ raise NotImplementedError # pragma: no cover - abstract
352
+
353
+ @abstractmethod
354
+ def list_sessions(self) -> list[SessionInfo]:
355
+ """Return the SessionInfo for all sessions managed by this SessionManager.
356
+
357
+ Returns
358
+ -------
359
+ List[SessionInfo]
360
+ """
361
+ raise NotImplementedError # pragma: no cover - abstract
362
+
363
+ def num_sessions(self) -> int:
364
+ """Return the number of sessions tracked by this SessionManager.
365
+
366
+ Subclasses of SessionManager shouldn't provide their own implementation of this
367
+ method without a *very* good reason.
368
+
369
+ Returns
370
+ -------
371
+ int
372
+ """
373
+ return len(self.list_sessions())
374
+
375
+ # NOTE: The following methods only need to be overwritten when a concrete
376
+ # SessionManager implementation has a notion of active vs inactive sessions.
377
+ # If left unimplemented in a subclass, the default implementations of these methods
378
+ # call corresponding SessionManager methods in a natural way.
379
+
380
+ def disconnect_session(self, session_id: str) -> None:
381
+ """Disconnect the given session.
382
+
383
+ This method should be idempotent.
384
+
385
+ Parameters
386
+ ----------
387
+ session_id
388
+ The session's unique ID.
389
+ """
390
+ self.close_session(session_id)
391
+
392
+ def get_active_session_info(self, session_id: str) -> ActiveSessionInfo | None:
393
+ """Return the ActiveSessionInfo for the given id, or None if either no such
394
+ session exists or the session is not active.
395
+
396
+ Parameters
397
+ ----------
398
+ session_id
399
+ The active session's unique ID.
400
+
401
+ Returns
402
+ -------
403
+ ActiveSessionInfo or None
404
+ """
405
+ session = self.get_session_info(session_id)
406
+ if session is None or not session.is_active():
407
+ return None
408
+ return session.to_active()
409
+
410
+ def is_active_session(self, session_id: str) -> bool:
411
+ """Return True if the given session exists and is active, False otherwise.
412
+
413
+ Returns
414
+ -------
415
+ bool
416
+ """
417
+ return self.get_active_session_info(session_id) is not None
418
+
419
+ def list_active_sessions(self) -> list[ActiveSessionInfo]:
420
+ """Return the session info for all active sessions tracked by this SessionManager.
421
+
422
+ Returns
423
+ -------
424
+ List[ActiveSessionInfo]
425
+ """
426
+ return [s.to_active() for s in self.list_sessions()]
427
+
428
+ def num_active_sessions(self) -> int:
429
+ """Return the number of active sessions tracked by this SessionManager.
430
+
431
+ Subclasses of SessionManager shouldn't provide their own implementation of this
432
+ method without a *very* good reason.
433
+
434
+ Returns
435
+ -------
436
+ int
437
+ """
438
+ return len(self.list_active_sessions())
venv/Lib/site-packages/streamlit/runtime/state/__init__.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from streamlit.runtime.state.common import (
16
+ BindOption,
17
+ PersistStateOption,
18
+ WidgetArgs,
19
+ WidgetCallback,
20
+ WidgetKwargs,
21
+ )
22
+ from streamlit.runtime.state.query_params_proxy import QueryParamsProxy
23
+ from streamlit.runtime.state.safe_session_state import SafeSessionState
24
+ from streamlit.runtime.state.session_state import (
25
+ SCRIPT_RUN_WITHOUT_ERRORS_KEY,
26
+ SessionState,
27
+ SessionStateStatProvider,
28
+ )
29
+ from streamlit.runtime.state.session_state_proxy import (
30
+ SessionStateProxy,
31
+ get_session_state,
32
+ )
33
+ from streamlit.runtime.state.widgets import register_widget
34
+
35
+ __all__ = [
36
+ "SCRIPT_RUN_WITHOUT_ERRORS_KEY",
37
+ "BindOption",
38
+ "PersistStateOption",
39
+ "QueryParamsProxy",
40
+ "SafeSessionState",
41
+ "SessionState",
42
+ "SessionStateProxy",
43
+ "SessionStateStatProvider",
44
+ "WidgetArgs",
45
+ "WidgetCallback",
46
+ "WidgetKwargs",
47
+ "get_session_state",
48
+ "register_widget",
49
+ ]
venv/Lib/site-packages/streamlit/runtime/state/__pycache__/__init__.cpython-314.pyc ADDED
Binary file (957 Bytes). View file
 
venv/Lib/site-packages/streamlit/runtime/state/__pycache__/common.cpython-314.pyc ADDED
Binary file (8.83 kB). View file
 
venv/Lib/site-packages/streamlit/runtime/state/__pycache__/presentation.cpython-314.pyc ADDED
Binary file (2.72 kB). View file
 
venv/Lib/site-packages/streamlit/runtime/state/__pycache__/query_params.cpython-314.pyc ADDED
Binary file (42.3 kB). View file
 
venv/Lib/site-packages/streamlit/runtime/state/__pycache__/query_params_proxy.cpython-314.pyc ADDED
Binary file (13.8 kB). View file