Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,6 +6,11 @@ import csv
|
|
| 6 |
import time
|
| 7 |
from dataclasses import dataclass
|
| 8 |
import zipfile
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
st.set_page_config(page_title="SFT Tiny Titans 🚀", page_icon="🤖", layout="wide", initial_sidebar_state="expanded")
|
| 11 |
|
|
@@ -34,84 +39,122 @@ class ModelBuilder:
|
|
| 34 |
self.model = None
|
| 35 |
self.tokenizer = None
|
| 36 |
def load_model(self, model_path: str, config: ModelConfig):
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
self.tokenizer
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
def fine_tune(self, csv_path):
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
self
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
def evaluate(self, prompt: str):
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
class DiffusionBuilder:
|
| 85 |
def __init__(self):
|
| 86 |
self.config = None
|
| 87 |
self.pipeline = None
|
| 88 |
def load_model(self, model_path: str, config: DiffusionConfig):
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
def fine_tune(self, images, texts):
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
def generate(self, prompt: str):
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
# Utilities
|
| 117 |
def get_download_link(file_path, mime_type="text/plain", label="Download"):
|
|
@@ -174,12 +217,16 @@ if selected_model != "None" and st.sidebar.button("Load Model 📂"):
|
|
| 174 |
builder = ModelBuilder() if "NLP" in model_type else DiffusionBuilder()
|
| 175 |
config = (ModelConfig if "NLP" in model_type else DiffusionConfig)(name=f"titan_{int(time.time())}", base_model=selected_model)
|
| 176 |
with st.spinner("Loading... ⏳"):
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
# Tabs
|
| 182 |
-
tab1, tab2, tab3, tab4 = st.tabs(["Build Titan 🌱", "Fine-Tune Titans 🔧", "Test Titans 🧪"
|
| 183 |
|
| 184 |
with tab1:
|
| 185 |
st.header("Build Titan 🌱 (Quick Start!)")
|
|
@@ -189,12 +236,74 @@ with tab1:
|
|
| 189 |
config = (ModelConfig if "NLP" in model_type else DiffusionConfig)(name=f"titan_{int(time.time())}", base_model=base_model)
|
| 190 |
builder = ModelBuilder() if "NLP" in model_type else DiffusionBuilder()
|
| 191 |
with st.spinner("Fetching... ⏳"):
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
with tab2:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
st.header("Fine-Tune Titans 🔧 (Tune Fast!)")
|
| 199 |
if 'builder' not in st.session_state or not st.session_state.get('model_loaded', False):
|
| 200 |
st.warning("Load a Titan first! ⚠️")
|
|
@@ -203,24 +312,32 @@ with tab2:
|
|
| 203 |
st.subheader("NLP Tune 🧠")
|
| 204 |
uploaded_csv = st.file_uploader("Upload CSV", type="csv", key="nlp_csv")
|
| 205 |
if uploaded_csv and st.button("Tune NLP 🔄"):
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
elif isinstance(st.session_state['builder'], DiffusionBuilder):
|
| 211 |
st.subheader("CV Tune 🎨")
|
| 212 |
captured_images = get_gallery_files(["png"])
|
| 213 |
if len(captured_images) >= 2:
|
| 214 |
texts = ["Superhero Neon", "Hero Glow", "Cape Spark"][:len(captured_images)]
|
| 215 |
if st.button("Tune CV 🔄"):
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
else:
|
| 221 |
st.warning("Capture at least 2 images first! ⚠️")
|
| 222 |
|
| 223 |
-
with
|
| 224 |
st.header("Test Titans 🧪 (Quick Check!)")
|
| 225 |
if 'builder' not in st.session_state or not st.session_state.get('model_loaded', False):
|
| 226 |
st.warning("Load a Titan first! ⚠️")
|
|
@@ -229,55 +346,27 @@ with tab3:
|
|
| 229 |
st.subheader("NLP Test 🧠")
|
| 230 |
prompt = st.text_area("Prompt", "What’s a superhero?", key="nlp_test")
|
| 231 |
if st.button("Test NLP ▶️"):
|
| 232 |
-
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
elif isinstance(st.session_state['builder'], DiffusionBuilder):
|
| 235 |
st.subheader("CV Test 🎨")
|
| 236 |
prompt = st.text_area("Prompt", "Neon Batman", key="cv_test")
|
| 237 |
if st.button("Test CV ▶️"):
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
ctx = webrtc_streamer(
|
| 246 |
-
key="camera",
|
| 247 |
-
video_processor_factory=VideoSnapshot,
|
| 248 |
-
frontend_rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]}
|
| 249 |
-
)
|
| 250 |
-
if ctx.video_processor:
|
| 251 |
-
delay = st.slider("Delay between captures (seconds)", 0, 10, 2)
|
| 252 |
-
if st.button("Capture 6 Frames 📸"):
|
| 253 |
-
captured_images = []
|
| 254 |
-
for i in range(6):
|
| 255 |
-
snapshot = ctx.video_processor.take_snapshot()
|
| 256 |
-
if snapshot:
|
| 257 |
-
filename = generate_filename(i)
|
| 258 |
-
snapshot.save(filename)
|
| 259 |
-
st.image(snapshot, caption=filename, use_container_width=True)
|
| 260 |
-
captured_images.append(filename)
|
| 261 |
-
time.sleep(delay)
|
| 262 |
-
st.success("6 frames captured! 🎉")
|
| 263 |
-
if len(captured_images) >= 2:
|
| 264 |
-
st.session_state['captured_images'] = captured_images
|
| 265 |
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
st.
|
| 272 |
-
if st.button("Download Dataset CSV 📝"):
|
| 273 |
-
csv_path = f"diffusion_sft_{int(time.time())}.csv"
|
| 274 |
-
with open(csv_path, "w", newline="") as f:
|
| 275 |
-
writer = csv.writer(f)
|
| 276 |
-
writer.writerow(["image", "text"])
|
| 277 |
-
for img, text in dataset:
|
| 278 |
-
writer.writerow([img, text])
|
| 279 |
-
st.markdown(get_download_link(csv_path, "text/csv", "Download Dataset CSV"), unsafe_allow_html=True)
|
| 280 |
-
if st.button("Download Images ZIP 📦"):
|
| 281 |
-
zip_path = f"captured_images_{int(time.time())}.zip"
|
| 282 |
-
zip_files(st.session_state['captured_images'], zip_path)
|
| 283 |
-
st.markdown(get_download_link(zip_path, "application/zip", "Download Images ZIP"), unsafe_allow_html=True)
|
|
|
|
| 6 |
import time
|
| 7 |
from dataclasses import dataclass
|
| 8 |
import zipfile
|
| 9 |
+
import logging
|
| 10 |
+
|
| 11 |
+
# Logging setup
|
| 12 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
st.set_page_config(page_title="SFT Tiny Titans 🚀", page_icon="🤖", layout="wide", initial_sidebar_state="expanded")
|
| 16 |
|
|
|
|
| 39 |
self.model = None
|
| 40 |
self.tokenizer = None
|
| 41 |
def load_model(self, model_path: str, config: ModelConfig):
|
| 42 |
+
try:
|
| 43 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 44 |
+
import torch
|
| 45 |
+
logger.info(f"Loading NLP model: {model_path}")
|
| 46 |
+
self.model = AutoModelForCausalLM.from_pretrained(model_path)
|
| 47 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 48 |
+
if self.tokenizer.pad_token is None:
|
| 49 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 50 |
+
self.config = config
|
| 51 |
+
self.model.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
|
| 52 |
+
logger.info("NLP model loaded successfully")
|
| 53 |
+
except Exception as e:
|
| 54 |
+
logger.error(f"Error loading NLP model: {str(e)}")
|
| 55 |
+
raise
|
| 56 |
def fine_tune(self, csv_path):
|
| 57 |
+
try:
|
| 58 |
+
from torch.utils.data import Dataset, DataLoader
|
| 59 |
+
import torch
|
| 60 |
+
logger.info(f"Starting NLP fine-tuning with {csv_path}")
|
| 61 |
+
class SFTDataset(Dataset):
|
| 62 |
+
def __init__(self, data, tokenizer):
|
| 63 |
+
self.data = data
|
| 64 |
+
self.tokenizer = tokenizer
|
| 65 |
+
def __len__(self):
|
| 66 |
+
return len(self.data)
|
| 67 |
+
def __getitem__(self, idx):
|
| 68 |
+
prompt = self.data[idx]["prompt"]
|
| 69 |
+
response = self.data[idx]["response"]
|
| 70 |
+
inputs = self.tokenizer(f"{prompt} {response}", return_tensors="pt", padding="max_length", max_length=128, truncation=True)
|
| 71 |
+
labels = inputs["input_ids"].clone()
|
| 72 |
+
labels[0, :len(self.tokenizer(prompt)["input_ids"][0])] = -100
|
| 73 |
+
return {"input_ids": inputs["input_ids"][0], "attention_mask": inputs["attention_mask"][0], "labels": labels[0]}
|
| 74 |
+
data = []
|
| 75 |
+
with open(csv_path, "r") as f:
|
| 76 |
+
reader = csv.DictReader(f)
|
| 77 |
+
for row in reader:
|
| 78 |
+
data.append({"prompt": row["prompt"], "response": row["response"]})
|
| 79 |
+
dataset = SFTDataset(data, self.tokenizer)
|
| 80 |
+
dataloader = DataLoader(dataset, batch_size=2)
|
| 81 |
+
optimizer = torch.optim.AdamW(self.model.parameters(), lr=2e-5)
|
| 82 |
+
self.model.train()
|
| 83 |
+
for _ in range(1):
|
| 84 |
+
for batch in dataloader:
|
| 85 |
+
optimizer.zero_grad()
|
| 86 |
+
outputs = self.model(**{k: v.to(self.model.device) for k, v in batch.items()})
|
| 87 |
+
outputs.loss.backward()
|
| 88 |
+
optimizer.step()
|
| 89 |
+
logger.info("NLP fine-tuning completed")
|
| 90 |
+
except Exception as e:
|
| 91 |
+
logger.error(f"Error in NLP fine-tuning: {str(e)}")
|
| 92 |
+
raise
|
| 93 |
def evaluate(self, prompt: str):
|
| 94 |
+
try:
|
| 95 |
+
import torch
|
| 96 |
+
logger.info(f"Evaluating NLP with prompt: {prompt}")
|
| 97 |
+
self.model.eval()
|
| 98 |
+
with torch.no_grad():
|
| 99 |
+
inputs = self.tokenizer(prompt, return_tensors="pt", max_length=128, truncation=True).to(self.model.device)
|
| 100 |
+
outputs = self.model.generate(**inputs, max_new_tokens=50)
|
| 101 |
+
result = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 102 |
+
logger.info(f"NLP evaluation result: {result}")
|
| 103 |
+
return result
|
| 104 |
+
except Exception as e:
|
| 105 |
+
logger.error(f"Error in NLP evaluation: {str(e)}")
|
| 106 |
+
raise
|
| 107 |
|
| 108 |
class DiffusionBuilder:
|
| 109 |
def __init__(self):
|
| 110 |
self.config = None
|
| 111 |
self.pipeline = None
|
| 112 |
def load_model(self, model_path: str, config: DiffusionConfig):
|
| 113 |
+
try:
|
| 114 |
+
from diffusers import StableDiffusionPipeline
|
| 115 |
+
import torch
|
| 116 |
+
logger.info(f"Loading diffusion model: {model_path}")
|
| 117 |
+
self.pipeline = StableDiffusionPipeline.from_pretrained(model_path)
|
| 118 |
+
self.pipeline.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
|
| 119 |
+
self.config = config
|
| 120 |
+
logger.info("Diffusion model loaded successfully")
|
| 121 |
+
except Exception as e:
|
| 122 |
+
logger.error(f"Error loading diffusion model: {str(e)}")
|
| 123 |
+
raise
|
| 124 |
def fine_tune(self, images, texts):
|
| 125 |
+
try:
|
| 126 |
+
import torch
|
| 127 |
+
from PIL import Image
|
| 128 |
+
import numpy as np
|
| 129 |
+
logger.info("Starting diffusion fine-tuning")
|
| 130 |
+
optimizer = torch.optim.AdamW(self.pipeline.unet.parameters(), lr=1e-5)
|
| 131 |
+
self.pipeline.unet.train()
|
| 132 |
+
for _ in range(1):
|
| 133 |
+
for img, text in zip(images, texts):
|
| 134 |
+
optimizer.zero_grad()
|
| 135 |
+
img_tensor = torch.tensor(np.array(img)).permute(2, 0, 1).unsqueeze(0).float().to(self.pipeline.device) / 255.0 # Normalize
|
| 136 |
+
latents = self.pipeline.vae.encode(img_tensor).latent_dist.sample()
|
| 137 |
+
noise = torch.randn_like(latents)
|
| 138 |
+
timesteps = torch.randint(0, self.pipeline.scheduler.num_train_timesteps, (1,), device=latents.device)
|
| 139 |
+
noisy_latents = self.pipeline.scheduler.add_noise(latents, noise, timesteps)
|
| 140 |
+
text_emb = self.pipeline.text_encoder(self.pipeline.tokenizer(text, return_tensors="pt").input_ids.to(self.pipeline.device))[0]
|
| 141 |
+
pred_noise = self.pipeline.unet(noisy_latents, timesteps, encoder_hidden_states=text_emb).sample
|
| 142 |
+
loss = torch.nn.functional.mse_loss(pred_noise, noise)
|
| 143 |
+
loss.backward()
|
| 144 |
+
optimizer.step()
|
| 145 |
+
logger.info("Diffusion fine-tuning completed")
|
| 146 |
+
except Exception as e:
|
| 147 |
+
logger.error(f"Error in diffusion fine-tuning: {str(e)}")
|
| 148 |
+
raise
|
| 149 |
def generate(self, prompt: str):
|
| 150 |
+
try:
|
| 151 |
+
logger.info(f"Generating image with prompt: {prompt}")
|
| 152 |
+
img = self.pipeline(prompt, num_inference_steps=20).images[0]
|
| 153 |
+
logger.info("Image generated successfully")
|
| 154 |
+
return img
|
| 155 |
+
except Exception as e:
|
| 156 |
+
logger.error(f"Error in image generation: {str(e)}")
|
| 157 |
+
raise
|
| 158 |
|
| 159 |
# Utilities
|
| 160 |
def get_download_link(file_path, mime_type="text/plain", label="Download"):
|
|
|
|
| 217 |
builder = ModelBuilder() if "NLP" in model_type else DiffusionBuilder()
|
| 218 |
config = (ModelConfig if "NLP" in model_type else DiffusionConfig)(name=f"titan_{int(time.time())}", base_model=selected_model)
|
| 219 |
with st.spinner("Loading... ⏳"):
|
| 220 |
+
try:
|
| 221 |
+
builder.load_model(selected_model, config)
|
| 222 |
+
st.session_state['builder'] = builder
|
| 223 |
+
st.session_state['model_loaded'] = True
|
| 224 |
+
st.success("Model loaded! 🎉")
|
| 225 |
+
except Exception as e:
|
| 226 |
+
st.error(f"Load failed: {str(e)}")
|
| 227 |
|
| 228 |
# Tabs
|
| 229 |
+
tab1, tab2, tab3, tab4 = st.tabs(["Build Titan 🌱", "Camera Snap 📷", "Fine-Tune Titans 🔧", "Test Titans 🧪"])
|
| 230 |
|
| 231 |
with tab1:
|
| 232 |
st.header("Build Titan 🌱 (Quick Start!)")
|
|
|
|
| 236 |
config = (ModelConfig if "NLP" in model_type else DiffusionConfig)(name=f"titan_{int(time.time())}", base_model=base_model)
|
| 237 |
builder = ModelBuilder() if "NLP" in model_type else DiffusionBuilder()
|
| 238 |
with st.spinner("Fetching... ⏳"):
|
| 239 |
+
try:
|
| 240 |
+
builder.load_model(base_model, config)
|
| 241 |
+
st.session_state['builder'] = builder
|
| 242 |
+
st.session_state['model_loaded'] = True
|
| 243 |
+
st.success("Titan up! 🎉")
|
| 244 |
+
except Exception as e:
|
| 245 |
+
st.error(f"Download failed: {str(e)}")
|
| 246 |
|
| 247 |
with tab2:
|
| 248 |
+
st.header("Camera Snap 📷 (Sequence Shots!)")
|
| 249 |
+
from streamlit_webrtc import webrtc_streamer
|
| 250 |
+
ctx = webrtc_streamer(
|
| 251 |
+
key="camera",
|
| 252 |
+
video_processor_factory=VideoSnapshot,
|
| 253 |
+
frontend_rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]}
|
| 254 |
+
)
|
| 255 |
+
if ctx.video_processor:
|
| 256 |
+
delay = st.slider("Delay between captures (seconds)", 0, 10, 2)
|
| 257 |
+
if st.button("Capture 6 Frames 📸"):
|
| 258 |
+
logger.info("Starting 6-frame capture")
|
| 259 |
+
captured_images = []
|
| 260 |
+
try:
|
| 261 |
+
for i in range(6):
|
| 262 |
+
snapshot = ctx.video_processor.take_snapshot()
|
| 263 |
+
if snapshot:
|
| 264 |
+
filename = generate_filename(i)
|
| 265 |
+
snapshot.save(filename)
|
| 266 |
+
st.image(snapshot, caption=filename, use_container_width=True)
|
| 267 |
+
captured_images.append(filename)
|
| 268 |
+
logger.info(f"Captured frame {i}: {filename}")
|
| 269 |
+
time.sleep(delay)
|
| 270 |
+
st.success("6 frames captured! 🎉")
|
| 271 |
+
st.session_state['captured_images'] = captured_images
|
| 272 |
+
except Exception as e:
|
| 273 |
+
st.error(f"Capture failed: {str(e)}")
|
| 274 |
+
logger.error(f"Error during capture: {str(e)}")
|
| 275 |
+
|
| 276 |
+
if 'captured_images' in st.session_state and len(st.session_state['captured_images']) >= 2:
|
| 277 |
+
st.subheader("Diffusion SFT Dataset 🎨")
|
| 278 |
+
sample_texts = ["Neon Hero", "Glowing Cape", "Spark Flyer", "Dark Knight", "Iron Shine", "Thunder Bolt"]
|
| 279 |
+
dataset = list(zip(st.session_state['captured_images'], sample_texts[:len(st.session_state['captured_images'])]))
|
| 280 |
+
st.code("\n".join([f"{i+1}. {text} -> {img}" for i, (img, text) in enumerate(dataset)]), language="text")
|
| 281 |
+
if st.button("Download Dataset CSV 📝"):
|
| 282 |
+
logger.info("Generating dataset CSV")
|
| 283 |
+
try:
|
| 284 |
+
csv_path = f"diffusion_sft_{int(time.time())}.csv"
|
| 285 |
+
with open(csv_path, "w", newline="") as f:
|
| 286 |
+
writer = csv.writer(f)
|
| 287 |
+
writer.writerow(["image", "text"])
|
| 288 |
+
for img, text in dataset:
|
| 289 |
+
writer.writerow([img, text])
|
| 290 |
+
st.markdown(get_download_link(csv_path, "text/csv", "Download Dataset CSV"), unsafe_allow_html=True)
|
| 291 |
+
logger.info("Dataset CSV generated")
|
| 292 |
+
except Exception as e:
|
| 293 |
+
st.error(f"CSV generation failed: {str(e)}")
|
| 294 |
+
logger.error(f"Error generating CSV: {str(e)}")
|
| 295 |
+
if st.button("Download Images ZIP 📦"):
|
| 296 |
+
logger.info("Generating images ZIP")
|
| 297 |
+
try:
|
| 298 |
+
zip_path = f"captured_images_{int(time.time())}.zip"
|
| 299 |
+
zip_files(st.session_state['captured_images'], zip_path)
|
| 300 |
+
st.markdown(get_download_link(zip_path, "application/zip", "Download Images ZIP"), unsafe_allow_html=True)
|
| 301 |
+
logger.info("Images ZIP generated")
|
| 302 |
+
except Exception as e:
|
| 303 |
+
st.error(f"ZIP generation failed: {str(e)}")
|
| 304 |
+
logger.error(f"Error generating ZIP: {str(e)}")
|
| 305 |
+
|
| 306 |
+
with tab3:
|
| 307 |
st.header("Fine-Tune Titans 🔧 (Tune Fast!)")
|
| 308 |
if 'builder' not in st.session_state or not st.session_state.get('model_loaded', False):
|
| 309 |
st.warning("Load a Titan first! ⚠️")
|
|
|
|
| 312 |
st.subheader("NLP Tune 🧠")
|
| 313 |
uploaded_csv = st.file_uploader("Upload CSV", type="csv", key="nlp_csv")
|
| 314 |
if uploaded_csv and st.button("Tune NLP 🔄"):
|
| 315 |
+
logger.info("Initiating NLP fine-tune")
|
| 316 |
+
try:
|
| 317 |
+
with open("temp.csv", "wb") as f:
|
| 318 |
+
f.write(uploaded_csv.read())
|
| 319 |
+
st.session_state['builder'].fine_tune("temp.csv")
|
| 320 |
+
st.success("NLP sharpened! 🎉")
|
| 321 |
+
except Exception as e:
|
| 322 |
+
st.error(f"NLP fine-tune failed: {str(e)}")
|
| 323 |
elif isinstance(st.session_state['builder'], DiffusionBuilder):
|
| 324 |
st.subheader("CV Tune 🎨")
|
| 325 |
captured_images = get_gallery_files(["png"])
|
| 326 |
if len(captured_images) >= 2:
|
| 327 |
texts = ["Superhero Neon", "Hero Glow", "Cape Spark"][:len(captured_images)]
|
| 328 |
if st.button("Tune CV 🔄"):
|
| 329 |
+
logger.info("Initiating CV fine-tune")
|
| 330 |
+
try:
|
| 331 |
+
from PIL import Image
|
| 332 |
+
images = [Image.open(img) for img in captured_images]
|
| 333 |
+
st.session_state['builder'].fine_tune(images, texts)
|
| 334 |
+
st.success("CV polished! 🎉")
|
| 335 |
+
except Exception as e:
|
| 336 |
+
st.error(f"CV fine-tune failed: {str(e)}")
|
| 337 |
else:
|
| 338 |
st.warning("Capture at least 2 images first! ⚠️")
|
| 339 |
|
| 340 |
+
with tab4:
|
| 341 |
st.header("Test Titans 🧪 (Quick Check!)")
|
| 342 |
if 'builder' not in st.session_state or not st.session_state.get('model_loaded', False):
|
| 343 |
st.warning("Load a Titan first! ⚠️")
|
|
|
|
| 346 |
st.subheader("NLP Test 🧠")
|
| 347 |
prompt = st.text_area("Prompt", "What’s a superhero?", key="nlp_test")
|
| 348 |
if st.button("Test NLP ▶️"):
|
| 349 |
+
logger.info("Running NLP test")
|
| 350 |
+
try:
|
| 351 |
+
result = st.session_state['builder'].evaluate(prompt)
|
| 352 |
+
st.write(f"**Answer**: {result}")
|
| 353 |
+
except Exception as e:
|
| 354 |
+
st.error(f"NLP test failed: {str(e)}")
|
| 355 |
elif isinstance(st.session_state['builder'], DiffusionBuilder):
|
| 356 |
st.subheader("CV Test 🎨")
|
| 357 |
prompt = st.text_area("Prompt", "Neon Batman", key="cv_test")
|
| 358 |
if st.button("Test CV ▶️"):
|
| 359 |
+
logger.info("Running CV test")
|
| 360 |
+
try:
|
| 361 |
+
with st.spinner("Generating... ⏳"):
|
| 362 |
+
img = st.session_state['builder'].generate(prompt)
|
| 363 |
+
st.image(img, caption="Generated Art", use_container_width=True)
|
| 364 |
+
except Exception as e:
|
| 365 |
+
st.error(f"CV test failed: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
|
| 367 |
+
# Display Logs
|
| 368 |
+
st.sidebar.subheader("Action Logs 📜")
|
| 369 |
+
log_container = st.sidebar.empty()
|
| 370 |
+
with log_container:
|
| 371 |
+
for record in logger.handlers[0].buffer:
|
| 372 |
+
st.write(f"{record.asctime} - {record.levelname} - {record.message}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|