Update app.py
Browse files
app.py
CHANGED
@@ -1,182 +1,159 @@
|
|
1 |
import streamlit as st
|
2 |
-
import
|
3 |
-
from
|
4 |
-
from
|
5 |
-
from
|
6 |
-
from peft import PeftConfig
|
7 |
from accelerate import Accelerator
|
8 |
from optimum.onnxruntime import ORTModelForSequenceClassification
|
9 |
import torch
|
10 |
-
import
|
|
|
11 |
|
12 |
-
# Cache resource-intensive models
|
13 |
@st.cache_resource
|
14 |
-
def
|
15 |
return StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
|
16 |
|
17 |
# Sidebar navigation
|
18 |
-
st.sidebar.title("π€ Libraries Demo")
|
19 |
-
st.sidebar.
|
20 |
-
page = st.sidebar.selectbox(
|
21 |
-
"Choose a Section",
|
22 |
-
[
|
23 |
-
"π Home",
|
24 |
-
"π Workflow",
|
25 |
-
"π Transformers",
|
26 |
-
"πΌοΈ Diffusers",
|
27 |
-
"π Datasets",
|
28 |
-
"βοΈ PEFT",
|
29 |
-
"π Accelerate",
|
30 |
-
"β‘ Optimum",
|
31 |
-
"π DistillKit",
|
32 |
-
"π MergeKit",
|
33 |
-
"βοΈ Spectrum"
|
34 |
-
],
|
35 |
-
help="Select a library to explore!"
|
36 |
-
)
|
37 |
-
|
38 |
-
# Mermaid graph for DistillKit, MergeKit, and Spectrum workflows
|
39 |
-
mermaid_code = """
|
40 |
-
graph TD
|
41 |
-
subgraph DistillKit
|
42 |
-
A1[Load Teacher Model] --> B1[Load Student Model]
|
43 |
-
B1 --> C1[Configure Distillation]
|
44 |
-
C1 --> D1[Perform Distillation]
|
45 |
-
D1 --> E1[Evaluate Model]
|
46 |
-
end
|
47 |
-
subgraph MergeKit
|
48 |
-
A2[Select Models] --> B2[Choose Merge Method]
|
49 |
-
B2 --> C2[Set Parameters]
|
50 |
-
C2 --> D2[Merge Models]
|
51 |
-
D2 --> E2[Save Merged Model]
|
52 |
-
end
|
53 |
-
subgraph Spectrum
|
54 |
-
A3[Load Model] --> B3[Analyze Layers]
|
55 |
-
B3 --> C3[Generate Config]
|
56 |
-
C3 --> D3[Apply Freezing]
|
57 |
-
D3 --> E3[Train/Evaluate Model]
|
58 |
-
end
|
59 |
-
"""
|
60 |
-
|
61 |
-
# Home Page
|
62 |
-
if page == "π Home":
|
63 |
-
st.title("Hugging Face & Arcee Libraries Demo π")
|
64 |
-
st.markdown("""
|
65 |
-
Welcome to an interactive demo of powerful libraries for text, image, and model processing!
|
66 |
-
- **π Text**: Analyze or generate text with Transformers.
|
67 |
-
- **πΌοΈ Images**: Create visuals with Diffusers.
|
68 |
-
- **π Models**: Distill, merge, and optimize with Arcee's DistillKit, MergeKit, and Spectrum.
|
69 |
-
Navigate via the sidebar to explore each library!
|
70 |
-
""")
|
71 |
-
|
72 |
-
# Workflow Page with Mermaid Graph
|
73 |
-
elif page == "π Workflow":
|
74 |
-
st.header("π Workflows: DistillKit, MergeKit, Spectrum")
|
75 |
-
st.markdown("See how inputs flow to outputs in Arceeβs libraries with this Mermaid graph:")
|
76 |
-
components.html(f"""
|
77 |
-
<div id="mermaid"></div>
|
78 |
-
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
|
79 |
-
<script>
|
80 |
-
mermaid.initialize({{ startOnLoad: true }});
|
81 |
-
const mermaidCode = `{mermaid_code}`;
|
82 |
-
mermaid.render('graph', mermaidCode, (svgCode) => {{
|
83 |
-
document.getElementById('mermaid').innerHTML = svgCode;
|
84 |
-
}});
|
85 |
-
</script>
|
86 |
-
""", height=600)
|
87 |
|
88 |
# Transformers Section
|
89 |
-
|
90 |
-
st.header("π Transformers")
|
91 |
-
st.
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
# Diffusers Section
|
104 |
-
elif
|
105 |
-
st.header("πΌοΈ Diffusers")
|
106 |
-
st.
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
|
|
|
|
|
|
|
|
|
|
111 |
image = pipe(prompt).images[0]
|
112 |
-
st.image(image, caption=
|
|
|
|
|
|
|
|
|
113 |
|
114 |
# Datasets Section
|
115 |
-
elif
|
116 |
-
st.header("π Datasets")
|
117 |
-
st.
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
#
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
#
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
#
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
#
|
159 |
-
|
160 |
-
st.
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
+
from transformers import pipeline, AutoModel, AutoTokenizer
|
3 |
+
from diffusers import StableDiffusionPipeline, DiffusionPipeline, DDIMScheduler
|
4 |
+
from datasets import load_dataset, Dataset
|
5 |
+
from peft import PeftModel, PeftConfig, get_peft_model
|
|
|
6 |
from accelerate import Accelerator
|
7 |
from optimum.onnxruntime import ORTModelForSequenceClassification
|
8 |
import torch
|
9 |
+
from PIL import Image
|
10 |
+
import pandas as pd
|
11 |
|
12 |
+
# Cache resource-intensive models for performance
|
13 |
@st.cache_resource
|
14 |
+
def load_diffuser():
|
15 |
return StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
|
16 |
|
17 |
# Sidebar navigation
|
18 |
+
st.sidebar.title("π€ Hugging Face Libraries Demo")
|
19 |
+
library = st.sidebar.selectbox("Choose a library", ["Transformers", "Diffusers", "Datasets", "PEFT", "Accelerate", "Optimum"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
# Transformers Section
|
22 |
+
if library == "Transformers":
|
23 |
+
st.header("π Transformers: Text Processing Powerhouse")
|
24 |
+
st.write("Analyze or transform text with pre-trained NLP models. Try it out below! π")
|
25 |
+
|
26 |
+
# pipeline: Easy inference for NLP tasks
|
27 |
+
# π - Sentiment analysis with pipeline. Ex: 'I love this!' β Positive | Emotions in a snap! π
|
28 |
+
# βοΈ - Text generation with pipeline. Ex: 'Once upon a time' β Story | Spin tales fast! π
|
29 |
+
# β - Question answering with pipeline. Ex: 'Who won?' β Answer | Quiz master ready! π§
|
30 |
+
task = st.selectbox("Pick a Task", ["Sentiment Analysis ππ’", "Text Generation βοΈ", "Fill Mask π€"])
|
31 |
+
text_input = st.text_area("Enter text here βοΈ", "", placeholder="Type your text...")
|
32 |
+
|
33 |
+
if st.button("Process Text π", disabled=not text_input):
|
34 |
+
with st.spinner("Processing... β³"):
|
35 |
+
if "Sentiment" in task:
|
36 |
+
classifier = pipeline("sentiment-analysis")
|
37 |
+
result = classifier(text_input)
|
38 |
+
st.success(f"**Sentiment Result:** {result[0]['label']} (Confidence: {result[0]['score']:.2f}) β
")
|
39 |
+
st.write("π - Sentiment analysis with pipeline. Ex: 'I love this!' β Positive | Emotions in a snap! π")
|
40 |
+
elif "Text Generation" in task:
|
41 |
+
generator = pipeline("text-generation")
|
42 |
+
result = generator(text_input, max_length=50)[0]['generated_text']
|
43 |
+
st.success(f"**Generated Text:** {result} β
")
|
44 |
+
st.write("βοΈ - Text generation with pipeline. Ex: 'Once upon a time' β Story | Spin tales fast! π")
|
45 |
+
elif "Fill Mask" in task:
|
46 |
+
fill_mask = pipeline("fill-mask")
|
47 |
+
results = fill_mask(text_input.replace("[MASK]", fill_mask.tokenizer.mask_token))
|
48 |
+
for res in results[:3]:
|
49 |
+
st.write(f"Prediction: {res['sequence']} (Score: {res['score']:.2f})")
|
50 |
+
# AutoModel & AutoTokenizer: Load models and tokenizers
|
51 |
+
# π€ - Mask filling with AutoModel. Ex: 'The [MASK] is blue' β sky | Guess master! β¨
|
52 |
+
# π - Tokenizing with AutoTokenizer. Ex: 'Hello world' β tokens | Words to numbers! π’
|
53 |
+
# βοΈ - Custom inference with AutoModel. Ex: 'BERT for sentiment' β logits | Model magic! πͺ
|
54 |
+
st.write("π€ - Mask filling with pipeline. Ex: 'The [MASK] is blue' β sky | Guess master! β¨")
|
55 |
|
56 |
# Diffusers Section
|
57 |
+
elif library == "Diffusers":
|
58 |
+
st.header("πΌοΈ Diffusers: Image Generation Magic")
|
59 |
+
st.write("Turn text into stunning images with diffusion models! Let's create something cool. π¨")
|
60 |
+
|
61 |
+
# StableDiffusionPipeline: Text-to-image generation
|
62 |
+
# πΌοΈ - Text-to-image with StableDiffusionPipeline. Ex: 'Cat in space' β Image | Art from words! π
|
63 |
+
# π¨ - Style transfer with StableDiffusionPipeline. Ex: 'Van Gogh cat' β Image | Paint like pros! ποΈ
|
64 |
+
# π - Creative prompts with StableDiffusionPipeline. Ex: 'Dream city' β Image | Imagine it, see it! β¨
|
65 |
+
prompt = st.text_input("Enter a Creative Prompt π¨", "", placeholder="e.g., 'A cat in space'")
|
66 |
+
if st.button("Generate Image π", disabled=not prompt):
|
67 |
+
with st.spinner("Generating image... β³"):
|
68 |
+
pipe = load_diffuser()
|
69 |
image = pipe(prompt).images[0]
|
70 |
+
st.image(image, caption="Generated Image", use_column_width=True)
|
71 |
+
st.write("πΌοΈ - Text-to-image with StableDiffusionPipeline. Ex: 'Cat in space' β Image | Art from words! π")
|
72 |
+
# DiffusionPipeline & DDIMScheduler: Advanced diffusion control
|
73 |
+
# π§© - Inpainting with DiffusionPipeline. Ex: 'Fix broken image' β Restored | Puzzle solver! π οΈ
|
74 |
+
# π§ - Scheduling with DDIMScheduler. Ex: 'Fast diffusion' β Image | Speedy art! β‘
|
75 |
|
76 |
# Datasets Section
|
77 |
+
elif library == "Datasets":
|
78 |
+
st.header("π Datasets: Ready-to-Use Data")
|
79 |
+
st.write("Explore datasets for training or analysis. Pick one and see a sample! π")
|
80 |
+
|
81 |
+
# load_dataset: Access public datasets
|
82 |
+
# π - Load reviews with load_dataset. Ex: 'imdb' β Reviews | Movie buffs rejoice! π¬
|
83 |
+
# β - Load QA with load_dataset. Ex: 'squad' β Q&A | Trivia time! π§
|
84 |
+
# π£οΈ - Load audio with load_dataset. Ex: 'common_voice' β Audio | Hear the data! ποΈ
|
85 |
+
dataset_name = st.selectbox("Choose a Dataset", ["imdb π¬", "squad β"])
|
86 |
+
if st.button("Load Dataset π₯"):
|
87 |
+
with st.spinner("Fetching dataset... β³"):
|
88 |
+
dataset = load_dataset(dataset_name.split()[0], split="train[:5]")
|
89 |
+
st.success(f"**Dataset Loaded:** {dataset_name} (showing first 5 samples) β
")
|
90 |
+
st.write(dataset)
|
91 |
+
st.write("π - Load reviews with load_dataset. Ex: 'imdb' β Reviews | Movie buffs rejoice! π¬")
|
92 |
+
|
93 |
+
# Dataset.from_pandas: Convert DataFrames to datasets
|
94 |
+
# π - CSV to dataset with Dataset.from_pandas. Ex: 'Tweets CSV' β Dataset | Your data shines! π¦
|
95 |
+
# π - Analyze data with Dataset.from_pandas. Ex: 'Sales data' β Dataset | Numbers talk! π°
|
96 |
+
# π - Preprocess with Dataset.from_pandas. Ex: 'Raw text' β Dataset | Clean it up! π§Ή
|
97 |
+
st.subheader("Create Dataset from CSV")
|
98 |
+
uploaded_file = st.file_uploader("Upload a CSV file", type="csv")
|
99 |
+
if uploaded_file is not None:
|
100 |
+
df = pd.read_csv(uploaded_file)
|
101 |
+
dataset = Dataset.from_pandas(df)
|
102 |
+
st.write(dataset)
|
103 |
+
st.write("π - CSV to dataset with Dataset.from_pandas. Ex: 'Tweets CSV' β Dataset | Your data shines! π¦")
|
104 |
+
|
105 |
+
# PEFT Section (Simplified)
|
106 |
+
elif library == "PEFT":
|
107 |
+
st.header("βοΈ PEFT: Efficient Fine-Tuning")
|
108 |
+
st.write("Learn about parameter-efficient fine-tuning (simplified demo).")
|
109 |
+
|
110 |
+
# PeftModel: Load fine-tuned models
|
111 |
+
# βοΈ - Inference with PeftModel. Ex: 'Adapted BERT' β Output | Slim yet mighty! πͺ
|
112 |
+
# π€ - Custom tasks with PeftModel. Ex: 'NER tuning' β Tags | Precision tweak! π―
|
113 |
+
# π - Low resource with PeftModel. Ex: 'Small GPU' β Model | Efficiency wins! π
|
114 |
+
# PeftConfig: Configure PEFT settings
|
115 |
+
# π οΈ - LoRA setup with PeftConfig. Ex: 'Rank 8' β Config | Tune light! π
|
116 |
+
# π§ - Adapter config with PeftConfig. Ex: 'Task-specific' β Config | Fit like a glove! π§€
|
117 |
+
# β‘ - Fast tuning with PeftConfig. Ex: 'Quick fine-tune' β Config | Speedy prep! π
|
118 |
+
# get_peft_model: Wrap models with PEFT
|
119 |
+
# π - Enhance with get_peft_model. Ex: 'BERT + LoRA' β Model | Power boost! π
|
120 |
+
# π - Task adapt with get_peft_model. Ex: 'Sentiment' β Model | Tailored fit! βοΈ
|
121 |
+
# π - Multi-task with get_peft_model. Ex: 'QA + NER' β Model | Versatility rules! π
|
122 |
+
text = st.text_area("Enter Text to Classify βοΈ", "", placeholder="Type something...")
|
123 |
+
if st.button("Classify π", disabled=not text):
|
124 |
+
with st.spinner("Processing... β³"):
|
125 |
+
st.success("**Result:** Placeholder (PEFT reduces parameters efficiently!) β
")
|
126 |
+
st.write("βοΈ - Inference with PeftModel. Ex: 'Adapted BERT' β Output | Slim yet mighty! πͺ")
|
127 |
+
|
128 |
+
# Accelerate Section (Simplified)
|
129 |
+
elif library == "Accelerate":
|
130 |
+
st.header("π Accelerate: Device Optimization")
|
131 |
+
st.write("Optimize inference across devices with Accelerate.")
|
132 |
+
|
133 |
+
# Accelerator: Manage device placement
|
134 |
+
# π - GPU use with Accelerator. Ex: 'Auto GPU' β Device | Speed unleashed! β‘
|
135 |
+
# π - Multi-device with Accelerator. Ex: '2 GPUs' β Setup | Teamwork rocks! π€
|
136 |
+
# π οΈ - Easy setup with Accelerator. Ex: 'Model prep' β Ready | Smooth start! π
|
137 |
+
text = st.text_area("Enter Text for Sentiment Analysis βοΈ", "", placeholder="Type something...")
|
138 |
+
if st.button("Analyze π", disabled=not text):
|
139 |
+
with st.spinner("Analyzing... β³"):
|
140 |
+
accelerator = Accelerator()
|
141 |
+
classifier = pipeline("sentiment-analysis")
|
142 |
+
result = classifier(text)
|
143 |
+
st.success(f"**Result:** {result[0]['label']} (Confidence: {result[0]['score']:.2f}) β
")
|
144 |
+
st.write("π - GPU use with Accelerator. Ex: 'Auto GPU' β Device | Speed unleashed! β‘")
|
145 |
+
|
146 |
+
# Optimum Section (Simplified)
|
147 |
+
elif library == "Optimum":
|
148 |
+
st.header("β‘ Optimum: Hardware Acceleration")
|
149 |
+
st.write("Speed up inference with optimized models (e.g., ONNX).")
|
150 |
+
|
151 |
+
# ORTModelForSequenceClassification: ONNX-optimized classification
|
152 |
+
# β‘ - Fast classify with ORTModelForSequenceClassification. Ex: 'Text' β Label | Speed king! ποΈ
|
153 |
+
# π₯οΈ - CPU boost with ORTModelForSequenceClassification. Ex: 'Sentiment' β Result | No GPU? No prob! πͺ
|
154 |
+
# π - Efficient with ORTModelForSequenceClassification. Ex: 'Batch text' β Labels | Quick wins! π
|
155 |
+
text = st.text_area("Enter Text to Classify βοΈ", "", placeholder="Type something...")
|
156 |
+
if st.button("Classify π", disabled=not text):
|
157 |
+
with st.spinner("Processing... β³"):
|
158 |
+
st.success("**Result:** Placeholder (Optimum boosts speed!) β
")
|
159 |
+
st.write("β‘ - Fast classify with ORTModelForSequenceClassification. Ex: 'Text' β Label | Speed king! ποΈ")
|