# Streamlit

Streamlit • A faster way to build and share data apps

Streamlit turns data scripts into shareable web apps in minutes.
All in pure Python. No front‑end experience required.

# Timezone Converter

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
from datetime import datetime
import pytz
import tzlocal
import streamlit as st


def convert_timezone(input_datetime, from_timezone, to_timezone):
if input_datetime and from_timezone and to_timezone:
from_timezone = pytz.timezone(from_timezone)
to_timezone = pytz.timezone(to_timezone)

output_datetime = from_timezone.localize(input_datetime).astimezone(to_timezone)

return output_datetime


st.title("Timezone Converter")
st.write("*Convert time from one timezone to another.*")

col1, col2 = st.columns(2)

with col1:
local_timezone = tzlocal.get_localzone_name()
from_timezone = st.selectbox('From Timezone', pytz.all_timezones, pytz.all_timezones.index(local_timezone))

with col2:
to_timezone = st.selectbox('To Timezone', pytz.all_timezones)

with col1:
input_date = st.date_input("Input Date")

with col2:
input_time = st.time_input("Input Time")

input_datetime = datetime.combine(input_date, input_time)
output_datetime = convert_timezone(input_datetime, from_timezone, to_timezone)

st.write(f"The time in {from_timezone} is {input_datetime.strftime('%Y-%m-%d %H:%M:%S %Z')} and the time in {to_timezone} is **{output_datetime.strftime('%Y-%m-%d %H:%M:%S %Z')}**.")

# URL Shorten

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
import streamlit as st
import pyshorteners

external_style = open("./shorten_url_style.css").read()
st.markdown(f"<style>{external_style}</style>", unsafe_allow_html=True)

st.markdown("""
<style>
.title {
background: linear-gradient(to bottom, orangered, orange);
color: white;
border-radius: 10px;
margin-bottom: 20px;
}
</style>
""", unsafe_allow_html=True)

st.markdown("<h1 style='text-align:center' class='title'>URL SHORTENER</h1>", unsafe_allow_html=True)

with st.form("Shorten Form"):
original_url = st.text_input('Enter the URL to shorten')
shortened = st.form_submit_button("Shorten")

def shorten_url(url):
s = pyshorteners.Shortener()
return s.tinyurl.short(url)

if shortened and original_url:
shortened_url = shorten_url(original_url)
st.success('Shortened URL: {}'.format(shortened_url))
shorten_url_style.css
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* Hidden Menu */
div[data-testid="stToolbar"] {
visibility: hidden;
}

/* Hidden Footer */
footer {
visibility: hidden;
}


div[data-testid="stForm"] {
background: rgba(255, 165, 0, 0.8);
}

# Image Editor

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
import streamlit as st
from PIL import Image, ImageFilter

st.markdown("<h1 style='text-align:center'>Image Editor</h1>", unsafe_allow_html=True)

uploaded_image = st.file_uploader("Choose an image", type=["jpg", "png"])

if uploaded_image:
image = Image.open(uploaded_image)

original_tab, edited_tab = st.tabs(["Original Image", "Edited Image"])

with original_tab:
st.image(image, caption='Original Image')

st.sidebar.markdown("<h2 style='text-align:center'>Resize</h2>", unsafe_allow_html=True)
col1, col2 = st.sidebar.columns(2)
with col1:
width = st.sidebar.number_input("Width", value=image.width)
with col2:
height = st.sidebar.number_input("Height", value=image.height)

st.sidebar.markdown("<h2 style='text-align:center'>Rotate</h2>", unsafe_allow_html=True)
rotation_angle = st.sidebar.slider('Rotate', -180, 180, 0)

st.sidebar.markdown("<h2 style='text-align:center'>Filter</h2>", unsafe_allow_html=True)
filter_type = st.sidebar.selectbox('Filter', ('', 'BLUR', 'CONTOUR', 'DETAIL', 'SHARPEN'), index=0)

image = image.resize((int(width), int(height))).rotate(rotation_angle)

if filter_type != '':
image = image.filter(getattr(ImageFilter, filter_type))

with edited_tab:
st.image(image, caption='Edited Image')

# Web Scraper

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
import streamlit as st
import requests
import webbrowser
from bs4 import BeautifulSoup

st.set_page_config(
page_title="Web Scraper",
page_icon="🧊",
layout="wide"
# initial_sidebar_state="expanded",
# menu_items={
# 'Get Help': 'https://www.extremelycoolapp.com/help',
# 'Report a bug': "https://www.extremelycoolapp.com/bug",
# 'About': "# This is a header. This is an *extremely* cool app!"
# }
)
st.markdown("<h1 style='text-align:center'>Web Scraper</h1>", unsafe_allow_html=True)

with st.form("Search"):
keyword = st.text_input("Enter keyword")
search = st.form_submit_button("Search")

# !IMPORTANT
placeholder = st.empty()

if keyword:
page = requests.get(f"https://unsplash.com/s/photos/{keyword}")
soup = BeautifulSoup(page.content, "lxml")
rows = soup.find_all("div", class_= "ripi6")

col1, col2 = placeholder.columns(2)

for index, row in enumerate(rows):
figures = row.find_all("figure")
for i in range(len(figures)):
img = figures[i].find("img", class_="tB6UZ")["srcset"].split("?")[0]
anchor_href = figures[i].find("a", class_="rEAWd")["href"]

if i % 2 == 0:
col1.image(img)
# !IMPORTANT key=str(index) + str(i)
# When a widget is created, it's assigned an internal key based on its structure.
# Multiple widgets with an identical structure will result in the same internal key, which causes this error.
btn = col1.button("Download", key=str(index) + str(i))
if btn:
webbrowser.open_new_tab(f"https://unsplash.com{anchor_href}")
else:
col2.image(img)
btn = col2.button("Download", key=str(index) + str(i))
if btn:
webbrowser.open_new_tab(f"https://unsplash.com{anchor_href}")

# Upload File Data to Oracle

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
import os
import time
import pandas as pd
import streamlit as st
from sqlalchemy import create_engine
from sqlalchemy.dialects.oracle import VARCHAR2, NUMBER

st.markdown("<h4 style='text-align:center'>Upload CSV/XML/Excel to Oracle</h4>", unsafe_allow_html=True)

with st.sidebar:
env = st.selectbox(label='Select Oracle Enviroment', options=('DEV', 'TEST', 'PROD'))

tablename = st.text_input(label='Table Name', value='edi_test')

col1, col2 = st.columns(2)
with col1:
csv_separator = st.selectbox(label='CSV Separator', options=(',', '|', ':'))
with col2:
xpath = st.text_input(label='XPath', value='.//record')

uploaded_files = st.file_uploader('', accept_multiple_files=True, type=["csv", "xml", "xls", "xlsx"])

if uploaded_files:
uploaded = st.button('Upload Data to Oracle')
# button default style
# <div class='row-widget stButton'>
# <button kind='primary' class='css-1cpxqw2 edgvbvh1'>Upload</button>
# </div>
st.markdown('''
<style>
div.stButton button:first-child {
background-color: rgb(204, 49, 49);
width: 100%;
color: #fff;
padding: 8px;
}
</style>''', unsafe_allow_html=True)

placeholder = st.empty()

if uploaded:
try:
if env in ('DEV', 'TEST'):
conn_string = f'oracle+cx_oracle://username:password@{env}'
elif env in ('PROD'):
conn_string = f'oracle+cx_oracle://username:password@{env}'
engine = create_engine(conn_string, echo=False)

for uploaded_file in uploaded_files:
filename = uploaded_file.name
basename, extension = os.path.splitext(filename)

if not tablename:
tablename = basename.lower()

placeholder.write(f'💜 Upload `{filename}`')
start_time = time.time()

if extension in ('.xls', '.xlsx'):
df = pd.read_excel(uploaded_file, keep_default_na=False, engine='openpyxl')
elif extension in ('.csv', '.txt'):
df = pd.read_csv(uploaded_file, keep_default_na=False, sep=csv_separator)
elif extension in ('.xml'):
df = pd.read_xml(uploaded_file, xpath=xpath)

if not df.empty:
st.write(df.head())

with st.spinner("Please wait..."):
# Oracle Database prior to version 12.2 limit identifier names, such as table names, column names, and primary key names, to 30 characters.
df.columns = df.columns.map(lambda name: name[:30])
dtype = {c: VARCHAR2(df[c].str.len().max()) for c in df.columns[df.dtypes == 'object'].tolist()}
dtype.update({c: NUMBER for c in df.columns[df.dtypes == 'float64'].tolist()})
df.to_sql(tablename, con=engine, index=False, if_exists='append', dtype=dtype, chunksize=10**4)

placeholder.write(f'❤️ Upload `{filename}` cost time: `{time.time() - start_time}`')
st.balloons()
except Exception as e:
placeholder.error(f'💔 {e}')
raise e

# Gradio

Gradio Build & Share Delightful Machine Learning Apps

Gradio is the fastest way to demo your machine learning model with a friendly web interface so that anyone can use it, anywhere!

# Timezone Converter use Interface

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
import pytz
import tzlocal
import gradio as gr


all_timezones = pytz.all_timezones
local_timezone = tzlocal.get_localzone_name()

def convert_timezone(time_str, from_tz, to_tz):
if time_str and from_tz and to_tz:
input_time = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")

from_timezone = pytz.timezone(from_tz)
to_timezone = pytz.timezone(to_tz)

converted_time = from_timezone.localize(input_time).astimezone(to_timezone)

return converted_time.strftime("%Y-%m-%d %H:%M:%S")

iface = gr.Interface(fn=convert_timezone,
inputs=[gr.Textbox(label="Input Time (YYYY-MM-DD HH:MM:SS)"),
gr.Dropdown(choices=all_timezones, label="From Timezone"),
gr.Dropdown(choices=all_timezones, label="To Timezone", value=local_timezone)],
outputs=gr.Textbox(label="Output Time"),
examples=[["2024-03-21 14:00:00", "EST", "Asia/Shanghai"],
["2024-03-21 14:00:00", "Asia/Shanghai", "EST"]],
title="Timezone Converter",
description="Convert time from one timezone to another",
allow_flagging="never",
live=True,
theme=gr.themes.Glass()
)

iface.launch()

# Timezone Converter use Blocks

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
from datetime import datetime
import pytz
import tzlocal
import gradio as gr


all_timezones = pytz.all_timezones
local_timezone = tzlocal.get_localzone_name()
now = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")

def convert_timezone(time_str, from_tz, to_tz):
input_time = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")

from_timezone = pytz.timezone(from_tz)
to_timezone = pytz.timezone(to_tz)

converted_time = from_timezone.localize(input_time).astimezone(to_timezone)

return converted_time.strftime("%Y-%m-%d %H:%M:%S")


# with gr.Blocks(theme=gr.themes.Glass()) as interface:
with gr.Blocks() as interface:
gr.Markdown("""
## Timezone Converter
*Convert time from one timezone to another.*
""")

with gr.Row():
input_time = gr.Textbox(label="Input Time (YYYY-MM-DD HH:MM:SS)", value=now)
output_time = gr.Textbox(label="Output Time")

with gr.Row():
from_timezone = gr.Dropdown(choices=all_timezones, label="From Timezone")
to_timezone = gr.Dropdown(choices=all_timezones, label="To Timezone", value=local_timezone)

# convert_btn = gr.Button("Convert", variant="primary")
# convert_btn.click(fn=convert_timezone, inputs = [input_time, from_timezone, to_timezone], outputs=[output_time])
[item.change(fn=convert_timezone, inputs=[input_time, from_timezone, to_timezone], outputs=[output_time]) for item in [input_time, from_timezone, to_timezone]]

gr.Examples([["2024-03-21 14:00:00", "EST", "Asia/Shanghai"],
["2024-03-21 14:00:00", "Asia/Shanghai", "EST"]], [input_time, from_timezone, to_timezone])

interface.launch()

# Common Layout

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
import gradio as gr

with gr.Blocks(css="style.css") as inferface:
with gr.Tab(label="txt.img"):
with gr.Row():
with gr.Column(scale=15):
txt1 = gr.Textbox(lines=2, label="")
txt2 = gr.Textbox(lines=2, label="")

with gr.Column(scale=1, min_width=1):
button1 = gr.Button(value="1")
button2 = gr.Button(value="2")
button3 = gr.Button(value="3")
button4 = gr.Button(value="4")

with gr.Column(scale=6):
generate_button = gr.Button(value="Generator", variant="primary", scale=1)
with gr.Row():
dropdown1 = gr.Dropdown(["1", "2", "3", "4"], label="Style1", min_width=1)
dropdown2 = gr.Dropdown(["1", "2", "3", "4"], label="Style2", min_width=1)

with gr.Row():
with gr.Column():
with gr.Row():
dropdown3 = gr.Dropdown(["1", "2", "3", "4"], label="Sampling method")
slider1 = gr.Slider(minimum=0, maximum=100, label="Sampling step")
checkboxgroup = gr.CheckboxGroup(["1", "2", "3", "4"], label="")
with gr.Row():
slider2 = gr.Slider(minimum=0, maximum=100, label="Width")
slider3 = gr.Slider(minimum=0, maximum=100, label="Batch count")
with gr.Row():
slider4 = gr.Slider(minimum=0, maximum=100, label="Height")
slider5 = gr.Slider(minimum=0, maximum=100, label="Batch size")
slider6 = gr.Slider(minimum=0, maximum=100, label="CFG scale")
with gr.Row(elem_classes="row-group"):
number1 = gr.Number(label="Seed", scale=5)
button5 = gr.Button(value="Randomize", min_width=1, elem_classes="btn")
button6 = gr.Button(value="Reset", min_width=1, elem_classes="btn")
checkbox1 = gr.Checkbox(label="Extra", scale=1)
dropdown4 = gr.Dropdown(["1", "2", "3", "4"], label="Script")
with gr.Column():
with gr.Accordion():
gallery = gr.Gallery([
"https://picsum.photos/300?id=1",
"https://picsum.photos/300?id=2",
"https://picsum.photos/300?id=3",
"https://picsum.photos/300?id=4",
"https://picsum.photos/300?id=5"
], columns=3)
with gr.Row():
button7 = gr.Button(value="Save", min_width=1)
button8 = gr.Button(value="Zip", min_width=1)
button9 = gr.Button(value="Save", min_width=1)
button10 = gr.Button(value="Zip", min_width=1)
with gr.Group():
button11 = gr.Button(value="Save to image", min_width=1)
button12 = gr.Button(value="Save to extras", min_width=1)
txt3 = gr.Text(lines=4, label="")

with gr.Tab(label="img.img"):
pass

inferface.launch()

style.css

1
2
3
4
5
6
7
8
9
10
11
12
gradio-app {
background: linear-gradient(to bottom right, skyblue, dodgerblue) !important;
}

.row-group {
align-items: center;
}

.btn {
background: linear-gradient(to bottom right, dodgerblue, skyblue);
border: none;
}

# Gradio in Notebook

Gradio can used in Python Notebook dirctlty.

Edited on