awacke1 commited on
Commit
c9b3642
·
verified ·
1 Parent(s): 76f7e5e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +786 -0
app.py ADDED
@@ -0,0 +1,786 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import aiofiles
2
+ import asyncio
3
+ import base64
4
+ import fitz
5
+ import glob
6
+ import logging
7
+ import os
8
+ import pandas as pd
9
+ import pytz
10
+ import random
11
+ import re
12
+ import requests
13
+ import shutil
14
+ import streamlit as st
15
+ import time
16
+ import torch
17
+ import zipfile
18
+ import json
19
+
20
+ from dataclasses import dataclass
21
+ from datetime import datetime
22
+ from diffusers import StableDiffusionPipeline
23
+ from io import BytesIO
24
+ from openai import OpenAI
25
+ from PIL import Image
26
+ from transformers import AutoModelForCausalLM, AutoTokenizer, AutoModel
27
+ from typing import Optional
28
+
29
+ # OpenAI client initialization
30
+ client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'), organization=os.getenv('OPENAI_ORG_ID'))
31
+
32
+ # Logging setup
33
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
34
+ logger = logging.getLogger(__name__)
35
+ log_records = []
36
+ class LogCaptureHandler(logging.Handler):
37
+ def emit(self, record):
38
+ log_records.append(record)
39
+ logger.addHandler(LogCaptureHandler())
40
+
41
+ # Streamlit configuration
42
+ st.set_page_config(
43
+ page_title="AI Vision & SFT Titans 🚀",
44
+ page_icon="🤖",
45
+ layout="wide",
46
+ initial_sidebar_state="expanded",
47
+ menu_items={
48
+ 'Get Help': 'https://huggingface.co/awacke1',
49
+ 'Report a Bug': 'https://huggingface.co/spaces/awacke1',
50
+ 'About': "AI Vision & SFT Titans: PDFs, OCR, Image Gen, Line Drawings, Custom Diffusion, and SFT on CPU! 🌌"
51
+ }
52
+ )
53
+
54
+ # Session state initialization
55
+ st.session_state.setdefault('history', [])
56
+ st.session_state.setdefault('builder', None)
57
+ st.session_state.setdefault('model_loaded', False)
58
+ st.session_state.setdefault('processing', {})
59
+ st.session_state.setdefault('asset_checkboxes', {})
60
+ st.session_state.setdefault('downloaded_pdfs', {})
61
+ st.session_state.setdefault('unique_counter', 0)
62
+ st.session_state.setdefault('selected_model_type', "Causal LM")
63
+ st.session_state.setdefault('selected_model', "None")
64
+ st.session_state.setdefault('cam0_file', None)
65
+ st.session_state.setdefault('cam1_file', None)
66
+ st.session_state.setdefault('characters', []) # Store created characters
67
+ if 'asset_gallery_container' not in st.session_state:
68
+ st.session_state['asset_gallery_container'] = st.sidebar.empty()
69
+
70
+ @dataclass
71
+ class ModelConfig:
72
+ name: str
73
+ base_model: str
74
+ size: str
75
+ domain: Optional[str] = None
76
+ model_type: str = "causal_lm"
77
+ @property
78
+ def model_path(self):
79
+ return f"models/{self.name}"
80
+
81
+ @dataclass
82
+ class DiffusionConfig:
83
+ name: str
84
+ base_model: str
85
+ size: str
86
+ domain: Optional[str] = None
87
+ @property
88
+ def model_path(self):
89
+ return f"diffusion_models/{self.name}"
90
+
91
+ class ModelBuilder:
92
+ def __init__(self):
93
+ self.config = None
94
+ self.model = None
95
+ self.tokenizer = None
96
+ self.jokes = [
97
+ "Why did the AI go to therapy? Too many layers to unpack! 😂",
98
+ "Training complete! Time for a binary coffee break. ☕",
99
+ "I told my neural network a joke; it couldn't stop dropping bits! 🤖",
100
+ "I asked the AI for a pun, and it said, 'I'm punning on parallel processing!' 😄",
101
+ "Debugging my code is like a stand-up routine—always a series of exceptions! 😆"
102
+ ]
103
+ def load_model(self, model_path: str, config: Optional[ModelConfig] = None):
104
+ with st.spinner(f"Loading {model_path}... ⏳"):
105
+ self.model = AutoModelForCausalLM.from_pretrained(model_path)
106
+ self.tokenizer = AutoTokenizer.from_pretrained(model_path)
107
+ if self.tokenizer.pad_token is None:
108
+ self.tokenizer.pad_token = self.tokenizer.eos_token
109
+ if config:
110
+ self.config = config
111
+ self.model.to("cuda" if torch.cuda.is_available() else "cpu")
112
+ st.success(f"Model loaded! 🎉 {random.choice(self.jokes)}")
113
+ return self
114
+ def save_model(self, path: str):
115
+ with st.spinner("Saving model... 💾"):
116
+ os.makedirs(os.path.dirname(path), exist_ok=True)
117
+ self.model.save_pretrained(path)
118
+ self.tokenizer.save_pretrained(path)
119
+ st.success(f"Model saved at {path}! ✅")
120
+
121
+ class DiffusionBuilder:
122
+ def __init__(self):
123
+ self.config = None
124
+ self.pipeline = None
125
+ def load_model(self, model_path: str, config: Optional[DiffusionConfig] = None):
126
+ with st.spinner(f"Loading diffusion model {model_path}... ⏳"):
127
+ self.pipeline = StableDiffusionPipeline.from_pretrained(model_path, torch_dtype=torch.float32).to("cpu")
128
+ if config:
129
+ self.config = config
130
+ st.success("Diffusion model loaded! 🎨")
131
+ return self
132
+ def save_model(self, path: str):
133
+ with st.spinner("Saving diffusion model... 💾"):
134
+ os.makedirs(os.path.dirname(path), exist_ok=True)
135
+ self.pipeline.save_pretrained(path)
136
+ st.success(f"Diffusion model saved at {path}! ✅")
137
+ def generate(self, prompt: str):
138
+ return self.pipeline(prompt, num_inference_steps=20).images[0]
139
+
140
+ def generate_filename(sequence, ext="png"):
141
+ return f"{sequence}_{time.strftime('%d%m%Y%H%M%S')}.{ext}"
142
+
143
+ def pdf_url_to_filename(url):
144
+ return re.sub(r'[<>:"/\\|?*]', '_', url) + ".pdf"
145
+
146
+ def get_download_link(file_path, mime_type="application/pdf", label="Download"):
147
+ return f'<a href="data:{mime_type};base64,{base64.b64encode(open(file_path, "rb").read()).decode()}" download="{os.path.basename(file_path)}">{label}</a>'
148
+
149
+ def zip_directory(directory_path, zip_path):
150
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
151
+ [zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.dirname(directory_path)))
152
+ for root, _, files in os.walk(directory_path) for file in files]
153
+
154
+ def get_model_files(model_type="causal_lm"):
155
+ return [d for d in glob.glob("models/*" if model_type == "causal_lm" else "diffusion_models/*") if os.path.isdir(d)] or ["None"]
156
+
157
+ def get_gallery_files(file_types=["png", "pdf"]):
158
+ return sorted(list({f for ext in file_types for f in glob.glob(f"*.{ext}")}))
159
+
160
+ def get_pdf_files():
161
+ return sorted(glob.glob("*.pdf"))
162
+
163
+ def download_pdf(url, output_path):
164
+ try:
165
+ response = requests.get(url, stream=True, timeout=10)
166
+ if response.status_code == 200:
167
+ with open(output_path, "wb") as f:
168
+ for chunk in response.iter_content(chunk_size=8192):
169
+ f.write(chunk)
170
+ ret = True
171
+ else:
172
+ ret = False
173
+ except requests.RequestException as e:
174
+ logger.error(f"Failed to download {url}: {e}")
175
+ ret = False
176
+ return ret
177
+
178
+ async def process_pdf_snapshot(pdf_path, mode="single"):
179
+ start_time = time.time()
180
+ status = st.empty()
181
+ status.text(f"Processing PDF Snapshot ({mode})... (0s)")
182
+ try:
183
+ doc = fitz.open(pdf_path)
184
+ output_files = []
185
+ if mode == "single":
186
+ page = doc[0]
187
+ pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
188
+ output_file = generate_filename("single", "png")
189
+ pix.save(output_file)
190
+ output_files.append(output_file)
191
+ elif mode == "twopage":
192
+ for i in range(min(2, len(doc))):
193
+ page = doc[i]
194
+ pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
195
+ output_file = generate_filename(f"twopage_{i}", "png")
196
+ pix.save(output_file)
197
+ output_files.append(output_file)
198
+ elif mode == "allpages":
199
+ for i in range(len(doc)):
200
+ page = doc[i]
201
+ pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
202
+ output_file = generate_filename(f"page_{i}", "png")
203
+ pix.save(output_file)
204
+ output_files.append(output_file)
205
+ doc.close()
206
+ elapsed = int(time.time() - start_time)
207
+ status.text(f"PDF Snapshot ({mode}) completed in {elapsed}s!")
208
+ return output_files
209
+ except Exception as e:
210
+ status.error(f"Failed to process PDF: {str(e)}")
211
+ return []
212
+
213
+ async def process_gpt4o_ocr(image, output_file):
214
+ start_time = time.time()
215
+ status = st.empty()
216
+ status.text("Processing GPT-4o OCR... (0s)")
217
+ buffered = BytesIO()
218
+ image.save(buffered, format="PNG")
219
+ img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
220
+ messages = [{
221
+ "role": "user",
222
+ "content": [
223
+ {"type": "text", "text": "Extract the electronic text from this image."},
224
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_str}", "detail": "auto"}}
225
+ ]
226
+ }]
227
+ try:
228
+ response = client.chat.completions.create(model="gpt-4o", messages=messages, max_tokens=300)
229
+ result = response.choices[0].message.content
230
+ elapsed = int(time.time() - start_time)
231
+ status.text(f"GPT-4o OCR completed in {elapsed}s!")
232
+ async with aiofiles.open(output_file, "w") as f:
233
+ await f.write(result)
234
+ return result
235
+ except Exception as e:
236
+ status.error(f"Failed to process image with GPT-4o: {str(e)}")
237
+ return ""
238
+
239
+ async def process_image_gen(prompt, output_file):
240
+ start_time = time.time()
241
+ status = st.empty()
242
+ status.text("Processing Image Gen... (0s)")
243
+ pipeline = (st.session_state['builder'].pipeline
244
+ if st.session_state.get('builder') and isinstance(st.session_state['builder'], DiffusionBuilder)
245
+ and st.session_state['builder'].pipeline
246
+ else StableDiffusionPipeline.from_pretrained("OFA-Sys/small-stable-diffusion-v0", torch_dtype=torch.float32).to("cpu"))
247
+ gen_image = pipeline(prompt, num_inference_steps=20).images[0]
248
+ elapsed = int(time.time() - start_time)
249
+ status.text(f"Image Gen completed in {elapsed}s!")
250
+ gen_image.save(output_file)
251
+ return gen_image
252
+
253
+ def process_image_with_prompt(image, prompt, model="gpt-4o-mini", detail="auto"):
254
+ buffered = BytesIO()
255
+ image.save(buffered, format="PNG")
256
+ img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
257
+ messages = [{
258
+ "role": "user",
259
+ "content": [
260
+ {"type": "text", "text": prompt},
261
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_str}", "detail": detail}}
262
+ ]
263
+ }]
264
+ try:
265
+ response = client.chat.completions.create(model=model, messages=messages, max_tokens=300)
266
+ return response.choices[0].message.content
267
+ except Exception as e:
268
+ return f"Error processing image with GPT: {str(e)}"
269
+
270
+ def process_text_with_prompt(text, prompt, model="gpt-4o-mini"):
271
+ messages = [{"role": "user", "content": f"{prompt}\n\n{text}"}]
272
+ try:
273
+ response = client.chat.completions.create(model=model, messages=messages, max_tokens=300)
274
+ return response.choices[0].message.content
275
+ except Exception as e:
276
+ return f"Error processing text with GPT: {str(e)}"
277
+
278
+ # Character Editor Functions
279
+ def randomize_character_content():
280
+ # Templates for randomizing Intro and Greeting
281
+ intro_templates = [
282
+ "{char} is a valiant knight who is silent and reserved, he looks handsome but aloof.",
283
+ "{char} is a mischievous thief with a heart of gold, always sneaking around but helping those in need.",
284
+ "{char} is a wise scholar who loves books more than people, often lost in thought.",
285
+ "{char} is a fiery warrior with a short temper, but fiercely loyal to friends.",
286
+ "{char} is a gentle healer who speaks softly, always carrying herbs and a warm smile."
287
+ ]
288
+ greeting_templates = [
289
+ "You were startled by the sudden intrusion of a man into your home. 'I am from the knight's guild, and I have been ordered to arrest you.'",
290
+ "A shadowy figure steps into the light. 'I heard you needed help—name’s {char}, best thief in town.'",
291
+ "A voice calls from behind a stack of books. 'Oh, hello! I’m {char}, didn’t see you there—too many scrolls!'",
292
+ "A booming voice echoes, 'I’m {char}, and I’m here to fight for justice—or at least a good brawl!'",
293
+ "A soft hand touches your shoulder. 'I’m {char}, here to heal your wounds—don’t worry, I’ve got you.'"
294
+ ]
295
+ intro = random.choice(intro_templates)
296
+ greeting = random.choice(greeting_templates)
297
+ return intro, greeting
298
+
299
+ def save_character(character_data):
300
+ # Save character to a JSON file
301
+ characters = st.session_state.get('characters', [])
302
+ characters.append(character_data)
303
+ st.session_state['characters'] = characters
304
+ with open("characters.json", "w") as f:
305
+ json.dump(characters, f)
306
+
307
+ def load_characters():
308
+ try:
309
+ with open("characters.json", "r") as f:
310
+ characters = json.load(f)
311
+ st.session_state['characters'] = characters
312
+ except FileNotFoundError:
313
+ st.session_state['characters'] = []
314
+
315
+ # Sidebar: Gallery Settings
316
+ st.sidebar.subheader("Gallery Settings")
317
+ st.session_state.setdefault('gallery_size', 2)
318
+ st.session_state['gallery_size'] = st.sidebar.slider("Gallery Size", 1, 10, st.session_state['gallery_size'], key="gallery_size_slider")
319
+
320
+ # Tabs setup
321
+ tabs = st.tabs([
322
+ "Camera Snap 📷", "Download PDFs 📥", "Test OCR 🔍", "Build Titan 🌱",
323
+ "Test Image Gen 🎨", "PDF Process 📄", "Image Process 🖼️", "MD Gallery 📚",
324
+ "Character Editor 🧑‍🎨", "Character Gallery 🖼️"
325
+ ])
326
+ (tab_camera, tab_download, tab_ocr, tab_build, tab_imggen, tab_pdf_process, tab_image_process, tab_md_gallery, tab_character_editor, tab_character_gallery) = tabs
327
+
328
+ with tab_camera:
329
+ st.header("Camera Snap 📷")
330
+ st.subheader("Single Capture")
331
+ cols = st.columns(2)
332
+ with cols[0]:
333
+ cam0_img = st.camera_input("Take a picture - Cam 0", key="cam0")
334
+ if cam0_img:
335
+ filename = generate_filename("cam0")
336
+ if st.session_state['cam0_file'] and os.path.exists(st.session_state['cam0_file']):
337
+ os.remove(st.session_state['cam0_file'])
338
+ with open(filename, "wb") as f:
339
+ f.write(cam0_img.getvalue())
340
+ st.session_state['cam0_file'] = filename
341
+ entry = f"Snapshot from Cam 0: {filename}"
342
+ st.session_state['history'].append(entry)
343
+ st.image(Image.open(filename), caption="Camera 0", use_container_width=True)
344
+ logger.info(f"Saved snapshot from Camera 0: {filename}")
345
+ with cols[1]:
346
+ cam1_img = st.camera_input("Take a picture - Cam 1", key="cam1")
347
+ if cam1_img:
348
+ filename = generate_filename("cam1")
349
+ if st.session_state['cam1_file'] and os.path.exists(st.session_state['cam1_file']):
350
+ os.remove(st.session_state['cam1_file'])
351
+ with open(filename, "wb") as f:
352
+ f.write(cam1_img.getvalue())
353
+ st.session_state['cam1_file'] = filename
354
+ entry = f"Snapshot from Cam 1: {filename}"
355
+ st.session_state['history'].append(entry)
356
+ st.image(Image.open(filename), caption="Camera 1", use_container_width=True)
357
+ logger.info(f"Saved snapshot from Camera 1: {filename}")
358
+
359
+ with tab_download:
360
+ st.header("Download PDFs 📥")
361
+ if st.button("Examples 📚"):
362
+ example_urls = [
363
+ "https://arxiv.org/pdf/2308.03892",
364
+ "https://arxiv.org/pdf/1912.01703",
365
+ "https://arxiv.org/pdf/2408.11039",
366
+ "https://arxiv.org/pdf/2109.10282",
367
+ "https://arxiv.org/pdf/2112.10752",
368
+ "https://arxiv.org/pdf/2308.11236",
369
+ "https://arxiv.org/pdf/1706.03762",
370
+ "https://arxiv.org/pdf/2006.11239",
371
+ "https://arxiv.org/pdf/2305.11207",
372
+ "https://arxiv.org/pdf/2106.09685",
373
+ "https://arxiv.org/pdf/2005.11401",
374
+ "https://arxiv.org/pdf/2106.10504"
375
+ ]
376
+ st.session_state['pdf_urls'] = "\n".join(example_urls)
377
+ url_input = st.text_area("Enter PDF URLs (one per line)", value=st.session_state.get('pdf_urls', ""), height=200)
378
+ if st.button("Robo-Download 🤖"):
379
+ urls = url_input.strip().split("\n")
380
+ progress_bar = st.progress(0)
381
+ status_text = st.empty()
382
+ total_urls = len(urls)
383
+ existing_pdfs = get_pdf_files()
384
+ for idx, url in enumerate(urls):
385
+ if url:
386
+ output_path = pdf_url_to_filename(url)
387
+ status_text.text(f"Fetching {idx + 1}/{total_urls}: {os.path.basename(output_path)}...")
388
+ if output_path not in existing_pdfs:
389
+ if download_pdf(url, output_path):
390
+ st.session_state['downloaded_pdfs'][url] = output_path
391
+ logger.info(f"Downloaded PDF from {url} to {output_path}")
392
+ entry = f"Downloaded PDF: {output_path}"
393
+ st.session_state['history'].append(entry)
394
+ st.session_state['asset_checkboxes'][output_path] = True
395
+ else:
396
+ st.error(f"Failed to nab {url} 😿")
397
+ else:
398
+ st.info(f"Already got {os.path.basename(output_path)}! Skipping... 🐾")
399
+ st.session_state['downloaded_pdfs'][url] = output_path
400
+ progress_bar.progress((idx + 1) / total_urls)
401
+ status_text.text("Robo-Download complete! 🚀")
402
+ mode = st.selectbox("Snapshot Mode", ["Single Page (High-Res)", "Two Pages (High-Res)", "All Pages (High-Res)"], key="download_mode")
403
+ if st.button("Snapshot Selected 📸"):
404
+ selected_pdfs = [path for path in get_gallery_files() if path.endswith('.pdf') and st.session_state['asset_checkboxes'].get(path, False)]
405
+ if selected_pdfs:
406
+ for pdf_path in selected_pdfs:
407
+ if not os.path.exists(pdf_path):
408
+ st.warning(f"File not found: {pdf_path}. Skipping.")
409
+ continue
410
+ mode_key = {"Single Page (High-Res)": "single",
411
+ "Two Pages (High-Res)": "twopage",
412
+ "All Pages (High-Res)": "allpages"}[mode]
413
+ snapshots = asyncio.run(process_pdf_snapshot(pdf_path, mode_key))
414
+ for snapshot in snapshots:
415
+ st.image(Image.open(snapshot), caption=snapshot, use_container_width=True)
416
+ st.session_state['asset_checkboxes'][snapshot] = True
417
+ else:
418
+ st.warning("No PDFs selected for snapshotting! Check some boxes in the sidebar.")
419
+
420
+ with tab_ocr:
421
+ st.header("Test OCR 🔍")
422
+ all_files = get_gallery_files()
423
+ if all_files:
424
+ if st.button("OCR All Assets 🚀"):
425
+ full_text = "# OCR Results (GPT-4o)\n\n"
426
+ for file in all_files:
427
+ if file.endswith('.png'):
428
+ image = Image.open(file)
429
+ else:
430
+ doc = fitz.open(file)
431
+ pix = doc[0].get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
432
+ image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
433
+ doc.close()
434
+ output_file = generate_filename(f"ocr_{os.path.basename(file)}", "txt")
435
+ result = asyncio.run(process_gpt4o_ocr(image, output_file))
436
+ full_text += f"## {os.path.basename(file)}\n\n{result}\n\n"
437
+ entry = f"OCR Test: {file} -> {output_file}"
438
+ st.session_state['history'].append(entry)
439
+ md_output_file = f"full_ocr_{int(time.time())}.md"
440
+ with open(md_output_file, "w") as f:
441
+ f.write(full_text)
442
+ st.success(f"Full OCR saved to {md_output_file}")
443
+ st.markdown(get_download_link(md_output_file, "text/markdown", "Download Full OCR Markdown"), unsafe_allow_html=True)
444
+ selected_file = st.selectbox("Select Image or PDF", all_files, key="ocr_select")
445
+ if selected_file:
446
+ if selected_file.endswith('.png'):
447
+ image = Image.open(selected_file)
448
+ else:
449
+ doc = fitz.open(selected_file)
450
+ pix = doc[0].get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
451
+ image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
452
+ doc.close()
453
+ st.image(image, caption="Input Image", use_container_width=True)
454
+ if st.button("Run OCR 🚀", key="ocr_run"):
455
+ output_file = generate_filename("ocr_output", "txt")
456
+ st.session_state['processing']['ocr'] = True
457
+ result = asyncio.run(process_gpt4o_ocr(image, output_file))
458
+ entry = f"OCR Test: {selected_file} -> {output_file}"
459
+ st.session_state['history'].append(entry)
460
+ st.text_area("OCR Result", result, height=200, key="ocr_result")
461
+ st.success(f"OCR output saved to {output_file}")
462
+ st.session_state['processing']['ocr'] = False
463
+ if selected_file.endswith('.pdf') and st.button("OCR All Pages 🚀", key="ocr_all_pages"):
464
+ doc = fitz.open(selected_file)
465
+ full_text = f"# OCR Results for {os.path.basename(selected_file)}\n\n"
466
+ for i in range(len(doc)):
467
+ pix = doc[i].get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
468
+ image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
469
+ output_file = generate_filename(f"ocr_page_{i}", "txt")
470
+ result = asyncio.run(process_gpt4o_ocr(image, output_file))
471
+ full_text += f"## Page {i + 1}\n\n{result}\n\n"
472
+ entry = f"OCR Test: {selected_file} Page {i + 1} -> {output_file}"
473
+ st.session_state['history'].append(entry)
474
+ md_output_file = f"full_ocr_{os.path.basename(selected_file)}_{int(time.time())}.md"
475
+ with open(md_output_file, "w") as f:
476
+ f.write(full_text)
477
+ st.success(f"Full OCR saved to {md_output_file}")
478
+ st.markdown(get_download_link(md_output_file, "text/markdown", "Download Full OCR Markdown"), unsafe_allow_html=True)
479
+ else:
480
+ st.warning("No assets in gallery yet. Use Camera Snap or Download PDFs!")
481
+
482
+ with tab_build:
483
+ st.header("Build Titan 🌱")
484
+ model_type = st.selectbox("Model Type", ["Causal LM", "Diffusion"], key="build_type")
485
+ base_model = st.selectbox(
486
+ "Select Tiny Model",
487
+ ["HuggingFaceTB/SmolLM-135M", "Qwen/Qwen1.5-0.5B-Chat"] if model_type == "Causal LM"
488
+ else ["OFA-Sys/small-stable-diffusion-v0", "stabilityai/stable-diffusion-2-base"]
489
+ )
490
+ model_name = st.text_input("Model Name", f"tiny-titan-{int(time.time())}")
491
+ domain = st.text_input("Target Domain", "general")
492
+ if st.button("Download Model ⬇️"):
493
+ config = (ModelConfig if model_type == "Causal LM" else DiffusionConfig)(
494
+ name=model_name, base_model=base_model, size="small", domain=domain
495
+ )
496
+ builder = ModelBuilder() if model_type == "Causal LM" else DiffusionBuilder()
497
+ builder.load_model(base_model, config)
498
+ builder.save_model(config.model_path)
499
+ st.session_state['builder'] = builder
500
+ st.session_state['model_loaded'] = True
501
+ st.session_state['selected_model_type'] = model_type
502
+ st.session_state['selected_model'] = config.model_path
503
+ entry = f"Built {model_type} model: {model_name}"
504
+ st.session_state['history'].append(entry)
505
+ st.success(f"Model downloaded and saved to {config.model_path}! 🎉")
506
+ st.rerun()
507
+
508
+ with tab_imggen:
509
+ st.header("Test Image Gen 🎨")
510
+ all_files = get_gallery_files()
511
+ if all_files:
512
+ selected_file = st.selectbox("Select Image or PDF", all_files, key="gen_select")
513
+ if selected_file:
514
+ if selected_file.endswith('.png'):
515
+ image = Image.open(selected_file)
516
+ else:
517
+ doc = fitz.open(selected_file)
518
+ pix = doc[0].get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
519
+ image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
520
+ doc.close()
521
+ st.image(image, caption="Reference Image", use_container_width=True)
522
+ prompt = st.text_area("Prompt", "Generate a neon superhero version of this image", key="gen_prompt")
523
+ if st.button("Run Image Gen 🚀", key="gen_run"):
524
+ output_file = generate_filename("gen_output", "png")
525
+ st.session_state['processing']['gen'] = True
526
+ result = asyncio.run(process_image_gen(prompt, output_file))
527
+ entry = f"Image Gen Test: {prompt} -> {output_file}"
528
+ st.session_state['history'].append(entry)
529
+ st.image(result, caption="Generated Image", use_container_width=True)
530
+ st.success(f"Image saved to {output_file}")
531
+ st.session_state['processing']['gen'] = False
532
+ else:
533
+ st.warning("No images or PDFs in gallery yet. Use Camera Snap or Download PDFs!")
534
+
535
+ with tab_pdf_process:
536
+ st.header("PDF Process")
537
+ st.subheader("Upload PDFs for GPT-based text extraction")
538
+ gpt_models = ["gpt-4o", "gpt-4o-mini"]
539
+ selected_gpt_model = st.selectbox("Select GPT Model", gpt_models, key="pdf_gpt_model")
540
+ detail_level = st.selectbox("Detail Level", ["auto", "low", "high"], key="pdf_detail_level")
541
+ uploaded_pdfs = st.file_uploader("Upload PDF files", type=["pdf"], accept_multiple_files=True, key="pdf_process_uploader")
542
+ view_mode = st.selectbox("View Mode", ["Single Page", "Double Page"], key="pdf_view_mode")
543
+ if st.button("Process Uploaded PDFs", key="process_pdfs"):
544
+ combined_text = ""
545
+ for pdf_file in uploaded_pdfs:
546
+ pdf_bytes = pdf_file.read()
547
+ temp_pdf_path = f"temp_{pdf_file.name}"
548
+ with open(temp_pdf_path, "wb") as f:
549
+ f.write(pdf_bytes)
550
+ try:
551
+ doc = fitz.open(temp_pdf_path)
552
+ st.write(f"Processing {pdf_file.name} with {len(doc)} pages")
553
+ if view_mode == "Single Page":
554
+ for i, page in enumerate(doc):
555
+ pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
556
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
557
+ st.image(img, caption=f"{pdf_file.name} Page {i+1}")
558
+ gpt_text = process_image_with_prompt(img, "Extract the electronic text from image", model=selected_gpt_model, detail=detail_level)
559
+ combined_text += f"\n## {pdf_file.name} - Page {i+1}\n\n{gpt_text}\n"
560
+ else:
561
+ pages = list(doc)
562
+ for i in range(0, len(pages), 2):
563
+ if i+1 < len(pages):
564
+ pix1 = pages[i].get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
565
+ img1 = Image.frombytes("RGB", [pix1.width, pix1.height], pix1.samples)
566
+ pix2 = pages[i+1].get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
567
+ img2 = Image.frombytes("RGB", [pix2.width, pix2.height], pix2.samples)
568
+ total_width = img1.width + img2.width
569
+ max_height = max(img1.height, img2.height)
570
+ combined_img = Image.new("RGB", (total_width, max_height))
571
+ combined_img.paste(img1, (0, 0))
572
+ combined_img.paste(img2, (img1.width, 0))
573
+ st.image(combined_img, caption=f"{pdf_file.name} Pages {i+1}-{i+2}")
574
+ gpt_text = process_image_with_prompt(combined_img, "Extract the electronic text from image", model=selected_gpt_model, detail=detail_level)
575
+ combined_text += f"\n## {pdf_file.name} - Pages {i+1}-{i+2}\n\n{gpt_text}\n"
576
+ else:
577
+ pix = pages[i].get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
578
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
579
+ st.image(img, caption=f"{pdf_file.name} Page {i+1}")
580
+ gpt_text = process_image_with_prompt(img, "Extract the electronic text from image", model=selected_gpt_model, detail=detail_level)
581
+ combined_text += f"\n## {pdf_file.name} - Page {i+1}\n\n{gpt_text}\n"
582
+ doc.close()
583
+ except Exception as e:
584
+ st.error(f"Error processing {pdf_file.name}: {str(e)}")
585
+ finally:
586
+ os.remove(temp_pdf_path)
587
+ output_filename = generate_filename("processed_pdf", "md")
588
+ with open(output_filename, "w", encoding="utf-8") as f:
589
+ f.write(combined_text)
590
+ st.success(f"PDF processing complete. MD file saved as {output_filename}")
591
+ st.markdown(get_download_link(output_filename, "text/markdown", "Download Processed PDF MD"), unsafe_allow_html=True)
592
+
593
+ with tab_image_process:
594
+ st.header("Image Process")
595
+ st.subheader("Upload Images for GPT-based OCR")
596
+ gpt_models = ["gpt-4o", "gpt-4o-mini"]
597
+ selected_gpt_model = st.selectbox("Select GPT Model", gpt_models, key="img_gpt_model")
598
+ detail_level = st.selectbox("Detail Level", ["auto", "low", "high"], key="img_detail_level")
599
+ prompt_img = st.text_input("Enter prompt for image processing", "Extract the electronic text from image", key="img_process_prompt")
600
+ uploaded_images = st.file_uploader("Upload image files", type=["png", "jpg", "jpeg"], accept_multiple_files=True, key="image_process_uploader")
601
+ if st.button("Process Uploaded Images", key="process_images"):
602
+ combined_text = ""
603
+ for img_file in uploaded_images:
604
+ try:
605
+ img = Image.open(img_file)
606
+ st.image(img, caption=img_file.name)
607
+ gpt_text = process_image_with_prompt(img, prompt_img, model=selected_gpt_model, detail=detail_level)
608
+ combined_text += f"\n## {img_file.name}\n\n{gpt_text}\n"
609
+ except Exception as e:
610
+ st.error(f"Error processing image {img_file.name}: {str(e)}")
611
+ output_filename = generate_filename("processed_image", "md")
612
+ with open(output_filename, "w", encoding="utf-8") as f:
613
+ f.write(combined_text)
614
+ st.success(f"Image processing complete. MD file saved as {output_filename}")
615
+ st.markdown(get_download_link(output_filename, "text/markdown", "Download Processed Image MD"), unsafe_allow_html=True)
616
+
617
+ with tab_md_gallery:
618
+ st.header("MD Gallery and GPT Processing")
619
+ gpt_models = ["gpt-4o", "gpt-4o-mini"]
620
+ selected_gpt_model = st.selectbox("Select GPT Model", gpt_models, key="md_gpt_model")
621
+ md_files = sorted(glob.glob("*.md"))
622
+ if md_files:
623
+ st.subheader("Individual File Processing")
624
+ cols = st.columns(2)
625
+ for idx, md_file in enumerate(md_files):
626
+ with cols[idx % 2]:
627
+ st.write(md_file)
628
+ if st.button(f"Process {md_file}", key=f"process_md_{md_file}"):
629
+ try:
630
+ with open(md_file, "r", encoding="utf-8") as f:
631
+ content = f.read()
632
+ prompt_md = "Summarize this into markdown outline with emojis and number the topics 1..12"
633
+ result_text = process_text_with_prompt(content, prompt_md, model=selected_gpt_model)
634
+ st.markdown(result_text)
635
+ output_filename = generate_filename(f"processed_{os.path.splitext(md_file)[0]}", "md")
636
+ with open(output_filename, "w", encoding="utf-8") as f:
637
+ f.write(result_text)
638
+ st.markdown(get_download_link(output_filename, "text/markdown", f"Download {output_filename}"), unsafe_allow_html=True)
639
+ except Exception as e:
640
+ st.error(f"Error processing {md_file}: {str(e)}")
641
+ st.subheader("Batch Processing")
642
+ st.write("Select MD files to combine and process:")
643
+ selected_md = {}
644
+ for md_file in md_files:
645
+ selected_md[md_file] = st.checkbox(md_file, key=f"checkbox_md_{md_file}")
646
+ batch_prompt = st.text_input("Enter batch processing prompt", "Summarize this into markdown outline with emojis and number the topics 1..12", key="batch_prompt")
647
+ if st.button("Process Selected MD Files", key="process_batch_md"):
648
+ combined_content = ""
649
+ for md_file, selected in selected_md.items():
650
+ if selected:
651
+ try:
652
+ with open(md_file, "r", encoding="utf-8") as f:
653
+ combined_content += f"\n## {md_file}\n" + f.read() + "\n"
654
+ except Exception as e:
655
+ st.error(f"Error reading {md_file}: {str(e)}")
656
+ if combined_content:
657
+ result_text = process_text_with_prompt(combined_content, batch_prompt, model=selected_gpt_model)
658
+ st.markdown(result_text)
659
+ output_filename = generate_filename("batch_processed_md", "md")
660
+ with open(output_filename, "w", encoding="utf-8") as f:
661
+ f.write(result_text)
662
+ st.success(f"Batch processing complete. MD file saved as {output_filename}")
663
+ st.markdown(get_download_link(output_filename, "text/markdown", "Download Batch Processed MD"), unsafe_allow_html=True)
664
+ else:
665
+ st.warning("No MD files selected.")
666
+ else:
667
+ st.warning("No MD files found.")
668
+
669
+ with tab_character_editor:
670
+ st.header("Character Editor 🧑‍🎨")
671
+ st.subheader("Create Your Character")
672
+
673
+ # Character creation form
674
+ if st.button("Randomize Content 🎲"):
675
+ name = f"Character_{random.randint(1000, 9999)}"
676
+ gender = random.choice(["Male", "Female", "Non-binary"])
677
+ intro, greeting = randomize_character_content()
678
+ st.session_state['char_name'] = name
679
+ st.session_state['char_gender'] = gender
680
+ st.session_state['char_intro'] = intro.format(char=name)
681
+ st.session_state['char_greeting'] = greeting.format(char=name)
682
+
683
+ name = st.text_input("Name (3-25 characters, letters, numbers, underscore, hyphen, space only)",
684
+ value=st.session_state.get('char_name', ''),
685
+ max_chars=25,
686
+ key="char_name")
687
+ gender = st.radio("Gender", ["Male", "Female", "Non-binary"],
688
+ index=["Male", "Female", "Non-binary"].index(st.session_state.get('char_gender', "Male")),
689
+ key="char_gender")
690
+ intro = st.text_area("Intro (Publicly seen)",
691
+ value=st.session_state.get('char_intro', ''),
692
+ max_chars=300,
693
+ key="char_intro")
694
+ greeting = st.text_area("Greeting",
695
+ value=st.session_state.get('char_greeting', ''),
696
+ max_chars=300,
697
+ key="char_greeting")
698
+
699
+ if st.button("Create Character", key="create_character"):
700
+ if not name or len(name) < 3:
701
+ st.error("Name must be 3-25 characters long.")
702
+ elif not re.match(r'^[a-zA-Z0-9_- ]+$', name):
703
+ st.error("Name can only contain letters, numbers, underscores, hyphens, and spaces.")
704
+ elif not intro or not greeting:
705
+ st.error("Intro and Greeting cannot be empty.")
706
+ else:
707
+ character_data = {
708
+ "name": name,
709
+ "gender": gender,
710
+ "intro": intro,
711
+ "greeting": greeting,
712
+ "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
713
+ "tags": ["OC"] # Default tag, can be expanded
714
+ }
715
+ save_character(character_data)
716
+ st.success(f"Character '{name}' created successfully!")
717
+ st.session_state['char_name'] = ''
718
+ st.session_state['char_gender'] = "Male"
719
+ st.session_state['char_intro'] = ''
720
+ st.session_state['char_greeting'] = ''
721
+ st.rerun()
722
+
723
+ with tab_character_gallery:
724
+ st.header("Character Gallery 🖼️")
725
+ load_characters()
726
+ characters = st.session_state.get('characters', [])
727
+ if characters:
728
+ st.subheader("Your Characters")
729
+ cols = st.columns(3) # 3 characters per row
730
+ for idx, char in enumerate(characters):
731
+ with cols[idx % 3]:
732
+ st.markdown(f"**{char['name']}**")
733
+ st.write(f"**Gender**: {char['gender']}")
734
+ st.write(f"**Intro**: {char['intro']}")
735
+ st.write(f"**Greeting**: {char['greeting']}")
736
+ st.write(f"**Created**: {char['created_at']}")
737
+ st.write(f"**Tags**: {', '.join(char['tags'])}")
738
+ if st.button(f"Delete {char['name']}", key=f"delete_char_{idx}"):
739
+ characters.pop(idx)
740
+ st.session_state['characters'] = characters
741
+ with open("characters.json", "w") as f:
742
+ json.dump(characters, f)
743
+ st.rerun()
744
+ st.markdown("---")
745
+ else:
746
+ st.warning("No characters created yet. Use the Character Editor to create one!")
747
+
748
+ def update_gallery():
749
+ container = st.session_state['asset_gallery_container']
750
+ container.empty()
751
+ all_files = get_gallery_files()
752
+ if all_files:
753
+ container.markdown("### Asset Gallery 📸📖")
754
+ cols = container.columns(2)
755
+ for idx, file in enumerate(all_files[:st.session_state['gallery_size']]):
756
+ with cols[idx % 2]:
757
+ st.session_state['unique_counter'] += 1
758
+ unique_id = st.session_state['unique_counter']
759
+ if file.endswith('.png'):
760
+ st.image(Image.open(file), caption=os.path.basename(file), use_container_width=True)
761
+ else:
762
+ doc = fitz.open(file)
763
+ pix = doc[0].get_pixmap(matrix=fitz.Matrix(0.5, 0.5))
764
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
765
+ st.image(img, caption=os.path.basename(file), use_container_width=True)
766
+ doc.close()
767
+ checkbox_key = f"asset_{file}_{unique_id}"
768
+ st.session_state['asset_checkboxes'][file] = st.checkbox("Use for SFT/Input", value=st.session_state['asset_checkboxes'].get(file, False), key=checkbox_key)
769
+ mime_type = "image/png" if file.endswith('.png') else "application/pdf"
770
+ st.markdown(get_download_link(file, mime_type, "Snag It! 📥"), unsafe_allow_html=True)
771
+ if st.button("Zap It! 🗑️", key=f"delete_{file}_{unique_id}"):
772
+ os.remove(file)
773
+ st.session_state['asset_checkboxes'].pop(file, None)
774
+ st.success(f"Asset {os.path.basename(file)} vaporized! 💨")
775
+ st.rerun()
776
+
777
+ update_gallery()
778
+
779
+ st.sidebar.subheader("Action Logs 📜")
780
+ for record in log_records:
781
+ st.sidebar.write(f"{record.asctime} - {record.levelname} - {record.message}")
782
+
783
+ st.sidebar.subheader("History 📜")
784
+ for entry in st.session_state.get("history", []):
785
+ if entry is not None:
786
+ st.sidebar.write(entry)