import streamlit as st
import pandas as pd
import numpy as np
import time
import random
from PIL import Image

# Additional imports for CoTracker3 Demo
import torch
import imageio.v3 as iio
import matplotlib.pyplot as plt
import colorsys
import tempfile
import cv2
import os

# Set up the page configuration
st.set_page_config(
    page_title="Streamlit Super Fun Guide ๐ŸŽˆ",
    page_icon="๐ŸŽˆ",
    layout="wide",
    initial_sidebar_state="expanded",
)

# Add a header with an emoji
st.title("Welcome to the Streamlit Super Fun Guide ๐ŸŽ‰")

# Add a limerick
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!
""")

# Add a wise quote
st.write("> โ€œAny fool can write code that a computer can understand. Good programmers write code that humans can understand.โ€ โ€“ Martin Fowler")

# Sidebar navigation
st.sidebar.title("Navigation ๐Ÿงญ")
options = st.sidebar.radio("Go to", [
    "Introduction ๐Ÿš€",
    "Upload Media ๐Ÿ“",
    "Animated Charts ๐Ÿ“Š",
    "Caching Demo ๐Ÿ—ƒ๏ธ",
    "Query Parameters ๐Ÿ”",
    "Character Gallery ๐Ÿพ",
    "CoTracker3 Demo ๐Ÿ•ต๏ธโ€โ™‚๏ธ"
])

# Introduction Page
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")

# Upload Media Page
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)

# Animated Charts Page
elif options == "Animated Charts ๐Ÿ“Š":
    st.header("Animated Charts ๐Ÿ“Š")
    st.write("Watch the data come alive with live-updating charts!")

    # Live-updating line chart
    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! ๐ŸŽ‰")

# Caching Demo Page
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)  # Simulate a long computation
        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...")

# Query Parameters Page
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.")

# Character Gallery Page
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']}**")

# CoTracker3 Demo Page
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
    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",
    }

    # Video uploader
    uploaded_video = st.file_uploader("Upload a video (mp4 format)", type=["mp4"])

    # Option to select example videos
    selected_example = st.selectbox("Or select an example video", ["None"] + list(example_videos.keys()))

    # Tracking button
    if st.button("Track Points"):
        with st.spinner("Processing..."):
            # Load the video
            if uploaded_video is not None:
                # Process the uploaded video
                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":
                # Download and read the example video
                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()
            
            # Check if video is too long
            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.")
            
            # Process with CoTracker3
            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)  # B T C H W

            # Run Offline CoTracker
            cotracker = torch.hub.load("facebookresearch/co-tracker", "cotracker3_offline").to(device)
            pred_tracks, pred_visibility = cotracker(video, grid_size=grid_size)  # B T N 2,  B T N 1

            # Visualize the results
            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

            # Prepare data for visualization
            pred_tracks = pred_tracks[0].cpu().numpy().transpose(1, 0, 2)  # N x T x 2
            pred_visibility = pred_visibility[0].cpu().numpy().transpose(1, 0)  # N x T

            output_frames = paint_point_track(frames, pred_tracks, pred_visibility)

            # Save the output video
            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()

            # Display the output video
            st.video(output_video_path)

            st.success("Tracking Complete! ๐ŸŽ‰")

# Footer with self-deprecating humor
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

    # Quiz Game Section
    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()

    # Animation Section
    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()