awacke1 commited on
Commit
6f8a2f4
·
verified ·
1 Parent(s): d09942e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +459 -0
app.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import shutil
4
+ import glob
5
+ import base64
6
+ import streamlit as st
7
+ import pandas as pd
8
+ import torch
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer
10
+ from torch.utils.data import Dataset, DataLoader
11
+ import csv
12
+ import time
13
+ from dataclasses import dataclass
14
+ from typing import Optional, Tuple
15
+ import zipfile
16
+ import math
17
+ from PIL import Image
18
+ import random
19
+ import logging
20
+ import numpy as np
21
+
22
+ # Logging setup
23
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
24
+ logger = logging.getLogger(__name__)
25
+
26
+ # Page Configuration
27
+ st.set_page_config(
28
+ page_title="SFT Tiny Titans 🚀",
29
+ page_icon="🤖",
30
+ layout="wide",
31
+ initial_sidebar_state="expanded",
32
+ menu_items={
33
+ 'Get Help': 'https://huggingface.co/awacke1',
34
+ 'Report a bug': 'https://huggingface.co/spaces/awacke1',
35
+ 'About': "Tiny Titans: Small models, big dreams, and a sprinkle of chaos! 🌌"
36
+ }
37
+ )
38
+
39
+ # Model Configuration Classes
40
+ @dataclass
41
+ class ModelConfig:
42
+ name: str
43
+ base_model: str
44
+ size: str
45
+ domain: Optional[str] = None
46
+ model_type: str = "causal_lm"
47
+ @property
48
+ def model_path(self):
49
+ return f"models/{self.name}"
50
+
51
+ @dataclass
52
+ class DiffusionConfig:
53
+ name: str
54
+ base_model: str
55
+ size: str
56
+ @property
57
+ def model_path(self):
58
+ return f"diffusion_models/{self.name}"
59
+
60
+ # Datasets
61
+ class SFTDataset(Dataset):
62
+ def __init__(self, data, tokenizer, max_length=128):
63
+ self.data = data
64
+ self.tokenizer = tokenizer
65
+ self.max_length = max_length
66
+ def __len__(self):
67
+ return len(self.data)
68
+ def __getitem__(self, idx):
69
+ prompt = self.data[idx]["prompt"]
70
+ response = self.data[idx]["response"]
71
+ full_text = f"{prompt} {response}"
72
+ full_encoding = self.tokenizer(full_text, max_length=self.max_length, padding="max_length", truncation=True, return_tensors="pt")
73
+ prompt_encoding = self.tokenizer(prompt, max_length=self.max_length, padding=False, truncation=True, return_tensors="pt")
74
+ input_ids = full_encoding["input_ids"].squeeze()
75
+ attention_mask = full_encoding["attention_mask"].squeeze()
76
+ labels = input_ids.clone()
77
+ prompt_len = prompt_encoding["input_ids"].shape[1]
78
+ if prompt_len < self.max_length:
79
+ labels[:prompt_len] = -100
80
+ return {"input_ids": input_ids, "attention_mask": attention_mask, "labels": labels}
81
+
82
+ class DiffusionDataset(Dataset):
83
+ def __init__(self, images, texts):
84
+ self.images = images
85
+ self.texts = texts
86
+ def __len__(self):
87
+ return len(self.images)
88
+ def __getitem__(self, idx):
89
+ return {"image": self.images[idx], "text": self.texts[idx]}
90
+
91
+ # Model Builders
92
+ class ModelBuilder:
93
+ def __init__(self):
94
+ self.config = None
95
+ self.model = None
96
+ self.tokenizer = None
97
+ self.sft_data = None
98
+ self.jokes = ["Why did the AI go to therapy? Too many layers to unpack! 😂", "Training complete! Time for a binary coffee break. ☕"]
99
+ def load_model(self, model_path: str, config: Optional[ModelConfig] = None):
100
+ with st.spinner(f"Loading {model_path}... ⏳"):
101
+ self.model = AutoModelForCausalLM.from_pretrained(model_path)
102
+ self.tokenizer = AutoTokenizer.from_pretrained(model_path)
103
+ if self.tokenizer.pad_token is None:
104
+ self.tokenizer.pad_token = self.tokenizer.eos_token
105
+ if config:
106
+ self.config = config
107
+ st.success(f"Model loaded! 🎉 {random.choice(self.jokes)}")
108
+ return self
109
+ def fine_tune_sft(self, csv_path: str, epochs: int = 3, batch_size: int = 4):
110
+ self.sft_data = []
111
+ with open(csv_path, "r") as f:
112
+ reader = csv.DictReader(f)
113
+ for row in reader:
114
+ self.sft_data.append({"prompt": row["prompt"], "response": row["response"]})
115
+ dataset = SFTDataset(self.sft_data, self.tokenizer)
116
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
117
+ optimizer = torch.optim.AdamW(self.model.parameters(), lr=2e-5)
118
+ self.model.train()
119
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
120
+ self.model.to(device)
121
+ for epoch in range(epochs):
122
+ with st.spinner(f"Training epoch {epoch + 1}/{epochs}... ⚙️"):
123
+ total_loss = 0
124
+ for batch in dataloader:
125
+ optimizer.zero_grad()
126
+ input_ids = batch["input_ids"].to(device)
127
+ attention_mask = batch["attention_mask"].to(device)
128
+ labels = batch["labels"].to(device)
129
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
130
+ loss = outputs.loss
131
+ loss.backward()
132
+ optimizer.step()
133
+ total_loss += loss.item()
134
+ st.write(f"Epoch {epoch + 1} completed. Average loss: {total_loss / len(dataloader):.4f}")
135
+ st.success(f"SFT Fine-tuning completed! 🎉 {random.choice(self.jokes)}")
136
+ return self
137
+ def save_model(self, path: str):
138
+ with st.spinner("Saving model... 💾"):
139
+ os.makedirs(os.path.dirname(path), exist_ok=True)
140
+ self.model.save_pretrained(path)
141
+ self.tokenizer.save_pretrained(path)
142
+ st.success(f"Model saved at {path}! ✅")
143
+ def evaluate(self, prompt: str, status_container=None):
144
+ self.model.eval()
145
+ if status_container:
146
+ status_container.write("Preparing to evaluate... 🧠")
147
+ try:
148
+ with torch.no_grad():
149
+ inputs = self.tokenizer(prompt, return_tensors="pt", max_length=128, truncation=True).to(self.model.device)
150
+ outputs = self.model.generate(**inputs, max_new_tokens=50, do_sample=True, top_p=0.95, temperature=0.7)
151
+ return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
152
+ except Exception as e:
153
+ if status_container:
154
+ status_container.error(f"Oops! Something broke: {str(e)} 💥")
155
+ return f"Error: {str(e)}"
156
+
157
+ class DiffusionBuilder:
158
+ def __init__(self):
159
+ self.config = None
160
+ self.pipeline = None
161
+ def load_model(self, model_path: str, config: Optional[DiffusionConfig] = None):
162
+ from diffusers import StableDiffusionPipeline
163
+ with st.spinner(f"Loading diffusion model {model_path}... ⏳"):
164
+ self.pipeline = StableDiffusionPipeline.from_pretrained(model_path)
165
+ self.pipeline.to("cuda" if torch.cuda.is_available() else "cpu")
166
+ if config:
167
+ self.config = config
168
+ st.success(f"Diffusion model loaded! 🎨")
169
+ return self
170
+ def fine_tune_sft(self, images, texts, epochs=3):
171
+ dataset = DiffusionDataset(images, texts)
172
+ dataloader = DataLoader(dataset, batch_size=1, shuffle=True)
173
+ optimizer = torch.optim.AdamW(self.pipeline.unet.parameters(), lr=1e-5)
174
+ self.pipeline.unet.train()
175
+ for epoch in range(epochs):
176
+ with st.spinner(f"Training diffusion epoch {epoch + 1}/{epochs}... ⚙️"):
177
+ total_loss = 0
178
+ for batch in dataloader:
179
+ optimizer.zero_grad()
180
+ image = batch["image"].to(self.pipeline.device)
181
+ text = batch["text"]
182
+ latents = self.pipeline.vae.encode(image).latent_dist.sample()
183
+ noise = torch.randn_like(latents)
184
+ timesteps = torch.randint(0, self.pipeline.scheduler.num_train_timesteps, (latents.shape[0],), device=latents.device)
185
+ noisy_latents = self.pipeline.scheduler.add_noise(latents, noise, timesteps)
186
+ text_embeddings = self.pipeline.text_encoder(self.pipeline.tokenizer(text, return_tensors="pt").input_ids.to(self.pipeline.device))[0]
187
+ pred_noise = self.pipeline.unet(noisy_latents, timesteps, encoder_hidden_states=text_embeddings).sample
188
+ loss = torch.nn.functional.mse_loss(pred_noise, noise)
189
+ loss.backward()
190
+ optimizer.step()
191
+ total_loss += loss.item()
192
+ st.write(f"Epoch {epoch + 1} completed. Average loss: {total_loss / len(dataloader):.4f}")
193
+ st.success("Diffusion SFT Fine-tuning completed! 🎨")
194
+ return self
195
+ def save_model(self, path: str):
196
+ with st.spinner("Saving diffusion model... 💾"):
197
+ os.makedirs(os.path.dirname(path), exist_ok=True)
198
+ self.pipeline.save_pretrained(path)
199
+ st.success(f"Diffusion model saved at {path}! ✅")
200
+ def generate(self, prompt: str):
201
+ return self.pipeline(prompt, num_inference_steps=50).images[0]
202
+
203
+ # Utility Functions
204
+ def get_download_link(file_path, mime_type="text/plain", label="Download"):
205
+ with open(file_path, 'rb') as f:
206
+ data = f.read()
207
+ b64 = base64.b64encode(data).decode()
208
+ return f'<a href="data:{mime_type};base64,{b64}" download="{os.path.basename(file_path)}">{label} 📥</a>'
209
+
210
+ def zip_directory(directory_path, zip_path):
211
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
212
+ for root, _, files in os.walk(directory_path):
213
+ for file in files:
214
+ zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.dirname(directory_path)))
215
+
216
+ def get_model_files(model_type="causal_lm"):
217
+ path = "models/*" if model_type == "causal_lm" else "diffusion_models/*"
218
+ return [d for d in glob.glob(path) if os.path.isdir(d)]
219
+
220
+ def get_gallery_files(file_types):
221
+ return sorted([f for ext in file_types for f in glob.glob(f"*.{ext}")])
222
+
223
+ def mock_search(query: str) -> str:
224
+ if "superhero" in query.lower():
225
+ return "Latest trends for 2025: Gold-plated Batman statues, VR superhero battles."
226
+ return "No relevant results found."
227
+
228
+ class PartyPlannerAgent:
229
+ def __init__(self, model, tokenizer):
230
+ self.model = model
231
+ self.tokenizer = tokenizer
232
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
233
+ self.model.to(self.device)
234
+ def generate(self, prompt: str) -> str:
235
+ self.model.eval()
236
+ with torch.no_grad():
237
+ inputs = self.tokenizer(prompt, return_tensors="pt", max_length=128, truncation=True).to(self.device)
238
+ outputs = self.model.generate(**inputs, max_new_tokens=100, do_sample=True, top_p=0.95, temperature=0.7)
239
+ return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
240
+ def plan_party(self, task: str) -> pd.DataFrame:
241
+ search_result = mock_search("superhero party trends")
242
+ prompt = f"Given this context: '{search_result}'\n{task}"
243
+ plan_text = self.generate(prompt)
244
+ locations = {"Wayne Manor": (42.3601, -71.0589), "New York": (40.7128, -74.0060)}
245
+ wayne_coords = locations["Wayne Manor"]
246
+ travel_times = {loc: calculate_cargo_travel_time(coords, wayne_coords) for loc, coords in locations.items() if loc != "Wayne Manor"}
247
+ data = [
248
+ {"Location": "New York", "Travel Time (hrs)": travel_times["New York"], "Luxury Idea": "Gold-plated Batman statues"},
249
+ {"Location": "Wayne Manor", "Travel Time (hrs)": 0.0, "Luxury Idea": "VR superhero battles"}
250
+ ]
251
+ return pd.DataFrame(data)
252
+
253
+ class CVPartyPlannerAgent:
254
+ def __init__(self, pipeline):
255
+ self.pipeline = pipeline
256
+ def generate(self, prompt: str) -> Image.Image:
257
+ return self.pipeline(prompt, num_inference_steps=50).images[0]
258
+ def plan_party(self, task: str) -> pd.DataFrame:
259
+ search_result = mock_search("superhero party trends")
260
+ prompt = f"Given this context: '{search_result}'\n{task}"
261
+ data = [
262
+ {"Theme": "Batman", "Image Idea": "Gold-plated Batman statue"},
263
+ {"Theme": "Avengers", "Image Idea": "VR superhero battle scene"}
264
+ ]
265
+ return pd.DataFrame(data)
266
+
267
+ def calculate_cargo_travel_time(origin_coords: Tuple[float, float], destination_coords: Tuple[float, float], cruising_speed_kmh: float = 750.0) -> float:
268
+ def to_radians(degrees: float) -> float:
269
+ return degrees * (math.pi / 180)
270
+ lat1, lon1 = map(to_radians, origin_coords)
271
+ lat2, lon2 = map(to_radians, destination_coords)
272
+ EARTH_RADIUS_KM = 6371.0
273
+ dlon = lon2 - lon1
274
+ dlat = lat2 - lat1
275
+ a = (math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2)
276
+ c = 2 * math.asin(math.sqrt(a))
277
+ distance = EARTH_RADIUS_KM * c
278
+ actual_distance = distance * 1.1
279
+ flight_time = (actual_distance / cruising_speed_kmh) + 1.0
280
+ return round(flight_time, 2)
281
+
282
+ # Main App
283
+ st.title("SFT Tiny Titans 🚀 (Small but Mighty!)")
284
+
285
+ # Sidebar Galleries
286
+ st.sidebar.header("Media Gallery 🎨")
287
+ gallery_size = st.sidebar.slider("Gallery Size", 1, 10, 4)
288
+ media_files = get_gallery_files(["png"])
289
+ if media_files:
290
+ cols = st.sidebar.columns(2)
291
+ for idx, file in enumerate(media_files[:gallery_size * 2]):
292
+ with cols[idx % 2]:
293
+ st.image(Image.open(file), caption=file, use_column_width=True)
294
+
295
+ st.sidebar.subheader("Model Management 🗂️")
296
+ model_type = st.sidebar.selectbox("Model Type", ["Causal LM", "Diffusion"])
297
+ model_dirs = get_model_files("causal_lm" if model_type == "Causal LM" else "diffusion")
298
+ selected_model = st.sidebar.selectbox("Select Saved Model", ["None"] + model_dirs)
299
+ if selected_model != "None" and st.sidebar.button("Load Model 📂"):
300
+ builder = ModelBuilder() if model_type == "Causal LM" else DiffusionBuilder()
301
+ config = (ModelConfig if model_type == "Causal LM" else DiffusionConfig)(name=os.path.basename(selected_model), base_model="unknown", size="small")
302
+ builder.load_model(selected_model, config)
303
+ st.session_state['builder'] = builder
304
+ st.session_state['model_loaded'] = True
305
+ st.rerun()
306
+
307
+ # Tabs
308
+ tab1, tab2, tab3, tab4, tab5 = st.tabs(["Build Titan 🌱", "Camera Snap 📷", "Fine-Tune Titan 🔧", "Test Titan 🧪", "Agentic RAG Party 🌐"])
309
+
310
+ with tab1:
311
+ st.header("Build Titan 🌱")
312
+ model_type = st.selectbox("Model Type", ["Causal LM", "Diffusion"], key="build_type")
313
+ base_model = st.selectbox("Select Tiny Model",
314
+ ["HuggingFaceTB/SmolLM-135M", "Qwen/Qwen1.5-0.5B-Chat"] if model_type == "Causal LM" else
315
+ ["stabilityai/stable-diffusion-2-base", "runwayml/stable-diffusion-v1-5"])
316
+ model_name = st.text_input("Model Name", f"tiny-titan-{int(time.time())}")
317
+ if st.button("Download Model ⬇️"):
318
+ config = (ModelConfig if model_type == "Causal LM" else DiffusionConfig)(name=model_name, base_model=base_model, size="small")
319
+ builder = ModelBuilder() if model_type == "Causal LM" else DiffusionBuilder()
320
+ builder.load_model(base_model, config)
321
+ builder.save_model(config.model_path)
322
+ st.session_state['builder'] = builder
323
+ st.session_state['model_loaded'] = True
324
+ st.rerun()
325
+
326
+ with tab2:
327
+ st.header("Camera Snap 📷 (Dual Capture!)")
328
+ slice_count = st.number_input("Image Slice Count", min_value=1, max_value=20, value=10)
329
+ video_length = st.number_input("Video Length (seconds)", min_value=1, max_value=30, value=10)
330
+ cols = st.columns(2)
331
+ with cols[0]:
332
+ st.subheader("Camera 0")
333
+ cam0_img = st.camera_input("Take a picture - Cam 0", key="cam0")
334
+ if cam0_img:
335
+ filename = generate_filename(0)
336
+ with open(filename, "wb") as f:
337
+ f.write(cam0_img.getvalue())
338
+ st.image(Image.open(filename), caption=filename, use_column_width=True)
339
+ logger.info(f"Saved snapshot from Camera 0: {filename}")
340
+ if 'captured_images' not in st.session_state:
341
+ st.session_state['captured_images'] = []
342
+ st.session_state['captured_images'].append(filename)
343
+ update_gallery()
344
+ if st.button(f"Capture {slice_count} Frames - Cam 0 📸"):
345
+ st.session_state['cam0_frames'] = []
346
+ for i in range(slice_count):
347
+ img = st.camera_input(f"Frame {i} - Cam 0", key=f"cam0_frame_{i}_{time.time()}")
348
+ if img:
349
+ filename = generate_filename(f"0_{i}")
350
+ with open(filename, "wb") as f:
351
+ f.write(img.getvalue())
352
+ st.session_state['cam0_frames'].append(filename)
353
+ logger.info(f"Saved frame {i} from Camera 0: {filename}")
354
+ time.sleep(1.0 / slice_count) # Adjust frame rate
355
+ st.session_state['captured_images'].extend(st.session_state['cam0_frames'])
356
+ update_gallery()
357
+ for frame in st.session_state['cam0_frames']:
358
+ st.image(Image.open(frame), caption=frame, use_column_width=True)
359
+ with cols[1]:
360
+ st.subheader("Camera 1")
361
+ cam1_img = st.camera_input("Take a picture - Cam 1", key="cam1")
362
+ if cam1_img:
363
+ filename = generate_filename(1)
364
+ with open(filename, "wb") as f:
365
+ f.write(cam1_img.getvalue())
366
+ st.image(Image.open(filename), caption=filename, use_column_width=True)
367
+ logger.info(f"Saved snapshot from Camera 1: {filename}")
368
+ if 'captured_images' not in st.session_state:
369
+ st.session_state['captured_images'] = []
370
+ st.session_state['captured_images'].append(filename)
371
+ update_gallery()
372
+ if st.button(f"Capture {slice_count} Frames - Cam 1 📸"):
373
+ st.session_state['cam1_frames'] = []
374
+ for i in range(slice_count):
375
+ img = st.camera_input(f"Frame {i} - Cam 1", key=f"cam1_frame_{i}_{time.time()}")
376
+ if img:
377
+ filename = generate_filename(f"1_{i}")
378
+ with open(filename, "wb") as f:
379
+ f.write(img.getvalue())
380
+ st.session_state['cam1_frames'].append(filename)
381
+ logger.info(f"Saved frame {i} from Camera 1: {filename}")
382
+ time.sleep(1.0 / slice_count) # Adjust frame rate
383
+ st.session_state['captured_images'].extend(st.session_state['cam1_frames'])
384
+ update_gallery()
385
+ for frame in st.session_state['cam1_frames']:
386
+ st.image(Image.open(frame), caption=frame, use_column_width=True)
387
+
388
+ with tab3:
389
+ st.header("Fine-Tune Titan 🔧")
390
+ if 'builder' not in st.session_state or not st.session_state.get('model_loaded', False):
391
+ st.warning("Please build or load a Titan first! ⚠️")
392
+ else:
393
+ if isinstance(st.session_state['builder'], ModelBuilder):
394
+ uploaded_csv = st.file_uploader("Upload CSV for SFT", type="csv")
395
+ if uploaded_csv and st.button("Fine-Tune with Uploaded CSV 🔄"):
396
+ csv_path = f"uploaded_sft_data_{int(time.time())}.csv"
397
+ with open(csv_path, "wb") as f:
398
+ f.write(uploaded_csv.read())
399
+ new_model_name = f"{st.session_state['builder'].config.name}-sft-{int(time.time())}"
400
+ new_config = ModelConfig(name=new_model_name, base_model=st.session_state['builder'].config.base_model, size="small")
401
+ st.session_state['builder'].config = new_config
402
+ st.session_state['builder'].fine_tune_sft(csv_path)
403
+ st.session_state['builder'].save_model(new_config.model_path)
404
+ zip_path = f"{new_config.model_path}.zip"
405
+ zip_directory(new_config.model_path, zip_path)
406
+ st.markdown(get_download_link(zip_path, "application/zip", "Download Fine-Tuned Titan"), unsafe_allow_html=True)
407
+ elif isinstance(st.session_state['builder'], DiffusionBuilder):
408
+ captured_images = get_gallery_files(["png"])
409
+ if len(captured_images) >= 2:
410
+ demo_data = [{"image": img, "text": f"Superhero {os.path.basename(img).split('.')[0]}"} for img in captured_images[:min(len(captured_images), slice_count)]]
411
+ edited_data = st.data_editor(pd.DataFrame(demo_data), num_rows="dynamic")
412
+ if st.button("Fine-Tune with Dataset 🔄"):
413
+ images = [Image.open(row["image"]) for _, row in edited_data.iterrows()]
414
+ texts = [row["text"] for _, row in edited_data.iterrows()]
415
+ new_model_name = f"{st.session_state['builder'].config.name}-sft-{int(time.time())}"
416
+ new_config = DiffusionConfig(name=new_model_name, base_model=st.session_state['builder'].config.base_model, size="small")
417
+ st.session_state['builder'].config = new_config
418
+ st.session_state['builder'].fine_tune_sft(images, texts)
419
+ st.session_state['builder'].save_model(new_config.model_path)
420
+ zip_path = f"{new_config.model_path}.zip"
421
+ zip_directory(new_config.model_path, zip_path)
422
+ st.markdown(get_download_link(zip_path, "application/zip", "Download Fine-Tuned Diffusion Model"), unsafe_allow_html=True)
423
+
424
+ with tab4:
425
+ st.header("Test Titan 🧪")
426
+ if 'builder' not in st.session_state or not st.session_state.get('model_loaded', False):
427
+ st.warning("Please build or load a Titan first! ⚠️")
428
+ else:
429
+ if isinstance(st.session_state['builder'], ModelBuilder):
430
+ test_prompt = st.text_area("Enter Test Prompt", "What is AI?")
431
+ if st.button("Run Test ▶️"):
432
+ result = st.session_state['builder'].evaluate(test_prompt)
433
+ st.write(f"**Generated Response**: {result}")
434
+ elif isinstance(st.session_state['builder'], DiffusionBuilder):
435
+ test_prompt = st.text_area("Enter Test Prompt", "Neon Batman")
436
+ if st.button("Run Test ▶️"):
437
+ image = st.session_state['builder'].generate(test_prompt)
438
+ st.image(image, caption="Generated Image")
439
+
440
+ with tab5:
441
+ st.header("Agentic RAG Party 🌐")
442
+ if 'builder' not in st.session_state or not st.session_state.get('model_loaded', False):
443
+ st.warning("Please build or load a Titan first! ⚠️")
444
+ else:
445
+ if isinstance(st.session_state['builder'], ModelBuilder):
446
+ if st.button("Run NLP RAG Demo 🎉"):
447
+ agent = PartyPlannerAgent(st.session_state['builder'].model, st.session_state['builder'].tokenizer)
448
+ task = "Plan a luxury superhero-themed party at Wayne Manor."
449
+ plan_df = agent.plan_party(task)
450
+ st.dataframe(plan_df)
451
+ elif isinstance(st.session_state['builder'], DiffusionBuilder):
452
+ if st.button("Run CV RAG Demo 🎉"):
453
+ agent = CVPartyPlannerAgent(st.session_state['builder'].pipeline)
454
+ task = "Generate images for a luxury superhero-themed party."
455
+ plan_df = agent.plan_party(task)
456
+ st.dataframe(plan_df)
457
+ for _, row in plan_df.iterrows():
458
+ image = agent.generate(row["Image Idea"])
459
+ st.image(image, caption=f"{row['Theme']} - {row['Image Idea']}")