File size: 7,982 Bytes
4f7e359
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import streamlit as st
st.set_option('deprecation.showPyplotGlobalUse', False)
#st.markdown()
st.title("Document Title")
st.header("Article header")
st.subheader("Article subheader")
st.code("y = mx + c")
st.latex("\ int a y^2 \ , dy")
st.text("This is a chair!")
st.markdown('Staying hydrated is **_very_ cool**.')

students = ["Amelia Kami", "Antoinne Mark", "Peter Zen", "North Kim"]

marks = [82, 76, 96, 68]

import pandas as pd

df = pd.DataFrame()

df["Student Name"] = students

df["Marks"] = marks
#save to dataframe
df.to_csv("students.csv", index = False)
#display
st.dataframe(df)

#Static table
st.table(df)

#Metrics
st.metric("KPI", 56, 3)
#Json
st.json(df.to_dict())

#Code
#average of a list
code = '''def cal_average(numbers):
    sum_number = 0
    for t in numbers:
        sum_number = sum_number + t           

    average = sum_number / len(numbers)
    return average'''
st.code(code, language='python')
#progress bar

import streamlit as st
import time

# Sample Progress bar
#bar_p = st.progress(0)

#for percentage_complete in range(100):
    #time.sleep(0.1)
    #bar_p.progress(percentage_complete + 1)

#with st.spinner('Please wait...'):
    #time.sleep(5)
#st.write('Complete!')


#Displaying an image using Streamlit
from PIL import Image
image = Image.open('media/ann-savchenko-H0h_89iFsWs-unsplash.jpg')

#st.image(image, caption='Sunset grass backgrounds')

#plotly
import plotly.express as px
# This dataframe has 244 rows, but 4 unique entries for the `day` variable
df = px.data.tips()
figx = px.pie(df, values='tip', names='day', title='Tips per day')
# Plot!
st.plotly_chart(figx, use_container_width=True)

#Altair
import altair as alt
import streamlit as st
import numpy as np

df = pd.DataFrame(
     np.random.randn(300, 4),
     columns=['a', 'b', 'c', 'd'])

chrt = alt.Chart(df).mark_circle().encode(
     x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c', 'd'])

st.altair_chart(chrt, use_container_width=True)

#Matplotlib
import matplotlib.pyplot as plt
import numpy as np

arr = np.random.normal(1, 1, size=1000)
fig, ax = plt.subplots()
ax.hist(arr, bins=30)
plt.grid()
st.pyplot(fig)

#Interactive widgets
st.button("Click here")
#st.download_button("Download audio", file)
selected = st.checkbox("Accept terms")
choice = st.radio("Select one", ["Apples", "Oranges"])


option = st.selectbox(
     'How would you like to receive your package?',
     ('By air', 'By sea', 'By rail'))

st.write('You selected:', option)
import datetime
day = st.date_input(
     "When is your birthday?",
     datetime.date(2022, 7, 6))
st.write('Your birthday is:', day)

color = st.color_picker('Choose A Color', '#00FFAA')
st.write('The selected color is', color)


@st.cache
def fetch_data():
    df = pd.read_csv("students.csv")
    return df

#data = fetch_data()

#Visualization

import matplotlib.pyplot as plt
import numpy as np

#Matplotlib

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
animals = ["Zebras", "Elephants", "Rhinos", "Leopards"]
number = [65, 72, 77, 59]
ax.bar(animals, number)
fig = plt.show()
st.pyplot(fig)
#Seaborn
import seaborn as sns
fig = plt.figure()
ax = sns.barplot(x = animals, y = number)
fig = plt.show()
st.pyplot(fig)

#Altair
#define data
df = pd.DataFrame()

df["Animals"] = animals
df["Number"] = number
#create chart
chrt = alt.Chart(df, title="Ploting using Altair in Streamlit").mark_bar().encode(
    x='Animals',
    y='Number'
)
#render with Streamlit
st.altair_chart(chrt, use_container_width=True)
#Plotly
#define data
df = pd.DataFrame()
df["Animals"] = animals
df["Number"] = number
#create plot
fig1 = px.bar(df, x='Animals', y='Number', title="Ploting using Plotly in Streamlit")
# Plot!
st.plotly_chart(fig1, use_container_width=True)

#data
df = pd.DataFrame()
df["Animals"] = animals
df["Number"] = number
#visualization
st.vega_lite_chart(df, {
     'mark': {'type': 'bar', 'tooltip': True},
     'encoding': {
         'x': {'field': 'Animals', 'type': 'nominal'},
         'y': {'field': 'Number', 'type': 'quantitative'},
     },
 }, use_container_width=True)

#Maps
import pandas as pd
states = pd.read_html('https://developers.google.com/public-data/docs/canonical/states_csv')[0]
states.columns = ['state', 'lat', 'lon', 'name']
states = states.drop(['state', 'name'], axis = 1)

st.map(states)

#Components
from st_aggrid import AgGrid
AgGrid(df)

#Statefulnness
import streamlit as st

st.title('Streamlit Counter Example')
count = 0

add = st.button('Addition')
if add:
    count += 1

st.write('Count = ', count)


import streamlit as st

st.title('Counter Session State')
if 'count' not in st.session_state:
    st.session_state.count = 0

increment = st.button('Add')
if increment:
    st.session_state.count += 1

st.write('Count = ', st.session_state.count)

#Layout
col1, col2 = st.columns(2)

with col1:
    st.altair_chart(chrt)
with col2:
    st.plotly_chart(fig1, use_container_width=True)
with st.beta_container():
    st.plotly_chart(figx, use_container_width=True)



#Add side widget

def your_widget(key):
    st.subheader('Hi! Welcome')
    return st.button(key + "Step")

# Displayed in the main area
clicked = your_widget("First")

# Shown within an expander
your_expander = st.expander("Expand", expanded=True)
with your_expander:
    clicked = your_widget("Second")

# Shown in the st.sidebar!
with st.sidebar:
    clicked = your_widget("Last")
#Session State
# Initialization
if 'key' not in st.session_state:
    st.session_state['key'] = 'value'
   
    

# Session State also supports attribute based syntax
if 'key' not in st.session_state:
    st.session_state.key = 'value'
    
st.session_state.key = 'value x'     # New Attribute API
st.session_state['key'] = 'value x'  # New Dictionary like API

st.write(st.session_state)

#Uploading files

import streamlit as st

#upload single file
file = st.file_uploader("Please select a file to upload")
if file is not None:
    #Can be used wherever a "file-like" object is accepted:
    df= pd.read_csv(file)
    st.dataframe(df)

#Multiple files
#adding a file uploader to accept multiple CSV file
uploaded_files = st.file_uploader("Please select a CSV file", accept_multiple_files=True)
for file in uploaded_files:
    df = pd.read_csv(file)
    st.write("File uploaded:", file.name)
    st.dataframe(df)
#Uploading and Processing
#upload single file
from PIL import Image
from PIL import ImageEnhance
def load_image(image):
    img = Image.open(image)
    return img

file = st.file_uploader("Please select image to upload and process")
if file is not None:
    image = Image.open(file) 
    fig = plt.figure()
    st.subheader("Original Image")
    plt.imshow(image)
    st.pyplot(fig)
    fig = plt.figure()
    contrast = ImageEnhance.Contrast(image).enhance(12)
    plt.imshow(contrast)
    st.subheader("Preprocessed Image")
    st.pyplot(fig)

    
#Image classification
import keras
from PIL import Image, ImageOps
import numpy as np



import streamlit as st
import streamlit as st
from transformers import pipeline

'''Hugging Face'''

import streamlit as st
from transformers import pipeline

if __name__ == "__main__":

    # Define the title of the and its description
    st.title("Answering questions using NLP through Streamlit interface")
    st.write("Pose questions, get answers")

    # Load file
    
    raw_text = st.text_area(label="Enter a text here")
    if raw_text != None and raw_text != '':

        # Display text
        with st.expander("Show question"):
            st.write(raw_text)

        # Conduct question answering using the pipeline
        question_answerer = pipeline('question-answering')

        answer = ''
        question = st.text_input('Ask a question')

        if question != '' and raw_text != '':
            answer = question_answerer({
                'question': question,
                'context': raw_text
            })

        st.write(answer)