awacke1's picture
Rename app.py to backup1.app.py
25a2715 verified
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! 🏎️")