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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
import os
|
3 |
+
import glob
|
4 |
+
import base64
|
5 |
+
import time
|
6 |
+
import shutil
|
7 |
+
import streamlit as st
|
8 |
+
import pandas as pd
|
9 |
+
import torch
|
10 |
+
import torch.nn as nn
|
11 |
+
import torch.nn.functional as F
|
12 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, AutoModel, AutoProcessor, Qwen2VLForConditionalGeneration, TrOCRProcessor, VisionEncoderDecoderModel
|
13 |
+
from diffusers import StableDiffusionPipeline
|
14 |
+
from torch.utils.data import Dataset, DataLoader
|
15 |
+
import csv
|
16 |
+
import fitz # PyMuPDF
|
17 |
+
import requests
|
18 |
+
from PIL import Image
|
19 |
+
import cv2
|
20 |
+
import numpy as np
|
21 |
+
import logging
|
22 |
+
import asyncio
|
23 |
+
import aiofiles
|
24 |
+
from io import BytesIO
|
25 |
+
from dataclasses import dataclass
|
26 |
+
from typing import Optional, Tuple
|
27 |
+
import zipfile
|
28 |
+
import math
|
29 |
+
import random
|
30 |
+
import re
|
31 |
+
from datetime import datetime
|
32 |
+
import pytz
|
33 |
+
|
34 |
+
# Logging setup with custom buffer
|
35 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
36 |
+
logger = logging.getLogger(__name__)
|
37 |
+
log_records = []
|
38 |
+
|
39 |
+
class LogCaptureHandler(logging.Handler):
|
40 |
+
def emit(self, record):
|
41 |
+
log_records.append(record)
|
42 |
+
|
43 |
+
logger.addHandler(LogCaptureHandler())
|
44 |
+
|
45 |
+
# Page Configuration
|
46 |
+
st.set_page_config(
|
47 |
+
page_title="AI Vision & SFT Titans 🚀",
|
48 |
+
page_icon="🤖",
|
49 |
+
layout="wide",
|
50 |
+
initial_sidebar_state="expanded",
|
51 |
+
menu_items={
|
52 |
+
'Get Help': 'https://huggingface.co/awacke1',
|
53 |
+
'Report a Bug': 'https://huggingface.co/spaces/awacke1',
|
54 |
+
'About': "AI Vision & SFT Titans: PDFs, OCR, Image Gen, Line Drawings, Custom Diffusion, and SFT on CPU! 🌌"
|
55 |
+
}
|
56 |
+
)
|
57 |
+
|
58 |
+
# Initialize st.session_state
|
59 |
+
if 'history' not in st.session_state:
|
60 |
+
st.session_state['history'] = [] # Flat list for history
|
61 |
+
if 'builder' not in st.session_state:
|
62 |
+
st.session_state['builder'] = None
|
63 |
+
if 'model_loaded' not in st.session_state:
|
64 |
+
st.session_state['model_loaded'] = False
|
65 |
+
if 'processing' not in st.session_state:
|
66 |
+
st.session_state['processing'] = {}
|
67 |
+
if 'pdf_checkboxes' not in st.session_state:
|
68 |
+
st.session_state['pdf_checkboxes'] = {}
|
69 |
+
if 'downloaded_pdfs' not in st.session_state:
|
70 |
+
st.session_state['downloaded_pdfs'] = {}
|
71 |
+
if 'captured_images' not in st.session_state:
|
72 |
+
st.session_state['captured_images'] = []
|
73 |
+
|
74 |
+
# Model Configuration Classes
|
75 |
+
@dataclass
|
76 |
+
class ModelConfig:
|
77 |
+
name: str
|
78 |
+
base_model: str
|
79 |
+
size: str
|
80 |
+
domain: Optional[str] = None
|
81 |
+
model_type: str = "causal_lm"
|
82 |
+
@property
|
83 |
+
def model_path(self):
|
84 |
+
return f"models/{self.name}"
|
85 |
+
|
86 |
+
@dataclass
|
87 |
+
class DiffusionConfig:
|
88 |
+
name: str
|
89 |
+
base_model: str
|
90 |
+
size: str
|
91 |
+
domain: Optional[str] = None # Fixed to include domain
|
92 |
+
@property
|
93 |
+
def model_path(self):
|
94 |
+
return f"diffusion_models/{self.name}"
|
95 |
+
|
96 |
+
# Datasets
|
97 |
+
class SFTDataset(Dataset):
|
98 |
+
def __init__(self, data, tokenizer, max_length=128):
|
99 |
+
self.data = data
|
100 |
+
self.tokenizer = tokenizer
|
101 |
+
self.max_length = max_length
|
102 |
+
def __len__(self):
|
103 |
+
return len(self.data)
|
104 |
+
def __getitem__(self, idx):
|
105 |
+
prompt = self.data[idx]["prompt"]
|
106 |
+
response = self.data[idx]["response"]
|
107 |
+
full_text = f"{prompt} {response}"
|
108 |
+
full_encoding = self.tokenizer(full_text, max_length=self.max_length, padding="max_length", truncation=True, return_tensors="pt")
|
109 |
+
prompt_encoding = self.tokenizer(prompt, max_length=self.max_length, padding=False, truncation=True, return_tensors="pt")
|
110 |
+
input_ids = full_encoding["input_ids"].squeeze()
|
111 |
+
attention_mask = full_encoding["attention_mask"].squeeze()
|
112 |
+
labels = input_ids.clone()
|
113 |
+
prompt_len = prompt_encoding["input_ids"].shape[1]
|
114 |
+
if prompt_len < self.max_length:
|
115 |
+
labels[:prompt_len] = -100
|
116 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask, "labels": labels}
|
117 |
+
|
118 |
+
class DiffusionDataset(Dataset):
|
119 |
+
def __init__(self, images, texts):
|
120 |
+
self.images = images
|
121 |
+
self.texts = texts
|
122 |
+
def __len__(self):
|
123 |
+
return len(self.images)
|
124 |
+
def __getitem__(self, idx):
|
125 |
+
return {"image": self.images[idx], "text": self.texts[idx]}
|
126 |
+
|
127 |
+
class TinyDiffusionDataset(Dataset):
|
128 |
+
def __init__(self, images):
|
129 |
+
self.images = [torch.tensor(np.array(img.convert("RGB")).transpose(2, 0, 1), dtype=torch.float32) / 255.0 for img in images]
|
130 |
+
def __len__(self):
|
131 |
+
return len(self.images)
|
132 |
+
def __getitem__(self, idx):
|
133 |
+
return self.images[idx]
|
134 |
+
|
135 |
+
# Custom Tiny Diffusion Model
|
136 |
+
class TinyUNet(nn.Module):
|
137 |
+
def __init__(self, in_channels=3, out_channels=3):
|
138 |
+
super(TinyUNet, self).__init__()
|
139 |
+
self.down1 = nn.Conv2d(in_channels, 32, 3, padding=1)
|
140 |
+
self.down2 = nn.Conv2d(32, 64, 3, padding=1, stride=2)
|
141 |
+
self.mid = nn.Conv2d(64, 128, 3, padding=1)
|
142 |
+
self.up1 = nn.ConvTranspose2d(128, 64, 3, stride=2, padding=1, output_padding=1)
|
143 |
+
self.up2 = nn.Conv2d(64 + 32, 32, 3, padding=1)
|
144 |
+
self.out = nn.Conv2d(32, out_channels, 3, padding=1)
|
145 |
+
self.time_embed = nn.Linear(1, 64)
|
146 |
+
|
147 |
+
def forward(self, x, t):
|
148 |
+
t_embed = F.relu(self.time_embed(t.unsqueeze(-1)))
|
149 |
+
t_embed = t_embed.view(t_embed.size(0), t_embed.size(1), 1, 1)
|
150 |
+
|
151 |
+
x1 = F.relu(self.down1(x))
|
152 |
+
x2 = F.relu(self.down2(x1))
|
153 |
+
x_mid = F.relu(self.mid(x2)) + t_embed
|
154 |
+
x_up1 = F.relu(self.up1(x_mid))
|
155 |
+
x_up2 = F.relu(self.up2(torch.cat([x_up1, x1], dim=1)))
|
156 |
+
return self.out(x_up2)
|
157 |
+
|
158 |
+
class TinyDiffusion:
|
159 |
+
def __init__(self, model, timesteps=100):
|
160 |
+
self.model = model
|
161 |
+
self.timesteps = timesteps
|
162 |
+
self.beta = torch.linspace(0.0001, 0.02, timesteps)
|
163 |
+
self.alpha = 1 - self.beta
|
164 |
+
self.alpha_cumprod = torch.cumprod(self.alpha, dim=0)
|
165 |
+
|
166 |
+
def train(self, images, epochs=50):
|
167 |
+
dataset = TinyDiffusionDataset(images)
|
168 |
+
dataloader = DataLoader(dataset, batch_size=1, shuffle=True)
|
169 |
+
optimizer = torch.optim.Adam(self.model.parameters(), lr=1e-4)
|
170 |
+
device = torch.device("cpu")
|
171 |
+
self.model.to(device)
|
172 |
+
for epoch in range(epochs):
|
173 |
+
total_loss = 0
|
174 |
+
for x in dataloader:
|
175 |
+
x = x.to(device)
|
176 |
+
t = torch.randint(0, self.timesteps, (x.size(0),), device=device).float()
|
177 |
+
noise = torch.randn_like(x)
|
178 |
+
alpha_t = self.alpha_cumprod[t.long()].view(-1, 1, 1, 1)
|
179 |
+
x_noisy = torch.sqrt(alpha_t) * x + torch.sqrt(1 - alpha_t) * noise
|
180 |
+
pred_noise = self.model(x_noisy, t)
|
181 |
+
loss = F.mse_loss(pred_noise, noise)
|
182 |
+
optimizer.zero_grad()
|
183 |
+
loss.backward()
|
184 |
+
optimizer.step()
|
185 |
+
total_loss += loss.item()
|
186 |
+
logger.info(f"Epoch {epoch + 1}/{epochs}, Loss: {total_loss / len(dataloader):.4f}")
|
187 |
+
return self
|
188 |
+
|
189 |
+
def generate(self, size=(64, 64), steps=100):
|
190 |
+
device = torch.device("cpu")
|
191 |
+
x = torch.randn(1, 3, size[0], size[1], device=device)
|
192 |
+
for t in reversed(range(steps)):
|
193 |
+
t_tensor = torch.full((1,), t, device=device, dtype=torch.float32)
|
194 |
+
alpha_t = self.alpha_cumprod[t].view(-1, 1, 1, 1)
|
195 |
+
pred_noise = self.model(x, t_tensor)
|
196 |
+
x = (x - (1 - self.alpha[t]) / torch.sqrt(1 - alpha_t) * pred_noise) / torch.sqrt(self.alpha[t])
|
197 |
+
if t > 0:
|
198 |
+
x += torch.sqrt(self.beta[t]) * torch.randn_like(x)
|
199 |
+
x = torch.clamp(x * 255, 0, 255).byte()
|
200 |
+
return Image.fromarray(x.squeeze(0).permute(1, 2, 0).cpu().numpy())
|
201 |
+
|
202 |
+
def upscale(self, image, scale_factor=2):
|
203 |
+
img_tensor = torch.tensor(np.array(image.convert("RGB")).transpose(2, 0, 1), dtype=torch.float32).unsqueeze(0) / 255.0
|
204 |
+
upscaled = F.interpolate(img_tensor, scale_factor=scale_factor, mode='bilinear', align_corners=False)
|
205 |
+
upscaled = torch.clamp(upscaled * 255, 0, 255).byte()
|
206 |
+
return Image.fromarray(upscaled.squeeze(0).permute(1, 2, 0).cpu().numpy())
|
207 |
+
|
208 |
+
# Model Builders
|
209 |
+
class ModelBuilder:
|
210 |
+
def __init__(self):
|
211 |
+
self.config = None
|
212 |
+
self.model = None
|
213 |
+
self.tokenizer = None
|
214 |
+
self.sft_data = None
|
215 |
+
self.jokes = ["Why did the AI go to therapy? Too many layers to unpack! 😂", "Training complete! Time for a binary coffee break. ☕"]
|
216 |
+
def load_model(self, model_path: str, config: Optional[ModelConfig] = None):
|
217 |
+
with st.spinner(f"Loading {model_path}... ⏳"):
|
218 |
+
self.model = AutoModelForCausalLM.from_pretrained(model_path)
|
219 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_path)
|
220 |
+
if self.tokenizer.pad_token is None:
|
221 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
222 |
+
if config:
|
223 |
+
self.config = config
|
224 |
+
self.model.to("cuda" if torch.cuda.is_available() else "cpu")
|
225 |
+
st.success(f"Model loaded! 🎉 {random.choice(self.jokes)}")
|
226 |
+
return self
|
227 |
+
def fine_tune_sft(self, csv_path: str, epochs: int = 3, batch_size: int = 4):
|
228 |
+
self.sft_data = []
|
229 |
+
with open(csv_path, "r") as f:
|
230 |
+
reader = csv.DictReader(f)
|
231 |
+
for row in reader:
|
232 |
+
self.sft_data.append({"prompt": row["prompt"], "response": row["response"]})
|
233 |
+
dataset = SFTDataset(self.sft_data, self.tokenizer)
|
234 |
+
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
|
235 |
+
optimizer = torch.optim.AdamW(self.model.parameters(), lr=2e-5)
|
236 |
+
self.model.train()
|
237 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
238 |
+
self.model.to(device)
|
239 |
+
for epoch in range(epochs):
|
240 |
+
with st.spinner(f"Training epoch {epoch + 1}/{epochs}... ⚙️"):
|
241 |
+
total_loss = 0
|
242 |
+
for batch in dataloader:
|
243 |
+
optimizer.zero_grad()
|
244 |
+
input_ids = batch["input_ids"].to(device)
|
245 |
+
attention_mask = batch["attention_mask"].to(device)
|
246 |
+
labels = batch["labels"].to(device)
|
247 |
+
outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
|
248 |
+
loss = outputs.loss
|
249 |
+
loss.backward()
|
250 |
+
optimizer.step()
|
251 |
+
total_loss += loss.item()
|
252 |
+
st.write(f"Epoch {epoch + 1} completed. Average loss: {total_loss / len(dataloader):.4f}")
|
253 |
+
st.success(f"SFT Fine-tuning completed! 🎉 {random.choice(self.jokes)}")
|
254 |
+
return self
|
255 |
+
def save_model(self, path: str):
|
256 |
+
with st.spinner("Saving model... 💾"):
|
257 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
258 |
+
self.model.save_pretrained(path)
|
259 |
+
self.tokenizer.save_pretrained(path)
|
260 |
+
st.success(f"Model saved at {path}! ✅")
|
261 |
+
def evaluate(self, prompt: str, status_container=None):
|
262 |
+
self.model.eval()
|
263 |
+
if status_container:
|
264 |
+
status_container.write("Preparing to evaluate... 🧠")
|
265 |
+
try:
|
266 |
+
with torch.no_grad():
|
267 |
+
inputs = self.tokenizer(prompt, return_tensors="pt", max_length=128, truncation=True).to(self.model.device)
|
268 |
+
outputs = self.model.generate(**inputs, max_new_tokens=50, do_sample=True, top_p=0.95, temperature=0.7)
|
269 |
+
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
270 |
+
except Exception as e:
|
271 |
+
if status_container:
|
272 |
+
status_container.error(f"Oops! Something broke: {str(e)} 💥")
|
273 |
+
return f"Error: {str(e)}"
|
274 |
+
|
275 |
+
class DiffusionBuilder:
|
276 |
+
def __init__(self):
|
277 |
+
self.config = None
|
278 |
+
self.pipeline = None
|
279 |
+
def load_model(self, model_path: str, config: Optional[DiffusionConfig] = None):
|
280 |
+
with st.spinner(f"Loading diffusion model {model_path}... ⏳"):
|
281 |
+
self.pipeline = StableDiffusionPipeline.from_pretrained(model_path, torch_dtype=torch.float32).to("cpu")
|
282 |
+
if config:
|
283 |
+
self.config = config
|
284 |
+
st.success(f"Diffusion model loaded! 🎨")
|
285 |
+
return self
|
286 |
+
def fine_tune_sft(self, images, texts, epochs=3):
|
287 |
+
dataset = DiffusionDataset(images, texts)
|
288 |
+
dataloader = DataLoader(dataset, batch_size=1, shuffle=True)
|
289 |
+
optimizer = torch.optim.AdamW(self.pipeline.unet.parameters(), lr=1e-5)
|
290 |
+
self.pipeline.unet.train()
|
291 |
+
for epoch in range(epochs):
|
292 |
+
with st.spinner(f"Training diffusion epoch {epoch + 1}/{epochs}... ⚙️"):
|
293 |
+
total_loss = 0
|
294 |
+
for batch in dataloader:
|
295 |
+
optimizer.zero_grad()
|
296 |
+
image = batch["image"][0].to(self.pipeline.device)
|
297 |
+
text = batch["text"][0]
|
298 |
+
latents = self.pipeline.vae.encode(torch.tensor(np.array(image)).permute(2, 0, 1).unsqueeze(0).float().to(self.pipeline.device)).latent_dist.sample()
|
299 |
+
noise = torch.randn_like(latents)
|
300 |
+
timesteps = torch.randint(0, self.pipeline.scheduler.num_train_timesteps, (latents.shape[0],), device=latents.device)
|
301 |
+
noisy_latents = self.pipeline.scheduler.add_noise(latents, noise, timesteps)
|
302 |
+
text_embeddings = self.pipeline.text_encoder(self.pipeline.tokenizer(text, return_tensors="pt").input_ids.to(self.pipeline.device))[0]
|
303 |
+
pred_noise = self.pipeline.unet(noisy_latents, timesteps, encoder_hidden_states=text_embeddings).sample
|
304 |
+
loss = torch.nn.functional.mse_loss(pred_noise, noise)
|
305 |
+
loss.backward()
|
306 |
+
optimizer.step()
|
307 |
+
total_loss += loss.item()
|
308 |
+
st.write(f"Epoch {epoch + 1} completed. Average loss: {total_loss / len(dataloader):.4f}")
|
309 |
+
st.success("Diffusion SFT Fine-tuning completed! 🎨")
|
310 |
+
return self
|
311 |
+
def save_model(self, path: str):
|
312 |
+
with st.spinner("Saving diffusion model... 💾"):
|
313 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
314 |
+
self.pipeline.save_pretrained(path)
|
315 |
+
st.success(f"Diffusion model saved at {path}! ✅")
|
316 |
+
def generate(self, prompt: str):
|
317 |
+
return self.pipeline(prompt, num_inference_steps=20).images[0]
|
318 |
+
|
319 |
+
# Utility Functions
|
320 |
+
def generate_filename(sequence, ext="png"):
|
321 |
+
central = pytz.timezone('US/Central')
|
322 |
+
timestamp = datetime.now(central).strftime("%d%m%Y%H%M%S%p")
|
323 |
+
return f"{sequence}_{timestamp}.{ext}"
|
324 |
+
|
325 |
+
def pdf_url_to_filename(url):
|
326 |
+
safe_name = re.sub(r'[<>:"/\\|?*]', '_', url)
|
327 |
+
return f"{safe_name}.pdf"
|
328 |
+
|
329 |
+
def get_download_link(file_path, mime_type="application/pdf", label="Download"):
|
330 |
+
with open(file_path, 'rb') as f:
|
331 |
+
data = f.read()
|
332 |
+
b64 = base64.b64encode(data).decode()
|
333 |
+
return f'<a href="data:{mime_type};base64,{b64}" download="{os.path.basename(file_path)}">{label}</a>'
|
334 |
+
|
335 |
+
def zip_directory(directory_path, zip_path):
|
336 |
+
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
337 |
+
for root, _, files in os.walk(directory_path):
|
338 |
+
for file in files:
|
339 |
+
zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.dirname(directory_path)))
|
340 |
+
|
341 |
+
def get_model_files(model_type="causal_lm"):
|
342 |
+
path = "models/*" if model_type == "causal_lm" else "diffusion_models/*"
|
343 |
+
return [d for d in glob.glob(path) if os.path.isdir(d)]
|
344 |
+
|
345 |
+
def get_gallery_files(file_types=["png", "txt"]):
|
346 |
+
return sorted([f for ext in file_types for f in glob.glob(f"*.{ext}")])
|
347 |
+
|
348 |
+
def get_pdf_files():
|
349 |
+
return sorted(glob.glob("*.pdf"))
|
350 |
+
|
351 |
+
def download_pdf(url, output_path):
|
352 |
+
try:
|
353 |
+
response = requests.get(url, stream=True, timeout=10)
|
354 |
+
if response.status_code == 200:
|
355 |
+
with open(output_path, "wb") as f:
|
356 |
+
for chunk in response.iter_content(chunk_size=8192):
|
357 |
+
f.write(chunk)
|
358 |
+
return True
|
359 |
+
except requests.RequestException as e:
|
360 |
+
logger.error(f"Failed to download {url}: {e}")
|
361 |
+
return False
|
362 |
+
|
363 |
+
# Model Loaders for New App Features
|
364 |
+
def load_ocr_qwen2vl():
|
365 |
+
model_id = "prithivMLmods/Qwen2-VL-OCR-2B-Instruct"
|
366 |
+
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
|
367 |
+
model = Qwen2VLForConditionalGeneration.from_pretrained(model_id, trust_remote_code=True, torch_dtype=torch.float32).to("cpu").eval()
|
368 |
+
return processor, model
|
369 |
+
|
370 |
+
def load_ocr_trocr():
|
371 |
+
model_id = "microsoft/trocr-small-handwritten"
|
372 |
+
processor = TrOCRProcessor.from_pretrained(model_id)
|
373 |
+
model = VisionEncoderDecoderModel.from_pretrained(model_id, torch_dtype=torch.float32).to("cpu").eval()
|
374 |
+
return processor, model
|
375 |
+
|
376 |
+
def load_image_gen():
|
377 |
+
model_id = "OFA-Sys/small-stable-diffusion-v0"
|
378 |
+
pipeline = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float32).to("cpu")
|
379 |
+
return pipeline
|
380 |
+
|
381 |
+
def load_line_drawer():
|
382 |
+
def edge_detection(image):
|
383 |
+
img_np = np.array(image.convert("RGB"))
|
384 |
+
gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
|
385 |
+
edges = cv2.Canny(gray, 100, 200)
|
386 |
+
return Image.fromarray(edges)
|
387 |
+
return edge_detection
|
388 |
+
|
389 |
+
# Async Processing Functions
|
390 |
+
async def process_pdf_snapshot(pdf_path, mode="single"):
|
391 |
+
start_time = time.time()
|
392 |
+
status = st.empty()
|
393 |
+
status.text(f"Processing PDF Snapshot ({mode})... (0s)")
|
394 |
+
try:
|
395 |
+
doc = fitz.open(pdf_path)
|
396 |
+
output_files = []
|
397 |
+
if mode == "single":
|
398 |
+
page = doc[0]
|
399 |
+
pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
|
400 |
+
output_file = generate_filename("single", "png")
|
401 |
+
pix.save(output_file)
|
402 |
+
output_files.append(output_file)
|
403 |
+
elif mode == "twopage":
|
404 |
+
for i in range(min(2, len(doc))):
|
405 |
+
page = doc[i]
|
406 |
+
pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
|
407 |
+
output_file = generate_filename(f"twopage_{i}", "png")
|
408 |
+
pix.save(output_file)
|
409 |
+
output_files.append(output_file)
|
410 |
+
elif mode == "allthumbs":
|
411 |
+
for i in range(len(doc)):
|
412 |
+
page = doc[i]
|
413 |
+
pix = page.get_pixmap(matrix=fitz.Matrix(0.5, 0.5))
|
414 |
+
output_file = generate_filename(f"thumb_{i}", "png")
|
415 |
+
pix.save(output_file)
|
416 |
+
output_files.append(output_file)
|
417 |
+
doc.close()
|
418 |
+
elapsed = int(time.time() - start_time)
|
419 |
+
status.text(f"PDF Snapshot ({mode}) completed in {elapsed}s!")
|
420 |
+
update_gallery()
|
421 |
+
return output_files
|
422 |
+
except Exception as e:
|
423 |
+
status.error(f"Failed to process PDF: {str(e)}")
|
424 |
+
return []
|
425 |
+
|
426 |
+
async def process_ocr(image, prompt, model_name, output_file):
|
427 |
+
start_time = time.time()
|
428 |
+
status = st.empty()
|
429 |
+
status.text(f"Processing {model_name} OCR... (0s)")
|
430 |
+
if model_name == "Qwen2-VL-OCR-2B":
|
431 |
+
processor, model = load_ocr_qwen2vl()
|
432 |
+
messages = [{"role": "user", "content": [{"type": "image", "image": image}, {"type": "text", "text": prompt}]}]
|
433 |
+
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
434 |
+
inputs = processor(text=[text], images=[image], return_tensors="pt", padding=True).to("cpu")
|
435 |
+
outputs = model.generate(**inputs, max_new_tokens=1024)
|
436 |
+
result = processor.batch_decode(outputs, skip_special_tokens=True)[0]
|
437 |
+
elif model_name == "TrOCR-Small":
|
438 |
+
processor, model = load_ocr_trocr()
|
439 |
+
pixel_values = processor(images=image, return_tensors="pt").pixel_values.to("cpu")
|
440 |
+
outputs = model.generate(pixel_values)
|
441 |
+
result = processor.batch_decode(outputs, skip_special_tokens=True)[0]
|
442 |
+
else: # GOT-OCR2_0 (original from Backup 6)
|
443 |
+
tokenizer = AutoTokenizer.from_pretrained("ucaslcl/GOT-OCR2_0", trust_remote_code=True)
|
444 |
+
model = AutoModel.from_pretrained("ucaslcl/GOT-OCR2_0", trust_remote_code=True, torch_dtype=torch.float32).to("cpu").eval()
|
445 |
+
result = model.chat(tokenizer, image, ocr_type='ocr')
|
446 |
+
elapsed = int(time.time() - start_time)
|
447 |
+
status.text(f"{model_name} OCR completed in {elapsed}s!")
|
448 |
+
async with aiofiles.open(output_file, "w") as f:
|
449 |
+
await f.write(result)
|
450 |
+
st.session_state['captured_images'].append(output_file)
|
451 |
+
update_gallery()
|
452 |
+
return result
|
453 |
+
|
454 |
+
async def process_image_gen(prompt, output_file):
|
455 |
+
start_time = time.time()
|
456 |
+
status = st.empty()
|
457 |
+
status.text("Processing Image Gen... (0s)")
|
458 |
+
pipeline = load_image_gen()
|
459 |
+
gen_image = pipeline(prompt, num_inference_steps=20).images[0]
|
460 |
+
elapsed = int(time.time() - start_time)
|
461 |
+
status.text(f"Image Gen completed in {elapsed}s!")
|
462 |
+
gen_image.save(output_file)
|
463 |
+
st.session_state['captured_images'].append(output_file)
|
464 |
+
update_gallery()
|
465 |
+
return gen_image
|
466 |
+
|
467 |
+
async def process_line_drawing(image, output_file):
|
468 |
+
start_time = time.time()
|
469 |
+
status = st.empty()
|
470 |
+
status.text("Processing Line Drawing... (0s)")
|
471 |
+
edge_fn = load_line_drawer()
|
472 |
+
line_drawing = edge_fn(image)
|
473 |
+
elapsed = int(time.time() - start_time)
|
474 |
+
status.text(f"Line Drawing completed in {elapsed}s!")
|
475 |
+
line_drawing.save(output_file)
|
476 |
+
st.session_state['captured_images'].append(output_file)
|
477 |
+
update_gallery()
|
478 |
+
return line_drawing
|
479 |
+
|
480 |
+
# Mock Search Tool for RAG
|
481 |
+
def mock_search(query: str) -> str:
|
482 |
+
if "superhero" in query.lower():
|
483 |
+
return "Latest trends: Gold-plated Batman statues, VR superhero battles."
|
484 |
+
return "No relevant results found."
|
485 |
+
|
486 |
+
def mock_duckduckgo_search(query: str) -> str:
|
487 |
+
if "superhero party trends" in query.lower():
|
488 |
+
return """
|
489 |
+
Latest trends for 2025:
|
490 |
+
- Luxury decorations: Gold-plated Batman statues, holographic Avengers displays.
|
491 |
+
- Entertainment: Live stunt shows with Iron Man suits, VR superhero battles.
|
492 |
+
- Catering: Gourmet kryptonite-green cocktails, Thor’s hammer-shaped appetizers.
|
493 |
+
"""
|
494 |
+
return "No relevant results found."
|
495 |
+
|
496 |
+
# Agent Classes
|
497 |
+
class PartyPlannerAgent:
|
498 |
+
def __init__(self, model, tokenizer):
|
499 |
+
self.model = model
|
500 |
+
self.tokenizer = tokenizer
|
501 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
502 |
+
self.model.to(self.device)
|
503 |
+
def generate(self, prompt: str) -> str:
|
504 |
+
self.model.eval()
|
505 |
+
with torch.no_grad():
|
506 |
+
inputs = self.tokenizer(prompt, return_tensors="pt", max_length=128, truncation=True).to(self.device)
|
507 |
+
outputs = self.model.generate(**inputs, max_new_tokens=100, do_sample=True, top_p=0.95, temperature=0.7)
|
508 |
+
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
509 |
+
def plan_party(self, task: str) -> pd.DataFrame:
|
510 |
+
search_result = mock_duckduckgo_search("latest superhero party trends")
|
511 |
+
prompt = f"Given this context: '{search_result}'\n{task}"
|
512 |
+
plan_text = self.generate(prompt)
|
513 |
+
locations = {
|
514 |
+
"Wayne Manor": (42.3601, -71.0589),
|
515 |
+
"New York": (40.7128, -74.0060),
|
516 |
+
"Los Angeles": (34.0522, -118.2437),
|
517 |
+
"London": (51.5074, -0.1278)
|
518 |
+
}
|
519 |
+
wayne_coords = locations["Wayne Manor"]
|
520 |
+
travel_times = {loc: calculate_cargo_travel_time(coords, wayne_coords) for loc, coords in locations.items() if loc != "Wayne Manor"}
|
521 |
+
catchphrases = ["To the Batmobile!", "Avengers, assemble!", "I am Iron Man!", "By the power of Grayskull!"]
|
522 |
+
data = [
|
523 |
+
{"Location": "New York", "Travel Time (hrs)": travel_times["New York"], "Luxury Idea": "Gold-plated Batman statues", "Catchphrase": random.choice(catchphrases)},
|
524 |
+
{"Location": "Los Angeles", "Travel Time (hrs)": travel_times["Los Angeles"], "Luxury Idea": "Holographic Avengers displays", "Catchphrase": random.choice(catchphrases)},
|
525 |
+
{"Location": "London", "Travel Time (hrs)": travel_times["London"], "Luxury Idea": "Live stunt shows with Iron Man suits", "Catchphrase": random.choice(catchphrases)},
|
526 |
+
{"Location": "Wayne Manor", "Travel Time (hrs)": 0.0, "Luxury Idea": "VR superhero battles", "Catchphrase": random.choice(catchphrases)},
|
527 |
+
{"Location": "New York", "Travel Time (hrs)": travel_times["New York"], "Luxury Idea": "Gourmet kryptonite-green cocktails", "Catchphrase": random.choice(catchphrases)},
|
528 |
+
{"Location": "Los Angeles", "Travel Time (hrs)": travel_times["Los Angeles"], "Luxury Idea": "Thor’s hammer-shaped appetizers", "Catchphrase": random.choice(catchphrases)},
|
529 |
+
]
|
530 |
+
return pd.DataFrame(data)
|
531 |
+
|
532 |
+
class CVPartyPlannerAgent:
|
533 |
+
def __init__(self, pipeline):
|
534 |
+
self.pipeline = pipeline
|
535 |
+
def generate(self, prompt: str) -> Image.Image:
|
536 |
+
return self.pipeline(prompt, num_inference_steps=20).images[0]
|
537 |
+
def plan_party(self, task: str) -> pd.DataFrame:
|
538 |
+
search_result = mock_search("superhero party trends")
|
539 |
+
prompt = f"Given this context: '{search_result}'\n{task}"
|
540 |
+
data = [
|
541 |
+
{"Theme": "Batman", "Image Idea": "Gold-plated Batman statue"},
|
542 |
+
{"Theme": "Avengers", "Image Idea": "VR superhero battle scene"}
|
543 |
+
]
|
544 |
+
return pd.DataFrame(data)
|
545 |
+
|
546 |
+
def calculate_cargo_travel_time(origin_coords: Tuple[float, float], destination_coords: Tuple[float, float], cruising_speed_kmh: float = 750.0) -> float:
|
547 |
+
def to_radians(degrees: float) -> float:
|
548 |
+
return degrees * (math.pi / 180)
|
549 |
+
lat1, lon1 = map(to_radians, origin_coords)
|
550 |
+
lat2, lon2 = map(to_radians, destination_coords)
|
551 |
+
EARTH_RADIUS_KM = 6371.0
|
552 |
+
dlon = lon2 - lon1
|
553 |
+
dlat = lat2 - lat1
|
554 |
+
a = (math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2)
|
555 |
+
c = 2 * math.asin(math.sqrt(a))
|
556 |
+
distance = EARTH_RADIUS_KM * c
|
557 |
+
actual_distance = distance * 1.1
|
558 |
+
flight_time = (actual_distance / cruising_speed_kmh) + 1.0
|
559 |
+
return round(flight_time, 2)
|
560 |
+
|
561 |
+
# Main App
|
562 |
+
st.title("AI Vision & SFT Titans 🚀")
|
563 |
+
|
564 |
+
# Sidebar
|
565 |
+
st.sidebar.header("Captured Files 📜")
|
566 |
+
gallery_size = st.sidebar.slider("Gallery Size", 1, 10, 2)
|
567 |
+
def update_gallery():
|
568 |
+
media_files = get_gallery_files(["png", "txt"])
|
569 |
+
pdf_files = get_pdf_files()
|
570 |
+
if media_files or pdf_files:
|
571 |
+
st.sidebar.subheader("Images & Text 📸")
|
572 |
+
cols = st.sidebar.columns(2)
|
573 |
+
for idx, file in enumerate(media_files[:gallery_size * 2]):
|
574 |
+
with cols[idx % 2]:
|
575 |
+
if file.endswith(".png"):
|
576 |
+
st.image(Image.open(file), caption=os.path.basename(file), use_container_width=True)
|
577 |
+
elif file.endswith(".txt"):
|
578 |
+
with open(file, "r") as f:
|
579 |
+
content = f.read()
|
580 |
+
st.text(content[:50] + "..." if len(content) > 50 else content, help=file)
|
581 |
+
st.sidebar.subheader("PDF Downloads 📖")
|
582 |
+
for pdf_file in pdf_files[:gallery_size * 2]:
|
583 |
+
st.markdown(get_download_link(pdf_file, "application/pdf", f"📥 Grab {os.path.basename(pdf_file)}"), unsafe_allow_html=True)
|
584 |
+
update_gallery()
|
585 |
+
|
586 |
+
st.sidebar.subheader("Model Management 🗂️")
|
587 |
+
model_type = st.sidebar.selectbox("Model Type", ["Causal LM", "Diffusion"], key="sidebar_model_type")
|
588 |
+
model_dirs = get_model_files(model_type)
|
589 |
+
selected_model = st.sidebar.selectbox("Select Saved Model", ["None"] + model_dirs, key="sidebar_model_select")
|
590 |
+
if selected_model != "None" and st.sidebar.button("Load Model 📂"):
|
591 |
+
builder = ModelBuilder() if model_type == "Causal LM" else DiffusionBuilder()
|
592 |
+
config = (ModelConfig if model_type == "Causal LM" else DiffusionConfig)(name=os.path.basename(selected_model), base_model="unknown", size="small")
|
593 |
+
builder.load_model(selected_model, config)
|
594 |
+
st.session_state['builder'] = builder
|
595 |
+
st.session_state['model_loaded'] = True
|
596 |
+
st.rerun()
|
597 |
+
|
598 |
+
st.sidebar.subheader("Action Logs 📜")
|
599 |
+
log_container = st.sidebar.empty()
|
600 |
+
with log_container:
|
601 |
+
for record in log_records:
|
602 |
+
st.write(f"{record.asctime} - {record.levelname} - {record.message}")
|
603 |
+
|
604 |
+
st.sidebar.subheader("History 📜")
|
605 |
+
history_container = st.sidebar.empty()
|
606 |
+
with history_container:
|
607 |
+
for entry in st.session_state['history'][-gallery_size * 2:]:
|
608 |
+
st.write(entry)
|
609 |
+
|
610 |
+
# Tabs
|
611 |
+
tab1, tab2, tab3, tab4, tab5, tab6, tab7, tab8, tab9, tab10 = st.tabs([
|
612 |
+
"Camera Snap 📷", "Download PDFs 📥", "Build Titan 🌱", "Fine-Tune Titan 🔧",
|
613 |
+
"Test Titan 🧪", "Agentic RAG Party 🌐", "Test OCR 🔍", "Test Image Gen 🎨",
|
614 |
+
"Test Line Drawings ✏️", "Custom Diffusion 🎨🤓"
|
615 |
+
])
|
616 |
+
|
617 |
+
with tab1:
|
618 |
+
st.header("Camera Snap 📷")
|
619 |
+
st.subheader("Single Capture")
|
620 |
+
cols = st.columns(2)
|
621 |
+
with cols[0]:
|
622 |
+
cam0_img = st.camera_input("Take a picture - Cam 0", key="cam0")
|
623 |
+
if cam0_img:
|
624 |
+
filename = generate_filename("cam0")
|
625 |
+
if filename not in st.session_state['captured_images']:
|
626 |
+
with open(filename, "wb") as f:
|
627 |
+
f.write(cam0_img.getvalue())
|
628 |
+
st.image(Image.open(filename), caption="Camera 0", use_container_width=True)
|
629 |
+
logger.info(f"Saved snapshot from Camera 0: {filename}")
|
630 |
+
st.session_state['captured_images'].append(filename)
|
631 |
+
update_gallery()
|
632 |
+
with cols[1]:
|
633 |
+
cam1_img = st.camera_input("Take a picture - Cam 1", key="cam1")
|
634 |
+
if cam1_img:
|
635 |
+
filename = generate_filename("cam1")
|
636 |
+
if filename not in st.session_state['captured_images']:
|
637 |
+
with open(filename, "wb") as f:
|
638 |
+
f.write(cam1_img.getvalue())
|
639 |
+
st.image(Image.open(filename), caption="Camera 1", use_container_width=True)
|
640 |
+
logger.info(f"Saved snapshot from Camera 1: {filename}")
|
641 |
+
st.session_state['captured_images'].append(filename)
|
642 |
+
update_gallery()
|
643 |
+
|
644 |
+
st.subheader("Burst Capture")
|
645 |
+
slice_count = st.number_input("Number of Frames", min_value=1, max_value=20, value=10, key="burst_count")
|
646 |
+
if st.button("Start Burst Capture 📸"):
|
647 |
+
st.session_state['burst_frames'] = []
|
648 |
+
placeholder = st.empty()
|
649 |
+
for i in range(slice_count):
|
650 |
+
with placeholder.container():
|
651 |
+
st.write(f"Capturing frame {i+1}/{slice_count}...")
|
652 |
+
img = st.camera_input(f"Frame {i}", key=f"burst_{i}_{time.time()}")
|
653 |
+
if img:
|
654 |
+
filename = generate_filename(f"burst_{i}")
|
655 |
+
if filename not in st.session_state['captured_images']:
|
656 |
+
with open(filename, "wb") as f:
|
657 |
+
f.write(img.getvalue())
|
658 |
+
st.session_state['burst_frames'].append(filename)
|
659 |
+
logger.info(f"Saved burst frame {i}: {filename}")
|
660 |
+
st.image(Image.open(filename), caption=filename, use_container_width=True)
|
661 |
+
time.sleep(0.5)
|
662 |
+
st.session_state['captured_images'].extend([f for f in st.session_state['burst_frames'] if f not in st.session_state['captured_images']])
|
663 |
+
update_gallery()
|
664 |
+
placeholder.success(f"Captured {len(st.session_state['burst_frames'])} frames!")
|
665 |
+
|
666 |
+
with tab2:
|
667 |
+
st.header("Download PDFs 📥")
|
668 |
+
if st.button("Examples 📚"):
|
669 |
+
example_urls = [
|
670 |
+
"https://arxiv.org/pdf/2308.03892", "https://arxiv.org/pdf/1912.01703", "https://arxiv.org/pdf/2408.11039",
|
671 |
+
"https://arxiv.org/pdf/2109.10282", "https://arxiv.org/pdf/2112.10752", "https://arxiv.org/pdf/2308.11236",
|
672 |
+
"https://arxiv.org/pdf/1706.03762", "https://arxiv.org/pdf/2006.11239", "https://arxiv.org/pdf/2305.11207",
|
673 |
+
"https://arxiv.org/pdf/2106.09685", "https://arxiv.org/pdf/2005.11401", "https://arxiv.org/pdf/2106.10504"
|
674 |
+
]
|
675 |
+
st.session_state['pdf_urls'] = "\n".join(example_urls)
|
676 |
+
|
677 |
+
url_input = st.text_area("Enter PDF URLs (one per line)", value=st.session_state.get('pdf_urls', ""), height=200)
|
678 |
+
if st.button("Robo-Download 🤖"):
|
679 |
+
urls = url_input.strip().split("\n")
|
680 |
+
progress_bar = st.progress(0)
|
681 |
+
status_text = st.empty()
|
682 |
+
total_urls = len(urls)
|
683 |
+
existing_pdfs = get_pdf_files()
|
684 |
+
for idx, url in enumerate(urls):
|
685 |
+
if url:
|
686 |
+
output_path = pdf_url_to_filename(url)
|
687 |
+
status_text.text(f"Fetching {idx + 1}/{total_urls}: {os.path.basename(output_path)}...")
|
688 |
+
if output_path not in existing_pdfs:
|
689 |
+
if download_pdf(url, output_path):
|
690 |
+
st.session_state['downloaded_pdfs'][url] = output_path
|
691 |
+
logger.info(f"Downloaded PDF from {url} to {output_path}")
|
692 |
+
entry = f"Downloaded PDF: {output_path}"
|
693 |
+
if entry not in st.session_state['history']:
|
694 |
+
st.session_state['history'].append(entry)
|
695 |
+
else:
|
696 |
+
st.error(f"Failed to nab {url} 😿")
|
697 |
+
else:
|
698 |
+
st.info(f"Already got {os.path.basename(output_path)}! Skipping... 🐾")
|
699 |
+
st.session_state['downloaded_pdfs'][url] = output_path
|
700 |
+
progress_bar.progress((idx + 1) / total_urls)
|
701 |
+
status_text.text("Robo-Download complete! 🚀")
|
702 |
+
update_gallery()
|
703 |
+
|
704 |
+
st.subheader("PDF Gallery 📖")
|
705 |
+
downloaded_pdfs = list(st.session_state['downloaded_pdfs'].values())
|
706 |
+
if downloaded_pdfs:
|
707 |
+
cols_per_row = 3
|
708 |
+
for i in range(0, len(downloaded_pdfs), cols_per_row):
|
709 |
+
cols = st.columns(cols_per_row)
|
710 |
+
for j, pdf_path in enumerate(downloaded_pdfs[i:i + cols_per_row]):
|
711 |
+
with cols[j]:
|
712 |
+
doc = fitz.open(pdf_path)
|
713 |
+
page = doc[0]
|
714 |
+
pix = page.get_pixmap(matrix=fitz.Matrix(0.5, 0.5))
|
715 |
+
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
716 |
+
st.image(img, caption=os.path.basename(pdf_path), use_container_width=True)
|
717 |
+
checkbox_key = f"pdf_{pdf_path}"
|
718 |
+
st.session_state['pdf_checkboxes'][checkbox_key] = st.checkbox(
|
719 |
+
"Use for SFT/Input", value=st.session_state['pdf_checkboxes'].get(checkbox_key, False), key=checkbox_key
|
720 |
+
)
|
721 |
+
st.markdown(get_download_link(pdf_path, "application/pdf", "Snag It! 📥"), unsafe_allow_html=True)
|
722 |
+
if st.button("Zap It! 🗑️", key=f"delete_{pdf_path}"):
|
723 |
+
os.remove(pdf_path)
|
724 |
+
url_key = next((k for k, v in st.session_state['downloaded_pdfs'].items() if v == pdf_path), None)
|
725 |
+
if url_key:
|
726 |
+
del st.session_state['downloaded_pdfs'][url_key]
|
727 |
+
del st.session_state['pdf_checkboxes'][checkbox_key]
|
728 |
+
st.success(f"PDF {os.path.basename(pdf_path)} vaporized! 💨")
|
729 |
+
st.rerun()
|
730 |
+
doc.close()
|
731 |
+
else:
|
732 |
+
st.info("No PDFs captured yet. Feed the robo-downloader some URLs! 🤖")
|
733 |
+
|
734 |
+
mode = st.selectbox("Snapshot Mode", ["Single Page (High-Res)", "Two Pages (High-Res)", "All Pages (Thumbnails)"], key="download_mode")
|
735 |
+
if st.button("Snapshot Selected 📸"):
|
736 |
+
selected_pdfs = [path for key, path in st.session_state['downloaded_pdfs'].items() if st.session_state['pdf_checkboxes'].get(f"pdf_{path}", False)]
|
737 |
+
if selected_pdfs:
|
738 |
+
for pdf_path in selected_pdfs:
|
739 |
+
mode_key = {"Single Page (High-Res)": "single", "Two Pages (High-Res)": "twopage", "All Pages (Thumbnails)": "allthumbs"}[mode]
|
740 |
+
snapshots = asyncio.run(process_pdf_snapshot(pdf_path, mode_key))
|
741 |
+
for snapshot in snapshots:
|
742 |
+
st.image(Image.open(snapshot), caption=snapshot, use_container_width=True)
|
743 |
+
else:
|
744 |
+
st.warning("No PDFs selected for snapshotting! Check some boxes first. 📝")
|
745 |
+
|
746 |
+
with tab3:
|
747 |
+
st.header("Build Titan 🌱")
|
748 |
+
model_type = st.selectbox("Model Type", ["Causal LM", "Diffusion"], key="build_type")
|
749 |
+
base_model = st.selectbox("Select Tiny Model",
|
750 |
+
["HuggingFaceTB/SmolLM-135M", "Qwen/Qwen1.5-0.5B-Chat"] if model_type == "Causal LM" else
|
751 |
+
["OFA-Sys/small-stable-diffusion-v0", "stabilityai/stable-diffusion-2-base"])
|
752 |
+
model_name = st.text_input("Model Name", f"tiny-titan-{int(time.time())}")
|
753 |
+
domain = st.text_input("Target Domain", "general")
|
754 |
+
if st.button("Download Model ⬇️"):
|
755 |
+
config = (ModelConfig if model_type == "Causal LM" else DiffusionConfig)(name=model_name, base_model=base_model, size="small", domain=domain)
|
756 |
+
builder = ModelBuilder() if model_type == "Causal LM" else DiffusionBuilder()
|
757 |
+
builder.load_model(base_model, config)
|
758 |
+
builder.save_model(config.model_path)
|
759 |
+
st.session_state['builder'] = builder
|
760 |
+
st.session_state['model_loaded'] = True
|
761 |
+
entry = f"Built {model_type} model: {model_name}"
|
762 |
+
if entry not in st.session_state['history']:
|
763 |
+
st.session_state['history'].append(entry)
|
764 |
+
st.success(f"Model downloaded and saved to {config.model_path}! 🎉")
|
765 |
+
st.rerun()
|
766 |
+
|
767 |
+
with tab4:
|
768 |
+
st.header("Fine-Tune Titan 🔧")
|
769 |
+
if 'builder' not in st.session_state or not st.session_state.get('model_loaded', False):
|
770 |
+
st.warning("Please build or load a Titan first! ⚠️")
|
771 |
+
else:
|
772 |
+
if isinstance(st.session_state['builder'], ModelBuilder):
|
773 |
+
if st.button("Generate Sample CSV 📝"):
|
774 |
+
sample_data = [
|
775 |
+
{"prompt": "What is AI?", "response": "AI is artificial intelligence, simulating human smarts in machines."},
|
776 |
+
{"prompt": "Explain machine learning", "response": "Machine learning is AI’s gym where models bulk up on data."},
|
777 |
+
]
|
778 |
+
csv_path = f"sft_data_{int(time.time())}.csv"
|
779 |
+
with open(csv_path, "w", newline="") as f:
|
780 |
+
writer = csv.DictWriter(f, fieldnames=["prompt", "response"])
|
781 |
+
writer.writeheader()
|
782 |
+
writer.writerows(sample_data)
|
783 |
+
st.markdown(get_download_link(csv_path, "text/csv", "Download Sample CSV"), unsafe_allow_html=True)
|
784 |
+
st.success(f"Sample CSV generated as {csv_path}! ✅")
|
785 |
+
|
786 |
+
uploaded_csv = st.file_uploader("Upload CSV for SFT", type="csv")
|
787 |
+
if uploaded_csv and st.button("Fine-Tune with Uploaded CSV 🔄"):
|
788 |
+
csv_path = f"uploaded_sft_data_{int(time.time())}.csv"
|
789 |
+
with open(csv_path, "wb") as f:
|
790 |
+
f.write(uploaded_csv.read())
|
791 |
+
new_model_name = f"{st.session_state['builder'].config.name}-sft-{int(time.time())}"
|
792 |
+
new_config = ModelConfig(name=new_model_name, base_model=st.session_state['builder'].config.base_model, size="small", domain=st.session_state['builder'].config.domain)
|
793 |
+
st.session_state['builder'].config = new_config
|
794 |
+
st.session_state['builder'].fine_tune_sft(csv_path)
|
795 |
+
st.session_state['builder'].save_model(new_config.model_path)
|
796 |
+
zip_path = f"{new_config.model_path}.zip"
|
797 |
+
zip_directory(new_config.model_path, zip_path)
|
798 |
+
entry = f"Fine-tuned Causal LM: {new_model_name}"
|
799 |
+
if entry not in st.session_state['history']:
|
800 |
+
st.session_state['history'].append(entry)
|
801 |
+
st.markdown(get_download_link(zip_path, "application/zip", "Download Fine-Tuned Titan"), unsafe_allow_html=True)
|
802 |
+
st.rerun()
|
803 |
+
elif isinstance(st.session_state['builder'], DiffusionBuilder):
|
804 |
+
captured_files = get_gallery_files(["png"])
|
805 |
+
selected_pdfs = [path for key, path in st.session_state['downloaded_pdfs'].items() if st.session_state['pdf_checkboxes'].get(f"pdf_{path}", False)]
|
806 |
+
if len(captured_files) + len(selected_pdfs) >= 2:
|
807 |
+
demo_data = [{"image": img, "text": f"Superhero {os.path.basename(img).split('.')[0]}"} for img in captured_files]
|
808 |
+
for pdf_path in selected_pdfs:
|
809 |
+
demo_data.append({"image": pdf_path, "text": f"PDF {os.path.basename(pdf_path)}"})
|
810 |
+
edited_data = st.data_editor(pd.DataFrame(demo_data), num_rows="dynamic")
|
811 |
+
if st.button("Fine-Tune with Dataset 🔄"):
|
812 |
+
images = [Image.open(row["image"]) if row["image"].endswith('.png') else Image.frombytes("RGB", fitz.open(row["image"])[0].get_pixmap(matrix=fitz.Matrix(2.0, 2.0)).size, fitz.open(row["image"])[0].get_pixmap(matrix=fitz.Matrix(2.0, 2.0)).samples) for _, row in edited_data.iterrows()]
|
813 |
+
texts = [row["text"] for _, row in edited_data.iterrows()]
|
814 |
+
new_model_name = f"{st.session_state['builder'].config.name}-sft-{int(time.time())}"
|
815 |
+
new_config = DiffusionConfig(name=new_model_name, base_model=st.session_state['builder'].config.base_model, size="small", domain=st.session_state['builder'].config.domain)
|
816 |
+
st.session_state['builder'].config = new_config
|
817 |
+
st.session_state['builder'].fine_tune_sft(images, texts)
|
818 |
+
st.session_state['builder'].save_model(new_config.model_path)
|
819 |
+
zip_path = f"{new_config.model_path}.zip"
|
820 |
+
zip_directory(new_config.model_path, zip_path)
|
821 |
+
entry = f"Fine-tuned Diffusion: {new_model_name}"
|
822 |
+
if entry not in st.session_state['history']:
|
823 |
+
st.session_state['history'].append(entry)
|
824 |
+
st.markdown(get_download_link(zip_path, "application/zip", "Download Fine-Tuned Diffusion Model"), unsafe_allow_html=True)
|
825 |
+
csv_path = f"sft_dataset_{int(time.time())}.csv"
|
826 |
+
with open(csv_path, "w", newline="") as f:
|
827 |
+
writer = csv.writer(f)
|
828 |
+
writer.writerow(["image", "text"])
|
829 |
+
for _, row in edited_data.iterrows():
|
830 |
+
writer.writerow([row["image"], row["text"]])
|
831 |
+
st.markdown(get_download_link(csv_path, "text/csv", "Download SFT Dataset CSV"), unsafe_allow_html=True)
|
832 |
+
|
833 |
+
with tab5:
|
834 |
+
st.header("Test Titan 🧪")
|
835 |
+
if 'builder' not in st.session_state or not st.session_state.get('model_loaded', False):
|
836 |
+
st.warning("Please build or load a Titan first! ⚠️")
|
837 |
+
else:
|
838 |
+
if isinstance(st.session_state['builder'], ModelBuilder):
|
839 |
+
if st.session_state['builder'].sft_data:
|
840 |
+
st.write("Testing with SFT Data:")
|
841 |
+
for item in st.session_state['builder'].sft_data[:3]:
|
842 |
+
prompt = item["prompt"]
|
843 |
+
expected = item["response"]
|
844 |
+
status_container = st.empty()
|
845 |
+
generated = st.session_state['builder'].evaluate(prompt, status_container)
|
846 |
+
st.write(f"**Prompt**: {prompt}")
|
847 |
+
st.write(f"**Expected**: {expected}")
|
848 |
+
st.write(f"**Generated**: {generated}")
|
849 |
+
st.write("---")
|
850 |
+
status_container.empty()
|
851 |
+
test_prompt = st.text_area("Enter Test Prompt", "What is AI?")
|
852 |
+
if st.button("Run Test ▶️"):
|
853 |
+
status_container = st.empty()
|
854 |
+
result = st.session_state['builder'].evaluate(test_prompt, status_container)
|
855 |
+
entry = f"Causal LM Test: {test_prompt} -> {result}"
|
856 |
+
if entry not in st.session_state['history']:
|
857 |
+
st.session_state['history'].append(entry)
|
858 |
+
st.write(f"**Generated Response**: {result}")
|
859 |
+
status_container.empty()
|
860 |
+
elif isinstance(st.session_state['builder'], DiffusionBuilder):
|
861 |
+
test_prompt = st.text_area("Enter Test Prompt", "Neon Batman")
|
862 |
+
selected_pdfs = [path for key, path in st.session_state['downloaded_pdfs'].items() if st.session_state['pdf_checkboxes'].get(f"pdf_{path}", False)]
|
863 |
+
if st.button("Run Test ▶️"):
|
864 |
+
image = st.session_state['builder'].generate(test_prompt)
|
865 |
+
output_file = generate_filename("diffusion_test", "png")
|
866 |
+
image.save(output_file)
|
867 |
+
entry = f"Diffusion Test: {test_prompt} -> {output_file}"
|
868 |
+
if entry not in st.session_state['history']:
|
869 |
+
st.session_state['history'].append(entry)
|
870 |
+
st.image(image, caption="Generated Image")
|
871 |
+
update_gallery()
|
872 |
+
|
873 |
+
with tab6:
|
874 |
+
st.header("Agentic RAG Party 🌐")
|
875 |
+
if 'builder' not in st.session_state or not st.session_state.get('model_loaded', False):
|
876 |
+
st.warning("Please build or load a Titan first! ⚠️")
|
877 |
+
else:
|
878 |
+
if isinstance(st.session_state['builder'], ModelBuilder):
|
879 |
+
if st.button("Run NLP RAG Demo 🎉"):
|
880 |
+
agent = PartyPlannerAgent(st.session_state['builder'].model, st.session_state['builder'].tokenizer)
|
881 |
+
task = "Plan a luxury superhero-themed party at Wayne Manor."
|
882 |
+
plan_df = agent.plan_party(task)
|
883 |
+
entry = f"NLP RAG Demo: Planned party at Wayne Manor"
|
884 |
+
if entry not in st.session_state['history']:
|
885 |
+
st.session_state['history'].append(entry)
|
886 |
+
st.dataframe(plan_df)
|
887 |
+
elif isinstance(st.session_state['builder'], DiffusionBuilder):
|
888 |
+
if st.button("Run CV RAG Demo 🎉"):
|
889 |
+
agent = CVPartyPlannerAgent(st.session_state['builder'].pipeline)
|
890 |
+
task = "Generate images for a luxury superhero-themed party."
|
891 |
+
plan_df = agent.plan_party(task)
|
892 |
+
entry = f"CV RAG Demo: Generated party images"
|
893 |
+
if entry not in st.session_state['history']:
|
894 |
+
st.session_state['history'].append(entry)
|
895 |
+
st.dataframe(plan_df)
|
896 |
+
for _, row in plan_df.iterrows():
|
897 |
+
image = agent.generate(row["Image Idea"])
|
898 |
+
output_file = generate_filename(f"cv_rag_{row['Theme'].lower()}", "png")
|
899 |
+
image.save(output_file)
|
900 |
+
st.image(image, caption=f"{row['Theme']} - {row['Image Idea']}")
|
901 |
+
update_gallery()
|
902 |
+
|
903 |
+
with tab7:
|
904 |
+
st.header("Test OCR 🔍")
|
905 |
+
captured_files = get_gallery_files(["png"])
|
906 |
+
selected_pdfs = [path for key, path in st.session_state['downloaded_pdfs'].items() if st.session_state['pdf_checkboxes'].get(f"pdf_{path}", False)]
|
907 |
+
all_files = captured_files + selected_pdfs
|
908 |
+
if all_files:
|
909 |
+
selected_file = st.selectbox("Select Image or PDF", all_files, key="ocr_select")
|
910 |
+
if selected_file:
|
911 |
+
if selected_file.endswith('.png'):
|
912 |
+
image = Image.open(selected_file)
|
913 |
+
else:
|
914 |
+
doc = fitz.open(selected_file)
|
915 |
+
pix = doc[0].get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
|
916 |
+
image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
917 |
+
doc.close()
|
918 |
+
st.image(image, caption="Input Image", use_container_width=True)
|
919 |
+
ocr_model = st.selectbox("Select OCR Model", ["Qwen2-VL-OCR-2B", "TrOCR-Small", "GOT-OCR2_0"], key="ocr_model_select")
|
920 |
+
prompt = st.text_area("Prompt", "Extract text from the image", key="ocr_prompt")
|
921 |
+
if st.button("Run OCR 🚀", key="ocr_run"):
|
922 |
+
output_file = generate_filename("ocr_output", "txt")
|
923 |
+
st.session_state['processing']['ocr'] = True
|
924 |
+
result = asyncio.run(process_ocr(image, prompt, ocr_model, output_file))
|
925 |
+
st.text_area("OCR Result", result, height=200, key="ocr_result")
|
926 |
+
st.success(f"OCR output saved to {output_file}")
|
927 |
+
st.session_state['processing']['ocr'] = False
|
928 |
+
else:
|
929 |
+
st.warning("No images or PDFs captured yet. Use Camera Snap or Download PDFs first!")
|
930 |
+
|
931 |
+
with tab8:
|
932 |
+
st.header("Test Image Gen 🎨")
|
933 |
+
captured_files = get_gallery_files(["png"])
|
934 |
+
selected_pdfs = [path for key, path in st.session_state['downloaded_pdfs'].items() if st.session_state['pdf_checkboxes'].get(f"pdf_{path}", False)]
|
935 |
+
all_files = captured_files + selected_pdfs
|
936 |
+
if all_files:
|
937 |
+
selected_file = st.selectbox("Select Image or PDF", all_files, key="gen_select")
|
938 |
+
if selected_file:
|
939 |
+
if selected_file.endswith('.png'):
|
940 |
+
image = Image.open(selected_file)
|
941 |
+
else:
|
942 |
+
doc = fitz.open(selected_file)
|
943 |
+
pix = doc[0].get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
|
944 |
+
image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
945 |
+
doc.close()
|
946 |
+
st.image(image, caption="Reference Image", use_container_width=True)
|
947 |
+
prompt = st.text_area("Prompt", "Generate a similar superhero image", key="gen_prompt")
|
948 |
+
if st.button("Run Image Gen 🚀", key="gen_run"):
|
949 |
+
output_file = generate_filename("gen_output", "png")
|
950 |
+
st.session_state['processing']['gen'] = True
|
951 |
+
result = asyncio.run(process_image_gen(prompt, output_file))
|
952 |
+
st.image(result, caption="Generated Image", use_container_width=True)
|
953 |
+
st.success(f"Image saved to {output_file}")
|
954 |
+
st.session_state['processing']['gen'] = False
|
955 |
+
else:
|
956 |
+
st.warning("No images or PDFs captured yet. Use Camera Snap or Download PDFs first!")
|
957 |
+
|
958 |
+
with tab9:
|
959 |
+
st.header("Test Line Drawings ✏️")
|
960 |
+
captured_files = get_gallery_files(["png"])
|
961 |
+
selected_pdfs = [path for key, path in st.session_state['downloaded_pdfs'].items() if st.session_state['pdf_checkboxes'].get(f"pdf_{path}", False)]
|
962 |
+
all_files = captured_files + selected_pdfs
|
963 |
+
if all_files:
|
964 |
+
selected_file = st.selectbox("Select Image or PDF", all_files, key="line_select")
|
965 |
+
if selected_file:
|
966 |
+
if selected_file.endswith('.png'):
|
967 |
+
image = Image.open(selected_file)
|
968 |
+
else:
|
969 |
+
doc = fitz.open(selected_file)
|
970 |
+
pix = doc[0].get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
|
971 |
+
image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
972 |
+
doc.close()
|
973 |
+
st.image(image, caption="Input Image", use_container_width=True)
|
974 |
+
if st.button("Run Line Drawing 🚀", key="line_run"):
|
975 |
+
output_file = generate_filename("line_output", "png")
|
976 |
+
st.session_state['processing']['line'] = True
|
977 |
+
result = asyncio.run(process_line_drawing(image, output_file))
|
978 |
+
st.image(result, caption="Line Drawing", use_container_width=True)
|
979 |
+
st.success(f"Line drawing saved to {output_file}")
|
980 |
+
st.session_state['processing']['line'] = False
|
981 |
+
else:
|
982 |
+
st.warning("No images or PDFs captured yet. Use Camera Snap or Download PDFs first!")
|
983 |
+
|
984 |
+
with tab10:
|
985 |
+
st.header("Custom Diffusion 🎨🤓")
|
986 |
+
st.write("Unleash your inner artist with our tiny diffusion models!")
|
987 |
+
captured_files = get_gallery_files(["png"])
|
988 |
+
selected_pdfs = [path for key, path in st.session_state['downloaded_pdfs'].items() if st.session_state['pdf_checkboxes'].get(f"pdf_{path}", False)]
|
989 |
+
all_files = captured_files + selected_pdfs
|
990 |
+
if all_files:
|
991 |
+
st.subheader("Select Images or PDFs to Train")
|
992 |
+
selected_files = st.multiselect("Pick Images or PDFs", all_files, key="diffusion_select")
|
993 |
+
images = []
|
994 |
+
for file in selected_files:
|
995 |
+
if file.endswith('.png'):
|
996 |
+
images.append(Image.open(file))
|
997 |
+
else:
|
998 |
+
doc = fitz.open(file)
|
999 |
+
pix = doc[0].get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
|
1000 |
+
images.append(Image.frombytes("RGB", [pix.width, pix.height], pix.samples))
|
1001 |
+
doc.close()
|
1002 |
+
|
1003 |
+
model_options = [
|
1004 |
+
("PixelTickler 🎨✨", "OFA-Sys/small-stable-diffusion-v0"),
|
1005 |
+
("DreamWeaver 🌙🖌️", "stabilityai/stable-diffusion-2-base"),
|
1006 |
+
("TinyArtBot 🤖🖼️", "custom")
|
1007 |
+
]
|
1008 |
+
model_choice = st.selectbox("Choose Your Diffusion Dynamo", [opt[0] for opt in model_options], key="diffusion_model")
|
1009 |
+
model_name = next(opt[1] for opt in model_options if opt[0] == model_choice)
|
1010 |
+
|
1011 |
+
if st.button("Train & Generate 🚀", key="diffusion_run"):
|
1012 |
+
output_file = generate_filename("custom_diffusion", "png")
|
1013 |
+
st.session_state['processing']['diffusion'] = True
|
1014 |
+
if model_name == "custom":
|
1015 |
+
result = asyncio.run(process_custom_diffusion(images, output_file, model_choice))
|
1016 |
+
else:
|
1017 |
+
builder = DiffusionBuilder()
|
1018 |
+
builder.load_model(model_name)
|
1019 |
+
result = builder.generate("A superhero scene inspired by captured images")
|
1020 |
+
result.save(output_file)
|
1021 |
+
entry = f"Custom Diffusion: {model_choice} -> {output_file}"
|
1022 |
+
if entry not in st.session_state['history']:
|
1023 |
+
st.session_state['history'].append(entry)
|
1024 |
+
st.image(result, caption=f"{model_choice} Masterpiece", use_container_width=True)
|
1025 |
+
st.success(f"Image saved to {output_file}")
|
1026 |
+
st.session_state['processing']['diffusion'] = False
|
1027 |
+
else:
|
1028 |
+
st.warning("No images or PDFs captured yet. Use Camera Snap or Download PDFs first!")
|
1029 |
+
|
1030 |
+
# Initial Gallery Update
|
1031 |
+
update_gallery()
|