import streamlit as st from transformers import pipeline, AutoModel, AutoTokenizer from diffusers import StableDiffusionPipeline, DiffusionPipeline, DDIMScheduler from datasets import load_dataset, Dataset from peft import PeftModel, PeftConfig, get_peft_model from accelerate import Accelerator from optimum.onnxruntime import ORTModelForSequenceClassification import torch from PIL import Image import pandas as pd # Cache resource-intensive models for performance @st.cache_resource def load_diffuser(): return StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") # Sidebar navigation st.sidebar.title("๐Ÿค— Hugging Face Libraries Demo") library = st.sidebar.selectbox("Choose a library", ["Transformers", "Diffusers", "Datasets", "PEFT", "Accelerate", "Optimum"]) # Transformers Section if library == "Transformers": st.header("๐Ÿ“ Transformers: Text Processing Powerhouse") st.write("Analyze or transform text with pre-trained NLP models. Try it out below! ๐Ÿ‘‡") # pipeline: Easy inference for NLP tasks # ๐ŸŽญ - Sentiment analysis with pipeline. Ex: 'I love this!' โ†’ Positive | Emotions in a snap! ๐Ÿ˜Š # โœ๏ธ - Text generation with pipeline. Ex: 'Once upon a time' โ†’ Story | Spin tales fast! ๐Ÿ“– # โ“ - Question answering with pipeline. Ex: 'Who won?' โ†’ Answer | Quiz master ready! ๐Ÿง  task = st.selectbox("Pick a Task", ["Sentiment Analysis ๐Ÿ˜Š๐Ÿ˜ข", "Text Generation โœ๏ธ", "Fill Mask ๐Ÿค–"]) text_input = st.text_area("Enter text here โœ๏ธ", "", placeholder="Type your text...") if st.button("Process Text ๐Ÿš€", disabled=not text_input): with st.spinner("Processing... โณ"): if "Sentiment" in task: classifier = pipeline("sentiment-analysis") result = classifier(text_input) st.success(f"**Sentiment Result:** {result[0]['label']} (Confidence: {result[0]['score']:.2f}) โœ…") st.write("๐ŸŽญ - Sentiment analysis with pipeline. Ex: 'I love this!' โ†’ Positive | Emotions in a snap! ๐Ÿ˜Š") elif "Text Generation" in task: generator = pipeline("text-generation") result = generator(text_input, max_length=50)[0]['generated_text'] st.success(f"**Generated Text:** {result} โœ…") st.write("โœ๏ธ - Text generation with pipeline. Ex: 'Once upon a time' โ†’ Story | Spin tales fast! ๐Ÿ“–") elif "Fill Mask" in task: fill_mask = pipeline("fill-mask") results = fill_mask(text_input.replace("[MASK]", fill_mask.tokenizer.mask_token)) for res in results[:3]: st.write(f"Prediction: {res['sequence']} (Score: {res['score']:.2f})") # AutoModel & AutoTokenizer: Load models and tokenizers # ๐Ÿค– - Mask filling with AutoModel. Ex: 'The [MASK] is blue' โ†’ sky | Guess master! โœจ # ๐Ÿ“ - Tokenizing with AutoTokenizer. Ex: 'Hello world' โ†’ tokens | Words to numbers! ๐Ÿ”ข # โš™๏ธ - Custom inference with AutoModel. Ex: 'BERT for sentiment' โ†’ logits | Model magic! ๐Ÿช„ st.write("๐Ÿค– - Mask filling with pipeline. Ex: 'The [MASK] is blue' โ†’ sky | Guess master! โœจ") # Diffusers Section elif library == "Diffusers": st.header("๐Ÿ–ผ๏ธ Diffusers: Image Generation Magic") st.write("Turn text into stunning images with diffusion models! Let's create something cool. ๐ŸŽจ") # StableDiffusionPipeline: Text-to-image generation # ๐Ÿ–ผ๏ธ - Text-to-image with StableDiffusionPipeline. Ex: 'Cat in space' โ†’ Image | Art from words! ๐Ÿš€ # ๐ŸŽจ - Style transfer with StableDiffusionPipeline. Ex: 'Van Gogh cat' โ†’ Image | Paint like pros! ๐Ÿ–Œ๏ธ # ๐ŸŒŸ - Creative prompts with StableDiffusionPipeline. Ex: 'Dream city' โ†’ Image | Imagine it, see it! โœจ prompt = st.text_input("Enter a Creative Prompt ๐ŸŽจ", "", placeholder="e.g., 'A cat in space'") if st.button("Generate Image ๐ŸŒŸ", disabled=not prompt): with st.spinner("Generating image... โณ"): pipe = load_diffuser() image = pipe(prompt).images[0] st.image(image, caption="Generated Image", use_column_width=True) st.write("๐Ÿ–ผ๏ธ - Text-to-image with StableDiffusionPipeline. Ex: 'Cat in space' โ†’ Image | Art from words! ๐Ÿš€") # DiffusionPipeline & DDIMScheduler: Advanced diffusion control # ๐Ÿงฉ - Inpainting with DiffusionPipeline. Ex: 'Fix broken image' โ†’ Restored | Puzzle solver! ๐Ÿ› ๏ธ # ๐Ÿ”ง - Scheduling with DDIMScheduler. Ex: 'Fast diffusion' โ†’ Image | Speedy art! โšก # Datasets Section elif library == "Datasets": st.header("๐Ÿ“Š Datasets: Ready-to-Use Data") st.write("Explore datasets for training or analysis. Pick one and see a sample! ๐Ÿ“ˆ") # load_dataset: Access public datasets # ๐Ÿ“š - Load reviews with load_dataset. Ex: 'imdb' โ†’ Reviews | Movie buffs rejoice! ๐ŸŽฌ # โ“ - Load QA with load_dataset. Ex: 'squad' โ†’ Q&A | Trivia time! ๐Ÿง  # ๐Ÿ—ฃ๏ธ - Load audio with load_dataset. Ex: 'common_voice' โ†’ Audio | Hear the data! ๐ŸŽ™๏ธ dataset_name = st.selectbox("Choose a Dataset", ["imdb ๐ŸŽฌ", "squad โ“"]) if st.button("Load Dataset ๐Ÿ“ฅ"): with st.spinner("Fetching dataset... โณ"): dataset = load_dataset(dataset_name.split()[0], split="train[:5]") st.success(f"**Dataset Loaded:** {dataset_name} (showing first 5 samples) โœ…") st.write(dataset) st.write("๐Ÿ“š - Load reviews with load_dataset. Ex: 'imdb' โ†’ Reviews | Movie buffs rejoice! ๐ŸŽฌ") # Dataset.from_pandas: Convert DataFrames to datasets # ๐Ÿ“Š - CSV to dataset with Dataset.from_pandas. Ex: 'Tweets CSV' โ†’ Dataset | Your data shines! ๐Ÿฆ # ๐Ÿ“ˆ - Analyze data with Dataset.from_pandas. Ex: 'Sales data' โ†’ Dataset | Numbers talk! ๐Ÿ’ฐ # ๐Ÿ”„ - Preprocess with Dataset.from_pandas. Ex: 'Raw text' โ†’ Dataset | Clean it up! ๐Ÿงน st.subheader("Create Dataset from CSV") uploaded_file = st.file_uploader("Upload a CSV file", type="csv") if uploaded_file is not None: df = pd.read_csv(uploaded_file) dataset = Dataset.from_pandas(df) st.write(dataset) st.write("๐Ÿ“Š - CSV to dataset with Dataset.from_pandas. Ex: 'Tweets CSV' โ†’ Dataset | Your data shines! ๐Ÿฆ") # PEFT Section (Simplified) elif library == "PEFT": st.header("โš™๏ธ PEFT: Efficient Fine-Tuning") st.write("Learn about parameter-efficient fine-tuning (simplified demo).") # PeftModel: Load fine-tuned models # โš™๏ธ - Inference with PeftModel. Ex: 'Adapted BERT' โ†’ Output | Slim yet mighty! ๐Ÿ’ช # ๐Ÿค– - Custom tasks with PeftModel. Ex: 'NER tuning' โ†’ Tags | Precision tweak! ๐ŸŽฏ # ๐Ÿ“‰ - Low resource with PeftModel. Ex: 'Small GPU' โ†’ Model | Efficiency wins! ๐Ÿ† # PeftConfig: Configure PEFT settings # ๐Ÿ› ๏ธ - LoRA setup with PeftConfig. Ex: 'Rank 8' โ†’ Config | Tune light! ๐ŸŒŸ # ๐Ÿ”ง - Adapter config with PeftConfig. Ex: 'Task-specific' โ†’ Config | Fit like a glove! ๐Ÿงค # โšก - Fast tuning with PeftConfig. Ex: 'Quick fine-tune' โ†’ Config | Speedy prep! ๐Ÿƒ # get_peft_model: Wrap models with PEFT # ๐Ÿ”— - Enhance with get_peft_model. Ex: 'BERT + LoRA' โ†’ Model | Power boost! ๐Ÿš€ # ๐Ÿ“ - Task adapt with get_peft_model. Ex: 'Sentiment' โ†’ Model | Tailored fit! โœ‚๏ธ # ๐ŸŒ - Multi-task with get_peft_model. Ex: 'QA + NER' โ†’ Model | Versatility rules! ๐ŸŒ text = st.text_area("Enter Text to Classify โœ๏ธ", "", placeholder="Type something...") if st.button("Classify ๐Ÿš€", disabled=not text): with st.spinner("Processing... โณ"): st.success("**Result:** Placeholder (PEFT reduces parameters efficiently!) โœ…") st.write("โš™๏ธ - Inference with PeftModel. Ex: 'Adapted BERT' โ†’ Output | Slim yet mighty! ๐Ÿ’ช") # Accelerate Section (Simplified) elif library == "Accelerate": st.header("๐Ÿš€ Accelerate: Device Optimization") st.write("Optimize inference across devices with Accelerate.") # Accelerator: Manage device placement # ๐Ÿš€ - GPU use with Accelerator. Ex: 'Auto GPU' โ†’ Device | Speed unleashed! โšก # ๐Ÿ”— - Multi-device with Accelerator. Ex: '2 GPUs' โ†’ Setup | Teamwork rocks! ๐Ÿค # ๐Ÿ› ๏ธ - Easy setup with Accelerator. Ex: 'Model prep' โ†’ Ready | Smooth start! ๐ŸŒˆ text = st.text_area("Enter Text for Sentiment Analysis โœ๏ธ", "", placeholder="Type something...") if st.button("Analyze ๐Ÿš€", disabled=not text): with st.spinner("Analyzing... โณ"): accelerator = Accelerator() classifier = pipeline("sentiment-analysis") result = classifier(text) st.success(f"**Result:** {result[0]['label']} (Confidence: {result[0]['score']:.2f}) โœ…") st.write("๐Ÿš€ - GPU use with Accelerator. Ex: 'Auto GPU' โ†’ Device | Speed unleashed! โšก") # Optimum Section (Simplified) elif library == "Optimum": st.header("โšก Optimum: Hardware Acceleration") st.write("Speed up inference with optimized models (e.g., ONNX).") # ORTModelForSequenceClassification: ONNX-optimized classification # โšก - Fast classify with ORTModelForSequenceClassification. Ex: 'Text' โ†’ Label | Speed king! ๐ŸŽ๏ธ # ๐Ÿ–ฅ๏ธ - CPU boost with ORTModelForSequenceClassification. Ex: 'Sentiment' โ†’ Result | No GPU? No prob! ๐Ÿ’ช # ๐Ÿ“Š - Efficient with ORTModelForSequenceClassification. Ex: 'Batch text' โ†’ Labels | Quick wins! ๐Ÿ† text = st.text_area("Enter Text to Classify โœ๏ธ", "", placeholder="Type something...") if st.button("Classify ๐Ÿš€", disabled=not text): with st.spinner("Processing... โณ"): st.success("**Result:** Placeholder (Optimum boosts speed!) โœ…") st.write("โšก - Fast classify with ORTModelForSequenceClassification. Ex: 'Text' โ†’ Label | Speed king! ๐ŸŽ๏ธ")