streamlit

Форк
0
181 строка · 3.6 Кб
1
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2024)
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
import io
16
from collections import namedtuple
17
from dataclasses import dataclass
18
from datetime import datetime
19

20
import altair as alt
21
import graphviz
22
import matplotlib.pyplot as plt
23
import numpy as np
24
import pandas as pd
25
import plotly.express as px
26
import pydeck as pdk
27
from PIL import Image
28

29
import streamlit as st
30

31
np.random.seed(0)
32

33
st.subheader("st.write(markdown)")
34

35
st.write("Hello", "World")
36

37
st.write("This **markdown** is awesome! :sunglasses:")
38

39
st.write("This <b>HTML tag</b> is escaped!")
40

41
st.write("This <b>HTML tag</b> is not escaped!", unsafe_allow_html=True)
42

43

44
class ClassWithReprHtml:
45
    def _repr_html_(self):
46
        return "This <b>HTML tag</b> is also not escaped!"
47

48

49
st.write(ClassWithReprHtml())
50
st.write(ClassWithReprHtml(), unsafe_allow_html=True)
51

52
st.write(100)
53

54
st.write(None)
55

56
st.write(datetime(2021, 1, 1))
57

58
st.write(np.float64(1.0))
59

60

61
class SomeObject1(object):
62
    def __str__(self):
63
        return "1 * 2 - 3 = 4 `ok` !"
64

65

66
st.write(SomeObject1())  # escaped single line string
67

68

69
class SomeObject2(object):
70
    def __str__(self):
71
        return "1 * 2\n - 3\n ``` = \n````\n4 `ok` !"
72

73

74
st.write(SomeObject2())  # escaped multiline string
75

76
string_io = io.StringIO()
77
string_io.write("This is a string IO object!")
78

79
st.write(string_io)
80

81

82
def stream_text():
83
    yield "This is "
84
    yield "streamed text"
85

86

87
st.subheader("st.write(generator)")
88

89
st.write(stream_text)
90

91
st.write(stream_text())
92

93

94
st.subheader("st.write(dataframe-like)")
95

96
st.write(pd.DataFrame(np.random.randn(25, 3), columns=["a", "b", "c"]))
97

98
st.write(pd.Series([1, 2, 3]))
99

100
st.write(
101
    pd.DataFrame(np.random.randn(25, 3), columns=["a", "b", "c"]).style.format("{:.2%}")
102
)
103

104
st.write(np.arange(25).reshape(5, 5))
105

106
st.subheader("st.write(json-like)")
107

108
st.write(["foo", "bar"])
109

110
st.write({"foo": "bar"})
111

112
st.write(st.session_state)
113
st.write(st.experimental_user)
114
st.write(st.query_params)
115

116
Point = namedtuple("Point", ["x", "y"])
117
st.write(Point(1, 2))
118

119
st.subheader("st.write(help)")
120

121
st.write(st.dataframe)
122

123

124
@dataclass
125
class ExampleClass:
126
    name: str
127
    age: int
128

129

130
st.write(ExampleClass)
131

132
st.subheader("st.write(exception)")
133

134
st.write(Exception("This is an exception!"))
135

136
st.subheader("st.write(matplotlib)")
137

138
fig, ax = plt.subplots()
139
ax.hist(np.random.normal(1, 1, size=100), bins=20)
140

141
st.write(fig)
142

143
st.subheader("st.write(altair)")
144

145
df = pd.DataFrame(np.random.randn(50, 3), columns=["a", "b", "c"])
146
chart = alt.Chart(df).mark_circle().encode(x="a", y="b", size="c", color="c")
147
st.write(chart)
148

149
st.subheader("st.write(plotly)")
150

151
fig = px.scatter(df, x="a", y="b")
152
st.write(fig)
153

154
st.subheader("st.write(graphviz)")
155

156
graph = graphviz.Digraph()
157
graph.edge("run", "intr")
158
graph.edge("intr", "runbl")
159
graph.edge("runbl", "run")
160

161
st.write(graph)
162

163
# Simple pydeck chart:
164

165
st.subheader("st.write(pydeck)")
166

167
st.write(
168
    pdk.Deck(
169
        map_style=None,
170
        initial_view_state=pdk.ViewState(
171
            latitude=37.76,
172
            longitude=-122.4,
173
            zoom=11,
174
            pitch=50,
175
        ),
176
    )
177
)
178

179
st.subheader("st.write(Image)")
180

181
st.write(Image.new("L", (10, 10), "black"))
182

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.