|
import streamlit as st |
|
import pandas as pd |
|
import numpy as np |
|
import time |
|
import random |
|
from PIL import Image |
|
|
|
|
|
import torch |
|
import imageio.v3 as iio |
|
import matplotlib.pyplot as plt |
|
import colorsys |
|
import tempfile |
|
import cv2 |
|
import os |
|
|
|
|
|
st.set_page_config( |
|
page_title="Streamlit Super Fun Guide 🎈", |
|
page_icon="🎈", |
|
layout="wide", |
|
initial_sidebar_state="expanded", |
|
) |
|
|
|
|
|
st.title("Welcome to the Streamlit Super Fun Guide 🎉") |
|
|
|
|
|
st.write(""" |
|
|
|
Reference Papers: |
|
https://arxiv.org/abs/2307.07635 |
|
https://arxiv.org/pdf/2307.07635 |
|
|
|
There once was a coder so bright, |
|
Who coded with all of their might. |
|
With Streamlit's delight, |
|
They coded all night, |
|
And apps popped up left and right! |
|
""") |
|
|
|
|
|
st.write("> “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler") |
|
|
|
|
|
st.sidebar.title("Navigation 🧭") |
|
options = st.sidebar.radio("Go to", [ |
|
"Introduction 🚀", |
|
"Upload Media 📁", |
|
"Animated Charts 📊", |
|
"Caching Demo 🗃️", |
|
"Query Parameters 🔍", |
|
"Character Gallery 🐾", |
|
"CoTracker3 Demo 🕵️♂️" |
|
]) |
|
|
|
|
|
if options == "Introduction 🚀": |
|
st.header("Introduction 🚀") |
|
st.write("Hello there 👋") |
|
st.write("Thanks for stopping by! Let's embark on a fun journey to learn Streamlit together!") |
|
st.write("Here's a joke to start with:") |
|
st.write("> Why did the programmer quit his job? Because he didn't get arrays! 😂") |
|
st.image("https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif") |
|
|
|
|
|
elif options == "Upload Media 📁": |
|
st.header("Upload Media Files 📁") |
|
st.write("You can upload images, videos, and audio files here, and we'll display them in galleries!") |
|
uploaded_files = st.file_uploader("Choose media files", accept_multiple_files=True, type=["png", "jpg", "jpeg", "mp4", "mp3", "wav"]) |
|
|
|
if uploaded_files: |
|
images = [] |
|
videos = [] |
|
audios = [] |
|
for uploaded_file in uploaded_files: |
|
if uploaded_file.type.startswith("image/"): |
|
images.append(uploaded_file) |
|
elif uploaded_file.type.startswith("video/"): |
|
videos.append(uploaded_file) |
|
elif uploaded_file.type.startswith("audio/"): |
|
audios.append(uploaded_file) |
|
|
|
if images: |
|
st.subheader("Image Gallery 🖼️") |
|
cols = st.columns(3) |
|
for idx, img in enumerate(images): |
|
with cols[idx % 3]: |
|
st.image(img, use_column_width=True) |
|
|
|
if videos: |
|
st.subheader("Video Gallery 🎥") |
|
for vid in videos: |
|
st.video(vid) |
|
|
|
if audios: |
|
st.subheader("Audio Gallery 🎵") |
|
for aud in audios: |
|
st.audio(aud) |
|
|
|
|
|
elif options == "Animated Charts 📊": |
|
st.header("Animated Charts 📊") |
|
st.write("Watch the data come alive with live-updating charts!") |
|
|
|
|
|
progress_bar = st.progress(0) |
|
status_text = st.empty() |
|
chart = st.line_chart(np.random.randn(10, 2)) |
|
|
|
for i in range(100): |
|
new_rows = np.random.randn(1, 2) |
|
status_text.text(f"Iteration {i+1}") |
|
chart.add_rows(new_rows) |
|
progress_bar.progress((i + 1) % 100) |
|
time.sleep(0.1) |
|
st.success("Animation Complete! 🎉") |
|
|
|
|
|
elif options == "Caching Demo 🗃️": |
|
st.header("Caching Demo 🗃️") |
|
st.write("This demonstrates how caching can speed up your app.") |
|
|
|
@st.cache_data |
|
def expensive_computation(n): |
|
time.sleep(2) |
|
return np.random.randn(n) |
|
|
|
st.write("Click the button to compute some data.") |
|
if st.button("Compute Data 🔄"): |
|
with st.spinner("Computing..."): |
|
data = expensive_computation(1000) |
|
st.success("Computation Complete! 🎉") |
|
st.line_chart(data) |
|
else: |
|
st.write("Awaiting your command...") |
|
|
|
|
|
elif options == "Query Parameters 🔍": |
|
st.header("Query Parameters 🔍") |
|
st.write("You can control the app via URL query parameters!") |
|
st.write("Try adding `?name=YourName` to the URL and see what happens.") |
|
|
|
name = st.experimental_get_query_params().get("name", ["Stranger"])[0] |
|
st.write(f"Hello, {name}! 👋") |
|
st.write("Change the 'name' parameter in the URL to personalize this message.") |
|
|
|
|
|
elif options == "Character Gallery 🐾": |
|
st.header("Character Gallery 🐾") |
|
st.write("Meet our delightful characters!") |
|
|
|
characters = [ |
|
{"name": "Leo", "emoji": "🦁"}, |
|
{"name": "Mia", "emoji": "🐱"}, |
|
{"name": "Max", "emoji": "🐶"}, |
|
{"name": "Zoe", "emoji": "🦊"}, |
|
{"name": "Sam", "emoji": "🐵"}, |
|
{"name": "Lily", "emoji": "🐰"}, |
|
{"name": "Oscar", "emoji": "🐼"}, |
|
{"name": "Ella", "emoji": "🐨"}, |
|
{"name": "Jack", "emoji": "🐸"}, |
|
{"name": "Nina", "emoji": "🐙"}, |
|
{"name": "Charlie", "emoji": "🐵"}, |
|
{"name": "Daisy", "emoji": "🐷"}, |
|
{"name": "Felix", "emoji": "🐧"}, |
|
{"name": "Grace", "emoji": "🐮"}, |
|
{"name": "Henry", "emoji": "🐴"}, |
|
] |
|
|
|
random.shuffle(characters) |
|
cols = st.columns(5) |
|
for idx, character in enumerate(characters): |
|
with cols[idx % 5]: |
|
st.write(f"{character['emoji']} **{character['name']}**") |
|
|
|
|
|
elif options == "CoTracker3 Demo 🕵️♂️": |
|
st.header("CoTracker3 Demo 🕵️♂️") |
|
st.write("This demo showcases point tracking using [CoTracker3](https://cotracker3.github.io/).") |
|
st.write("Upload a video or select one of the example videos, then click **Track Points** to see CoTracker3 in action!") |
|
|
|
|
|
example_videos = { |
|
"Apple": "https://github.com/facebookresearch/co-tracker/raw/refs/heads/main/assets/apple.mp4", |
|
"Bear": "https://github.com/facebookresearch/co-tracker/raw/refs/heads/main/assets/bear.mp4", |
|
"Paragliding Launch": "https://github.com/facebookresearch/co-tracker/raw/refs/heads/main/assets/paragliding-launch.mp4", |
|
"Paragliding": "https://github.com/facebookresearch/co-tracker/raw/refs/heads/main/assets/paragliding.mp4", |
|
"Cat": "https://github.com/facebookresearch/co-tracker/raw/refs/heads/main/assets/cat.mp4", |
|
"Pillow": "https://github.com/facebookresearch/co-tracker/raw/refs/heads/main/assets/pillow.mp4", |
|
"Teddy": "https://github.com/facebookresearch/co-tracker/raw/refs/heads/main/assets/teddy.mp4", |
|
"Backpack": "https://github.com/facebookresearch/co-tracker/raw/refs/heads/main/assets/backpack.mp4", |
|
} |
|
|
|
|
|
uploaded_video = st.file_uploader("Upload a video (mp4 format)", type=["mp4"]) |
|
|
|
|
|
selected_example = st.selectbox("Or select an example video", ["None"] + list(example_videos.keys())) |
|
|
|
|
|
if st.button("Track Points"): |
|
with st.spinner("Processing..."): |
|
|
|
if uploaded_video is not None: |
|
|
|
video_bytes = uploaded_video.read() |
|
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_file: |
|
tmp_file.write(video_bytes) |
|
tmp_video_path = tmp_file.name |
|
frames = iio.imread(tmp_video_path, plugin="pyav") |
|
elif selected_example != "None": |
|
|
|
video_url = example_videos[selected_example] |
|
frames = iio.imread(video_url, plugin="pyav") |
|
else: |
|
st.warning("Please upload a video or select an example video.") |
|
st.stop() |
|
|
|
|
|
FRAME_LIMIT = 300 |
|
if frames.shape[0] > FRAME_LIMIT: |
|
frames = frames[:FRAME_LIMIT] |
|
st.warning(f"Video is too long. Only the first {FRAME_LIMIT} frames will be processed.") |
|
|
|
|
|
device = 'cuda' if torch.cuda.is_available() else 'cpu' |
|
grid_size = 10 |
|
video = torch.tensor(frames).permute(0, 3, 1, 2)[None].float().to(device) |
|
|
|
|
|
cotracker = torch.hub.load("facebookresearch/co-tracker", "cotracker3_offline").to(device) |
|
pred_tracks, pred_visibility = cotracker(video, grid_size=grid_size) |
|
|
|
|
|
def get_colors(num_colors): |
|
colors = [] |
|
for i in np.arange(0.0, 360.0, 360.0 / num_colors): |
|
hue = i / 360.0 |
|
lightness = (50 + np.random.rand() * 10) / 100.0 |
|
saturation = (90 + np.random.rand() * 10) / 100.0 |
|
color = colorsys.hls_to_rgb(hue, lightness, saturation) |
|
colors.append( |
|
(int(color[0] * 255), int(color[1] * 255), int(color[2] * 255)) |
|
) |
|
random.shuffle(colors) |
|
return colors |
|
|
|
def paint_point_track(frames, point_tracks, visibles, colormap=None): |
|
num_points, num_frames = point_tracks.shape[0:2] |
|
if colormap is None: |
|
colormap = get_colors(num_colors=num_points) |
|
height, width = frames.shape[1:3] |
|
radius = int(round(min(height, width) * 0.015)) |
|
video = frames.copy() |
|
for t in range(num_frames): |
|
image = video[t] |
|
for i in range(num_points): |
|
x, y = point_tracks[i, t, :] |
|
x = int(np.clip(x, 0, width - 1)) |
|
y = int(np.clip(y, 0, height - 1)) |
|
if visibles[i, t]: |
|
cv2.circle(image, (x, y), radius, colormap[i], -1) |
|
video[t] = image |
|
return video |
|
|
|
|
|
pred_tracks = pred_tracks[0].cpu().numpy().transpose(1, 0, 2) |
|
pred_visibility = pred_visibility[0].cpu().numpy().transpose(1, 0) |
|
|
|
output_frames = paint_point_track(frames, pred_tracks, pred_visibility) |
|
|
|
|
|
output_video_path = os.path.join(tempfile.gettempdir(), "output_video.mp4") |
|
writer = imageio.get_writer(output_video_path, fps=25) |
|
for frame in output_frames: |
|
writer.append_data(frame) |
|
writer.close() |
|
|
|
|
|
st.video(output_video_path) |
|
|
|
st.success("Tracking Complete! 🎉") |
|
|
|
|
|
st.write("If you find any bugs, remember they're just features in disguise! 🐞") |
|
|
|
|
|
|
|
import random |
|
import requests |
|
import streamlit as st |
|
from streamlit_lottie import st_lottie |
|
|
|
class QuoteQuizGame: |
|
def __init__(self): |
|
self.questions = [ |
|
{ |
|
"question": "Who said: 'The unexamined life is not worth living'?", |
|
"choices": ["Plato", "Socrates", "Aristotle"], |
|
"correct_answer": "Socrates" |
|
}, |
|
{ |
|
"question": "Which philosopher wrote: 'God is dead. God remains dead. And we have killed him.'?", |
|
"choices": ["Jean-Paul Sartre", "Friedrich Nietzsche", "Albert Camus"], |
|
"correct_answer": "Friedrich Nietzsche" |
|
}, |
|
{ |
|
"question": "Who is credited with the quote: 'I think, therefore I am' (originally in Latin: 'Cogito, ergo sum')?", |
|
"choices": ["René Descartes", "Immanuel Kant", "John Locke"], |
|
"correct_answer": "René Descartes" |
|
}, |
|
{ |
|
"question": "Which ancient Chinese philosopher said: 'The journey of a thousand miles begins with a single step'?", |
|
"choices": ["Confucius", "Sun Tzu", "Lao Tzu"], |
|
"correct_answer": "Lao Tzu" |
|
}, |
|
{ |
|
"question": "Who wrote: 'He who has a why to live can bear almost any how'?", |
|
"choices": ["Viktor Frankl", "Friedrich Nietzsche", "Carl Jung"], |
|
"correct_answer": "Friedrich Nietzsche" |
|
}, |
|
{ |
|
"question": "Which existentialist philosopher said: 'Man is condemned to be free'?", |
|
"choices": ["Albert Camus", "Simone de Beauvoir", "Jean-Paul Sartre"], |
|
"correct_answer": "Jean-Paul Sartre" |
|
}, |
|
{ |
|
"question": "Who is known for the quote: 'The owl of Minerva spreads its wings only with the falling of the dusk'?", |
|
"choices": ["Georg Wilhelm Friedrich Hegel", "Arthur Schopenhauer", "Søren Kierkegaard"], |
|
"correct_answer": "Georg Wilhelm Friedrich Hegel" |
|
}, |
|
{ |
|
"question": "Which philosopher wrote: 'The life of man [is] solitary, poor, nasty, brutish, and short'?", |
|
"choices": ["John Locke", "Thomas Hobbes", "Jean-Jacques Rousseau"], |
|
"correct_answer": "Thomas Hobbes" |
|
}, |
|
{ |
|
"question": "Who said: 'He who fights with monsters should look to it that he himself does not become a monster'?", |
|
"choices": ["Carl Jung", "Friedrich Nietzsche", "Fyodor Dostoevsky"], |
|
"correct_answer": "Friedrich Nietzsche" |
|
}, |
|
{ |
|
"question": "Which philosopher wrote: 'The function of prayer is not to influence God, but rather to change the nature of the one who prays'?", |
|
"choices": ["Søren Kierkegaard", "Blaise Pascal", "Martin Buber"], |
|
"correct_answer": "Søren Kierkegaard" |
|
} |
|
] |
|
random.shuffle(self.questions) |
|
self.score = 0 |
|
self.current_question = 0 |
|
|
|
def get_current_question(self): |
|
return self.questions[self.current_question] |
|
|
|
def check_answer(self, answer): |
|
question = self.questions[self.current_question] |
|
if question["choices"][answer - 1] == question["correct_answer"]: |
|
self.score += 1 |
|
return True |
|
return False |
|
|
|
def next_question(self): |
|
self.current_question += 1 |
|
return self.current_question < len(self.questions) |
|
|
|
def load_lottie_url(url: str): |
|
r = requests.get(url) |
|
if r.status_code != 200: |
|
return None |
|
return r.json() |
|
|
|
def show_animation(name, url): |
|
anim = load_lottie_url(url) |
|
st_lottie(anim, key=name) |
|
|
|
def main(): |
|
|
|
st.title("Quote Quiz Game with Animations") |
|
|
|
if 'quiz_game' not in st.session_state: |
|
st.session_state.quiz_game = QuoteQuizGame() |
|
st.session_state.game_over = False |
|
|
|
quiz = st.session_state.quiz_game |
|
|
|
|
|
st.header("PhD-level Quote Quiz Game") |
|
if not st.session_state.game_over: |
|
question = quiz.get_current_question() |
|
st.write(f"Question {quiz.current_question + 1}:") |
|
st.write(question["question"]) |
|
|
|
answer = st.radio("Choose your answer:", question["choices"], key=f"question_{quiz.current_question}") |
|
|
|
if st.button("Submit Answer"): |
|
correct = quiz.check_answer(question["choices"].index(answer) + 1) |
|
if correct: |
|
st.success("Correct!") |
|
else: |
|
st.error(f"Incorrect. The correct answer was: {question['correct_answer']}") |
|
|
|
if not quiz.next_question(): |
|
st.session_state.game_over = True |
|
|
|
if st.session_state.game_over: |
|
st.write(f"Game over! Your final score is: {quiz.score} out of {len(quiz.questions)}.") |
|
if quiz.score == len(quiz.questions): |
|
st.write("Perfect score! You're a true philosophy expert!") |
|
elif quiz.score >= len(quiz.questions) * 0.8: |
|
st.write("Excellent job! You have a deep understanding of philosophical quotes.") |
|
elif quiz.score >= len(quiz.questions) * 0.6: |
|
st.write("Good effort! You have a solid grasp of famous quotes.") |
|
elif quiz.score >= len(quiz.questions) * 0.4: |
|
st.write("Not bad! There's room for improvement in your philosophical knowledge.") |
|
else: |
|
st.write("Keep studying! The world of philosophy has much to offer.") |
|
|
|
if st.button("Play Again"): |
|
st.session_state.quiz_game = QuoteQuizGame() |
|
st.session_state.game_over = False |
|
st.experimental_rerun() |
|
|
|
|
|
st.header("Animations") |
|
st.markdown('# Animations: https://lottiefiles.com/recent') |
|
st.markdown("# Animate with JSON, SVG, Adobe XD, Figma, and deploy to web, mobile as tiny animation files ") |
|
|
|
col1, col2, col3 = st.columns(3) |
|
|
|
with col1: |
|
show_animation("Badge1", "https://assets5.lottiefiles.com/packages/lf20_wtohqzml.json") |
|
show_animation("Badge2", "https://assets5.lottiefiles.com/packages/lf20_i4zw2ddg.json") |
|
show_animation("Badge3", "https://assets5.lottiefiles.com/private_files/lf30_jfhmdmk5.json") |
|
show_animation("Graph", "https://assets6.lottiefiles.com/packages/lf20_4gqhiayj.json") |
|
|
|
with col2: |
|
show_animation("PhoneBot", "https://assets9.lottiefiles.com/packages/lf20_zrqthn6o.json") |
|
show_animation("SupportBot", "https://assets5.lottiefiles.com/private_files/lf30_cmd8kh2q.json") |
|
show_animation("ChatBot", "https://assets8.lottiefiles.com/packages/lf20_j1oeaifz.json") |
|
show_animation("IntelligentMachine", "https://assets8.lottiefiles.com/packages/lf20_edouagsj.json") |
|
|
|
with col3: |
|
show_animation("GearAI", "https://assets10.lottiefiles.com/packages/lf20_3jkp7dqt.json") |
|
show_animation("ContextGraph", "https://assets10.lottiefiles.com/private_files/lf30_vwC61X.json") |
|
show_animation("Yggdrasil", "https://assets4.lottiefiles.com/packages/lf20_8q1bhU.json") |
|
show_animation("Studying", "https://assets9.lottiefiles.com/packages/lf20_6ft9bypa.json") |
|
|
|
if __name__ == "__main__": |
|
main() |