- Spec files
pypi-streamlit
Describes: pkg:pypi/streamlit@1.49.x
- Description
- A faster way to build and share data apps
- Author
- tessl
- Last updated
media-status.md docs/
1# Media and Status23Media display capabilities and status messaging functions for rich content presentation and user feedback. These components enable multimedia content display and effective user communication.45## Capabilities67### Media Display89Display images, audio, video, and PDF content with various formatting options.1011```python { .api }12def image(image, caption=None, width=None, use_column_width=None, clamp=False, channels="RGB", output_format="auto", use_container_width=False):13"""14Display an image or list of images.1516Parameters:17- image: Image data (PIL Image, numpy array, file path, URL, or bytes)18- caption (str or list): Image caption(s)19- width (int): Image width in pixels20- use_column_width (bool): Deprecated - use use_container_width instead21- clamp (bool): Clamp image pixel values to valid range22- channels (str): Color channel interpretation ('RGB' or 'BGR')23- output_format (str): Output format ('JPEG', 'PNG', or 'auto')24- use_container_width (bool): Use full container width2526Returns:27None28"""2930def audio(data, format="audio/wav", start_time=0, sample_rate=None, end_time=None, loop=False, autoplay=False):31"""32Display an audio player widget.3334Parameters:35- data: Audio data (file path, URL, bytes, or numpy array)36- format (str): Audio format MIME type37- start_time (int): Start playback time in seconds38- sample_rate (int): Sample rate for numpy array data39- end_time (int): End playback time in seconds40- loop (bool): Loop audio playback41- autoplay (bool): Start playing automatically4243Returns:44None45"""4647def video(data, format="video/mp4", start_time=0, subtitles=None, end_time=None, loop=False, autoplay=False, muted=False):48"""49Display a video player widget.5051Parameters:52- data: Video data (file path, URL, or bytes)53- format (str): Video format MIME type54- start_time (int): Start playback time in seconds55- subtitles (str or list): Subtitle file path(s) or WebVTT content56- end_time (int): End playback time in seconds57- loop (bool): Loop video playback58- autoplay (bool): Start playing automatically59- muted (bool): Start with audio muted6061Returns:62None63"""6465def pdf(data, width=None, height=600):66"""67Display a PDF viewer widget.6869Parameters:70- data: PDF data (file path, URL, or bytes)71- width (int): Viewer width in pixels72- height (int): Viewer height in pixels7374Returns:75None76"""77```7879### Status Messages8081Provide user feedback with different severity levels and styling.8283```python { .api }84def success(body, icon=True):85"""86Display a success message with green styling.8788Parameters:89- body (str): Success message text90- icon (bool or str): Show success icon or custom icon name9192Returns:93None94"""9596def info(body, icon=True):97"""98Display an informational message with blue styling.99100Parameters:101- body (str): Information message text102- icon (bool or str): Show info icon or custom icon name103104Returns:105None106"""107108def warning(body, icon=True):109"""110Display a warning message with yellow styling.111112Parameters:113- body (str): Warning message text114- icon (bool or str): Show warning icon or custom icon name115116Returns:117None118"""119120def error(body, icon=True):121"""122Display an error message with red styling.123124Parameters:125- body (str): Error message text126- icon (bool or str): Show error icon or custom icon name127128Returns:129None130"""131132def exception(exception):133"""134Display an exception with full traceback.135136Parameters:137- exception (Exception): Exception object to display138139Returns:140None141"""142```143144### Interactive Notifications145146Display temporary notifications and celebratory animations.147148```python { .api }149def toast(body, icon=None):150"""151Display a toast notification that appears temporarily.152153Parameters:154- body (str): Toast message text155- icon (str): Optional icon name or emoji156157Returns:158None159"""160161def balloons():162"""163Display celebratory balloons animation.164165Returns:166None167"""168169def snow():170"""171Display falling snow animation.172173Returns:174None175"""176```177178### User Feedback Widgets179180Collect user feedback and interaction responses.181182```python { .api }183def feedback(options, key=None, disabled=False, on_change=None, args=None, kwargs=None):184"""185Display a feedback widget for collecting user sentiment.186187Parameters:188- options (str): Type of feedback options ('thumbs' or 'faces')189- key (str): Unique key for the widget190- disabled (bool): Disable the widget191- on_change (callable): Function to call when feedback changes192- args (tuple): Arguments to pass to on_change function193- kwargs (dict): Keyword arguments to pass to on_change function194195Returns:196dict or None: Feedback score and sentiment information197"""198199def badge(label, background_color=None):200"""201Display a badge element with optional color.202203Parameters:204- label (str): Badge text205- background_color (str): Badge background color (hex, CSS name, or None)206207Returns:208None209"""210```211212## Usage Examples213214### Image Display215216```python217import streamlit as st218from PIL import Image219import numpy as np220221# Display image from file222st.subheader("Image from File")223try:224image = Image.open("sample_image.jpg")225st.image(image, caption="Sample Image", use_container_width=True)226except FileNotFoundError:227st.error("Image file not found")228229# Display image from URL230st.subheader("Image from URL")231st.image(232"https://static.streamlit.io/examples/cat.jpg",233caption="Cat from URL",234width=300235)236237# Display numpy array as image238st.subheader("Generated Image")239image_array = np.random.randint(0, 255, (200, 200, 3), dtype=np.uint8)240st.image(image_array, caption="Random noise image", clamp=True)241242# Display multiple images243st.subheader("Image Gallery")244images = [245"https://static.streamlit.io/examples/cat.jpg",246"https://static.streamlit.io/examples/dog.jpg"247]248captions = ["Cat", "Dog"]249st.image(images, caption=captions, width=200)250```251252### Audio and Video253254```python255# Display audio player256st.subheader("Audio Player")257258# From file259try:260audio_file = open("sample_audio.wav", "rb")261audio_bytes = audio_file.read()262st.audio(audio_bytes, format="audio/wav")263audio_file.close()264except FileNotFoundError:265st.info("Audio file not available for demo")266267# From URL268st.audio("https://www.soundjay.com/misc/sounds/bell-ringing-05.wav")269270# Video player271st.subheader("Video Player")272273# Local video file274try:275video_file = open("sample_video.mp4", "rb")276video_bytes = video_file.read()277st.video(video_bytes, start_time=10) # Start at 10 seconds278video_file.close()279except FileNotFoundError:280st.info("Video file not available for demo")281282# Video with subtitles283st.video(284"sample_video.mp4",285subtitles="subtitles.vtt",286loop=True,287autoplay=False288)289```290291### PDF Viewer292293```python294# Display PDF document295st.subheader("PDF Document")296297try:298with open("document.pdf", "rb") as pdf_file:299pdf_bytes = pdf_file.read()300301st.pdf(pdf_bytes, width=700)302except FileNotFoundError:303st.info("PDF file not available for demo")304305# PDF from URL306st.pdf("https://example.com/sample.pdf", height=400)307```308309### Status Messages310311```python312# Different types of status messages313st.subheader("Status Messages")314315st.success("✅ Operation completed successfully!")316st.info("ℹ️ Here's some helpful information.")317st.warning("⚠️ Please review your input carefully.")318st.error("❌ An error occurred during processing.")319320# Status messages with custom icons321st.success("Data saved!", icon="💾")322st.info("New features available", icon="🚀")323st.warning("Server maintenance scheduled", icon="🔧")324st.error("Connection failed", icon="🌐")325326# Exception display327try:328result = 1 / 0329except ZeroDivisionError as e:330st.exception(e)331```332333### Toast Notifications334335```python336# Toast notifications (appear temporarily)337if st.button("Show Success Toast"):338st.toast("Success! Operation completed.", icon="✅")339340if st.button("Show Info Toast"):341st.toast("Information: Check your email.", icon="📧")342343if st.button("Show Warning Toast"):344st.toast("Warning: Please save your work.", icon="⚠️")345346if st.button("Show Custom Toast"):347st.toast("Custom notification!", icon="🎉")348```349350### Celebrations351352```python353# Celebratory animations354col1, col2 = st.columns(2)355356with col1:357if st.button("🎈 Celebrate with Balloons"):358st.balloons()359st.success("Congratulations! 🎉")360361with col2:362if st.button("❄️ Let it Snow"):363st.snow()364st.info("Winter wonderland! ⛄")365```366367### User Feedback Collection368369```python370# Feedback widgets371st.subheader("Feedback Collection")372373# Thumbs up/down feedback374feedback_1 = st.feedback("thumbs", key="feedback_1")375if feedback_1:376st.write(f"Feedback received: {feedback_1}")377378# Faces feedback (1-5 scale)379feedback_2 = st.feedback("faces", key="feedback_2")380if feedback_2:381st.write(f"Rating: {feedback_2['score']}/5")382383# Badge display384st.subheader("Badges")385col1, col2, col3 = st.columns(3)386387with col1:388st.badge("New", background_color="#FF6B6B")389390with col2:391st.badge("Premium", background_color="#4ECDC4")392393with col3:394st.badge("Beta", background_color="#45B7D1")395```396397### Media with Interactive Controls398399```python400# Interactive media controls401st.subheader("Interactive Media Player")402403# Media controls404col1, col2 = st.columns([3, 1])405406with col1:407# Video player with user controls408autoplay = st.checkbox("Autoplay")409loop_video = st.checkbox("Loop")410muted = st.checkbox("Muted")411412start_time = st.slider("Start time (seconds)", 0, 300, 0)413414with col2:415st.write("**Player Settings**")416417if st.button("Load Video"):418st.video(419"sample_video.mp4",420autoplay=autoplay,421loop=loop_video,422muted=muted,423start_time=start_time424)425```426427### Status Message with Actions428429```python430# Status messages with follow-up actions431error_occurred = st.checkbox("Simulate error condition")432433if error_occurred:434st.error("Database connection failed!", icon="🔌")435436col1, col2, col3 = st.columns(3)437438with col1:439if st.button("Retry Connection"):440st.success("Connection restored!")441442with col2:443if st.button("Check Status"):444st.info("System status: All services operational")445446with col3:447if st.button("Contact Support"):448st.info("Support ticket created: #12345")449450# Success with next steps451if st.button("Complete Process"):452st.success("✅ File uploaded successfully!")453st.balloons()454455with st.expander("Next Steps"):456st.write("1. Review the uploaded data")457st.write("2. Configure processing options")458st.write("3. Start the analysis")459```460461### Conditional Media Display462463```python464# Conditional media based on user selection465media_type = st.selectbox(466"Select media type:",467["None", "Image", "Audio", "Video", "PDF"]468)469470if media_type == "Image":471st.image(472"https://static.streamlit.io/examples/cat.jpg",473caption="Sample image",474use_container_width=True475)476477elif media_type == "Audio":478st.audio("https://www.soundjay.com/misc/sounds/bell-ringing-05.wav")479480elif media_type == "Video":481st.video("https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4")482483elif media_type == "PDF":484st.info("PDF viewer would display here with actual PDF file")485486else:487st.info("Select a media type to display content")488```