Datasets:
Tags:
Not-For-All-Audiences
Upload LoRa_vertical_slice.ipynb
Browse files
LoRa_vertical_slice.ipynb
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
{"cells":[{"cell_type":"code","source":["import os\n","import io\n","import random\n","from google.colab import files\n","from PIL import Image\n","import cv2\n","import numpy as np\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Configuration\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","num_frames = 14 #@param {type:\"slider\", min:1, max:500, step:1}\n","split_images_horizontally = False #@param {type:\"boolean\"}\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Upload your images/videos\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","print(\"Upload your jpg, jpeg, png, webp or webm files\")\n","uploaded = files.upload()\n","\n","# Collect images (and optionally split them)\n","source_images = []\n","\n","for filename, filedata in uploaded.items():\n"," fname_lower = filename.lower()\n"," if fname_lower.endswith(('.jpg', '.jpeg', '.png', '.webp')):\n"," try:\n"," img = Image.open(io.BytesIO(filedata)).convert('RGB')\n"," source_images.append(img)\n"," except:\n"," print(f\"Could not open image: {filename}\")\n"," elif fname_lower.endswith('.webm'):\n"," try:\n"," cap = cv2.VideoCapture(filename)\n"," ret, frame = cap.read()\n"," cap.release()\n"," if ret:\n"," frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n"," img = Image.fromarray(frame_rgb)\n"," source_images.append(img)\n"," else:\n"," print(f\"Could not read video frame: {filename}\")\n"," except:\n"," print(f\"Error processing video: {filename}\")\n","\n","if not source_images:\n"," print(\"No valid images were loaded. Please upload jpg/jpeg/png/webp/webm files.\")\n"," # Early exit\n","else:\n"," print(f\"Loaded {len(source_images)} images\")\n","\n"," if split_images_horizontally:\n"," print(\"Splitting images horizontally (top + bottom half)...\")\n"," split_images = []\n"," for img in source_images:\n"," w, h = img.size\n"," if h < 4: # too tiny to split meaningfully\n"," split_images.append(img)\n"," continue\n"," half_h = h // 2\n"," top = img.crop((0, 0, w, half_h))\n"," bottom = img.crop((0, half_h, w, h))\n"," split_images.append(top)\n"," split_images.append(bottom)\n"," source_images = split_images\n"," print(f\"β Now working with {len(source_images)} half-images\")\n","\n"," # ββββββββββββββββββββββββββββββββββββββββββββββββ\n"," # Settings\n"," # ββββββββββββββββββββββββββββββββββββββββββββββββ\n"," FRAME_SIZE = 1024\n"," BORDER_PX = 14\n"," INNER_SIZE = FRAME_SIZE - 2 * BORDER_PX # 996\n"," num_vertical_panels = 4 #@param{type:'slider',min:1, max:12}\n"," NUM_SLICES = num_vertical_panels\n"," SLICE_WIDTH = INNER_SIZE // NUM_SLICES # 166 px when NUM_SLICES=6\n"," BORDER_COLOR = (24, 24, 24) # #181818\n","\n"," # ββββββββββββββββββββββββββββββββββββββββββββββββ\n"," # Extract multiple vertical slices from each (half-)image\n"," # ββββββββββββββββββββββββββββββββββββββββββββββββ\n"," all_slices = []\n"," target_w = SLICE_WIDTH\n"," target_h = INNER_SIZE\n","\n"," for photo in source_images:\n"," w, h = photo.size\n"," if h == 0 or w == 0:\n"," continue\n","\n"," # Resize so height matches target_h (full inner height)\n"," scale = target_h / h\n"," new_w = int(w * scale + 0.5)\n"," new_h = target_h\n","\n"," if new_w < 1:\n"," continue\n","\n"," resized = photo.resize((new_w, new_h), Image.LANCZOS)\n","\n"," if new_w < target_w:\n"," # Too narrow β center-pad to one slice\n"," slice_img = Image.new('RGB', (target_w, target_h), BORDER_COLOR)\n"," paste_x = (target_w - new_w) // 2\n"," slice_img.paste(resized, (paste_x, 0))\n"," all_slices.append(slice_img)\n"," else:\n"," # Multiple slices possible\n"," num_possible = new_w // target_w\n"," if num_possible < 1:\n"," num_possible = 1\n","\n"," total_width_used = num_possible * target_w\n"," start_left = (new_w - total_width_used) // 2\n","\n"," for i in range(num_possible):\n"," left = start_left + i * target_w\n"," crop = resized.crop((left, 0, left + target_w, target_h))\n"," all_slices.append(crop)\n","\n"," print(f\"Extracted {len(all_slices)} vertical slices\")\n","\n"," if len(all_slices) == 0:\n"," print(\"No usable slices could be extracted. Check image sizes.\")\n"," else:\n"," output_dir = \"vertical_slice_frames\"\n"," os.makedirs(output_dir, exist_ok=True)\n","\n"," frame_idx = 0\n","\n"," while frame_idx < num_frames:\n"," # Random sample with some oversampling to reduce repetition\n"," group = random.sample(all_slices * 4, NUM_SLICES) # Γ4 β good balance for variety\n"," random.shuffle(group)\n","\n"," # Build canvas\n"," canvas = Image.new('RGB', (INNER_SIZE, INNER_SIZE), (0, 0, 0))\n","\n"," for col in range(NUM_SLICES):\n"," crop = group[col]\n"," x = col * SLICE_WIDTH\n"," canvas.paste(crop, (x, 0))\n","\n"," # Add border\n"," final = Image.new('RGB', (FRAME_SIZE, FRAME_SIZE), BORDER_COLOR)\n"," final.paste(canvas, (BORDER_PX, BORDER_PX))\n","\n"," # Save\n"," frame_idx += 1\n"," out_path = os.path.join(output_dir, f\"frame_{frame_idx:04d}.jpg\") # :04d for nicer sorting with 500 frames\n"," final.save(out_path, \"JPEG\", quality=92)\n"," if frame_idx % 50 == 0:\n"," print(f\"Saved {frame_idx}/{num_frames} frames...\")\n","\n"," print(f\"\\nDone. Created {frame_idx} randomized frames in folder: /{output_dir}\")\n","\n"," # Zip & download\n"," zip_name = \"vertical_frames.zip\"\n"," !zip -r -q {zip_name} {output_dir}\n"," files.download(zip_name)"],"metadata":{"id":"_kz2zIO12PQQ"},"execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/LoRa_vertical_slice.ipynb","timestamp":1772831486007},{"file_id":"11rioWNojWzoPp-O4wZK97yjublkR9GtQ","timestamp":1772750616448},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1772741185417},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1763646205520},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1760993725927},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1760450712160},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1756712618300},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1747490904984},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1740037333374},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1736477078136},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1725365086834}]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}
|
|
|
|
| 1 |
+
{"cells":[{"cell_type":"code","source":["from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"collapsed":true,"id":"at9ImGTxYqn6"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["import os\n","import io\n","import random\n","import zipfile\n","from google.colab import drive\n","from PIL import Image\n","import cv2\n","import numpy as np\n","from datetime import datetime\n","import gc\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Configuration\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","num_frames = 1000 #@param {type:\"slider\", min:1, max:1500, step:1}\n","split_images_horizontally = False #@param {type:\"boolean\"}\n","use_manual_upload = False #@param {type:\"boolean\"}\n","\n","save_to_google_drive = True #@param {type:\"boolean\"}\n","drive_folder_name = \"vertical_slices_output\" #@param {type:\"string\"}\n","\n","#@markdown ---\n","#@markdown **ZIP MODE** (when `use_manual_upload` is OFF)\n","#@markdown Paste full path to your zip file\n","#@markdown (example: `/content/my_images.zip` or `/content/drive/MyDrive/photos.zip`)\n","zip_file_path = \"/content/drive/MyDrive/fetch.zip\" #@param {type:\"string\"}\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Mount Google Drive if selected\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","drive_mounted = False\n","drive_output_dir = None\n","\n","if save_to_google_drive:\n"," try:\n"," drive.mount('/content/drive', force_remount=False)\n"," drive_mounted = True\n"," drive_base = \"/content/drive/MyDrive\"\n"," drive_output_dir = os.path.join(drive_base, drive_folder_name)\n"," os.makedirs(drive_output_dir, exist_ok=True)\n"," print(f\"β Google Drive mounted. Zip will be saved to: {drive_output_dir}\")\n"," except Exception as e:\n"," print(f\"Google Drive mount failed: {e}\")\n"," print(\"β No output will be saved (browser download was removed).\")\n"," save_to_google_drive = False\n","else:\n"," print(\"Google Drive saving is disabled β no output will be saved!\")\n","\n","# Early exit if nowhere to save\n","if not save_to_google_drive:\n"," print(\"\\n!!! WARNING: No saving method is active. Frames will be created but lost after runtime ends.\")\n"," print(\" β Enable 'save_to_google_drive' or the work is temporary only.\\n\")\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Helpers to reduce memory usage\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","def extract_vertical_slices(photo, target_w, target_h, border_color):\n"," \"\"\"Extract slices from one image β return list of small crops only\"\"\"\n"," slices = []\n"," w, h = photo.size\n"," if h <= 0 or w <= 0:\n"," return slices\n","\n"," scale = target_h / h\n"," new_w = int(w * scale + 0.5)\n"," if new_w < 1:\n"," return slices\n","\n"," resized = photo.resize((new_w, target_h), Image.LANCZOS)\n","\n"," if new_w < target_w:\n"," sl = Image.new('RGB', (target_w, target_h), border_color)\n"," sl.paste(resized, ((target_w - new_w)//2, 0))\n"," slices.append(sl)\n"," else:\n"," num = max(1, new_w // target_w)\n"," used = num * target_w\n"," start = (new_w - used) // 2\n"," for i in range(num):\n"," left = start + i * target_w\n"," crop = resized.crop((left, 0, left + target_w, target_h))\n"," slices.append(crop)\n","\n"," # Free resized immediately\n"," del resized\n"," return slices\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Load & process images one-by-one (memory friendly)\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","all_slices = []\n","BORDER_COLOR = (24, 24, 24)\n","\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","# Frame composition settings - moved up to define target_w earlier\n","# ββββββββββββββββββββββββββββββββββββββββββββββββ\n","FRAME_SIZE = 1024\n","BORDER_PX = 14\n","INNER_SIZE = FRAME_SIZE - 2 * BORDER_PX\n","num_vertical_panels = 4 #@param {type:\"slider\", min:1, max:12}\n","NUM_SLICES = num_vertical_panels\n","SLICE_WIDTH = INNER_SIZE // NUM_SLICES\n","target_h = INNER_SIZE # target_h was also defined later, ensuring it's available\n","target_w = SLICE_WIDTH # now we know it\n","\n","extract_root = \"/content/extracted_images\"\n","os.makedirs(extract_root, exist_ok=True)\n","\n","print(\"Starting image loading and slice extraction...\\n\")\n","\n","if use_manual_upload:\n"," from google.colab import files\n"," print(\"Upload your jpg, jpeg, png, webp or webm files\")\n"," uploaded = files.upload()\n","\n"," for filename, filedata in uploaded.items():\n"," fname_lower = filename.lower()\n"," if fname_lower.startswith('._') or '__macosx' in fname_lower:\n"," continue\n","\n"," if fname_lower.endswith(('.jpg','.jpeg','.png','.webp')):\n"," try:\n"," img = Image.open(io.BytesIO(filedata)).convert('RGB')\n"," # Process immediately\n"," temp_slices = extract_vertical_slices(img, target_w, target_h, BORDER_COLOR)\n"," all_slices.extend(temp_slices)\n"," del img\n"," del temp_slices\n"," gc.collect()\n"," except Exception as e:\n"," print(f\"Skip {filename}: {e}\")\n","\n"," elif fname_lower.endswith('.webm'):\n"," # Video handling skipped for memory β too heavy; can re-add if needed\n"," pass # Added pass statement here to fix the IndentationError\n","\n","else:\n"," if not zip_file_path.strip() or not os.path.isfile(zip_file_path):\n"," print(\"No valid zip path provided.\")\n"," else:\n"," try:\n"," with zipfile.ZipFile(zip_file_path, 'r') as zf:\n"," zf.extractall(extract_root)\n"," print(\"Extraction done.\")\n"," except Exception as e:\n"," print(f\"Zip error: {e}\")\n"," raise\n","\n"," valid_exts = ('.jpg', '.jpeg', '.png', '.webp')\n"," count = 0\n"," for root, _, files in os.walk(extract_root):\n"," if '__MACOSX' in root:\n"," continue\n"," for fname in files:\n"," if fname.startswith('._'):\n"," continue\n"," if fname.lower().endswith(valid_exts):\n"," path = os.path.join(root, fname)\n"," try:\n"," with Image.open(path) as img:\n"," img.verify() # quick corruption check\n"," img = Image.open(path).convert('RGB') # reopen properly\n"," temp_slices = extract_vertical_slices(img, target_w, target_h, BORDER_COLOR)\n"," all_slices.extend(temp_slices)\n"," del img\n"," del temp_slices\n"," count += 1\n"," if count % 20 == 0:\n"," print(f\"Processed {count} images...\")\n"," gc.collect()\n"," except Exception as e:\n"," print(f\"Skip {fname}: {e}\")\n","\n","print(f\"\\nExtracted {len(all_slices)} vertical slices in total.\")\n","\n"," # ββββββββββββββββββββββββββββββββββββββββββββββββ\n"," # Frame composition settings (original location - not needed here anymore)\n"," # ββββββββββββββββββββββββββββββββββββββββββββββββ\n"," # FRAME_SIZE = 1024\n"," # BORDER_PX = 14\n"," # INNER_SIZE = FRAME_SIZE - 2 * BORDER_PX\n"," # num_vertical_panels = 4 #@param {type:\"slider\", min:1, max:12}\n"," # NUM_SLICES = num_vertical_panels\n"," # SLICE_WIDTH = INNER_SIZE // NUM_SLICES\n"," # target_w = SLICE_WIDTH # now we know it\n","\n","if len(all_slices) == 0:\n"," print(\"No slices β nothing to do.\")\n","else:\n"," output_dir = \"/content/vertical_slice_frames\"\n"," os.makedirs(output_dir, exist_ok=True)\n","\n"," frame_idx = 0\n"," while frame_idx < num_frames:\n"," k = min(NUM_SLICES, len(all_slices))\n"," group = random.sample(all_slices * 4, k)\n"," random.shuffle(group)\n","\n"," canvas = Image.new('RGB', (INNER_SIZE, INNER_SIZE), (0,0,0))\n"," for col in range(NUM_SLICES):\n"," crop = group[col % len(group)]\n"," canvas.paste(crop, (col * SLICE_WIDTH, 0))\n","\n"," final = Image.new('RGB', (FRAME_SIZE, FRAME_SIZE), BORDER_COLOR)\n"," final.paste(canvas, (BORDER_PX, BORDER_PX))\n","\n"," frame_idx += 1\n"," fname = f\"frame_{frame_idx:04d}.jpg\"\n"," final.save(os.path.join(output_dir, fname), \"JPEG\", quality=85) # lower quality = less disk/RAM pressure\n","\n"," del canvas, final\n"," if frame_idx % 50 == 0:\n"," print(f\"Saved {frame_idx}/{num_frames} frames...\")\n"," gc.collect()\n","\n"," print(f\"\\nCreated {frame_idx} frames in {output_dir}\")\n","\n"," # βββ Zip & save only to Drive βββ\n"," if save_to_google_drive and drive_mounted:\n"," timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n"," zip_name = f\"vertical_frames_{timestamp}.zip\"\n"," zip_path_local = f\"/content/{zip_name}\"\n","\n"," print(\"Creating zip...\")\n"," !zip -r -q \"{zip_path_local}\" \"{output_dir}\"\n","\n"," drive_zip_path = os.path.join(drive_output_dir, zip_name)\n"," print(\"Copying to Google Drive...\")\n"," !cp \"{zip_path_local}\" \"{drive_zip_path}\"\n","\n"," print(f\"\\nDone! Zip saved here:\")\n"," print(f\"β {drive_zip_path}\")\n","\n"," # Optional: clean up local files to free space\n"," # !rm -rf \"{output_dir}\" \"{zip_path_local}\"\n"," print(\"Local files kept in /content/ β you can delete them manually via Files panel.\")\n"," else:\n"," print(\"\\nNo save location active β frames are in /content/vertical_slice_frames but will be lost when runtime ends.\")"],"metadata":{"id":"eJLdI4TvcLyz"},"execution_count":null,"outputs":[]}],"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/LoRa_vertical_slice.ipynb","timestamp":1772923478843},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/LoRa_vertical_slice.ipynb","timestamp":1772831486007},{"file_id":"11rioWNojWzoPp-O4wZK97yjublkR9GtQ","timestamp":1772750616448},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1772741185417},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1763646205520},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/Drive to WebP.ipynb","timestamp":1760993725927},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1760450712160},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1756712618300},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1747490904984},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1740037333374},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1736477078136},{"file_id":"https://huggingface.co/codeShare/JupyterNotebooks/blob/main/YT-playlist-to-mp3.ipynb","timestamp":1725365086834}]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}
|