codeShare commited on
Commit
639b4a7
Β·
verified Β·
1 Parent(s): 57dd0bc

Upload LoRa_vertical_slice.ipynb

Browse files
Files changed (1) hide show
  1. LoRa_vertical_slice.ipynb +1 -1
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 = 500 #@param {type:\"slider\", min:1, max:500, step:1}\n","split_images_horizontally = True #@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_SLICES = 3\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":{"colab":{"base_uri":"https://localhost:8080/","height":1000},"id":"_kz2zIO12PQQ","executionInfo":{"status":"ok","timestamp":1772762872418,"user_tz":-60,"elapsed":128874,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"1185dc31-eb4f-488a-cbf9-a560d51004aa"},"execution_count":2,"outputs":[{"output_type":"stream","name":"stdout","text":["Upload your jpg, jpeg, png, webp or webm files\n"]},{"output_type":"display_data","data":{"text/plain":["<IPython.core.display.HTML object>"],"text/html":["\n"," <input type=\"file\" id=\"files-09366c9e-c94e-48be-acdd-ce7bb8857b6c\" name=\"files[]\" multiple disabled\n"," style=\"border:none\" />\n"," <output id=\"result-09366c9e-c94e-48be-acdd-ce7bb8857b6c\">\n"," Upload widget is only available when the cell has been executed in the\n"," current browser session. Please rerun this cell to enable.\n"," </output>\n"," <script>// Copyright 2017 Google LLC\n","//\n","// Licensed under the Apache License, Version 2.0 (the \"License\");\n","// you may not use this file except in compliance with the License.\n","// You may obtain a copy of the License at\n","//\n","// http://www.apache.org/licenses/LICENSE-2.0\n","//\n","// Unless required by applicable law or agreed to in writing, software\n","// distributed under the License is distributed on an \"AS IS\" BASIS,\n","// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n","// See the License for the specific language governing permissions and\n","// limitations under the License.\n","\n","/**\n"," * @fileoverview Helpers for google.colab Python module.\n"," */\n","(function(scope) {\n","function span(text, styleAttributes = {}) {\n"," const element = document.createElement('span');\n"," element.textContent = text;\n"," for (const key of Object.keys(styleAttributes)) {\n"," element.style[key] = styleAttributes[key];\n"," }\n"," return element;\n","}\n","\n","// Max number of bytes which will be uploaded at a time.\n","const MAX_PAYLOAD_SIZE = 100 * 1024;\n","\n","function _uploadFiles(inputId, outputId) {\n"," const steps = uploadFilesStep(inputId, outputId);\n"," const outputElement = document.getElementById(outputId);\n"," // Cache steps on the outputElement to make it available for the next call\n"," // to uploadFilesContinue from Python.\n"," outputElement.steps = steps;\n","\n"," return _uploadFilesContinue(outputId);\n","}\n","\n","// This is roughly an async generator (not supported in the browser yet),\n","// where there are multiple asynchronous steps and the Python side is going\n","// to poll for completion of each step.\n","// This uses a Promise to block the python side on completion of each step,\n","// then passes the result of the previous step as the input to the next step.\n","function _uploadFilesContinue(outputId) {\n"," const outputElement = document.getElementById(outputId);\n"," const steps = outputElement.steps;\n","\n"," const next = steps.next(outputElement.lastPromiseValue);\n"," return Promise.resolve(next.value.promise).then((value) => {\n"," // Cache the last promise value to make it available to the next\n"," // step of the generator.\n"," outputElement.lastPromiseValue = value;\n"," return next.value.response;\n"," });\n","}\n","\n","/**\n"," * Generator function which is called between each async step of the upload\n"," * process.\n"," * @param {string} inputId Element ID of the input file picker element.\n"," * @param {string} outputId Element ID of the output display.\n"," * @return {!Iterable<!Object>} Iterable of next steps.\n"," */\n","function* uploadFilesStep(inputId, outputId) {\n"," const inputElement = document.getElementById(inputId);\n"," inputElement.disabled = false;\n","\n"," const outputElement = document.getElementById(outputId);\n"," outputElement.innerHTML = '';\n","\n"," const pickedPromise = new Promise((resolve) => {\n"," inputElement.addEventListener('change', (e) => {\n"," resolve(e.target.files);\n"," });\n"," });\n","\n"," const cancel = document.createElement('button');\n"," inputElement.parentElement.appendChild(cancel);\n"," cancel.textContent = 'Cancel upload';\n"," const cancelPromise = new Promise((resolve) => {\n"," cancel.onclick = () => {\n"," resolve(null);\n"," };\n"," });\n","\n"," // Wait for the user to pick the files.\n"," const files = yield {\n"," promise: Promise.race([pickedPromise, cancelPromise]),\n"," response: {\n"," action: 'starting',\n"," }\n"," };\n","\n"," cancel.remove();\n","\n"," // Disable the input element since further picks are not allowed.\n"," inputElement.disabled = true;\n","\n"," if (!files) {\n"," return {\n"," response: {\n"," action: 'complete',\n"," }\n"," };\n"," }\n","\n"," for (const file of files) {\n"," const li = document.createElement('li');\n"," li.append(span(file.name, {fontWeight: 'bold'}));\n"," li.append(span(\n"," `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n"," `last modified: ${\n"," file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n"," 'n/a'} - `));\n"," const percent = span('0% done');\n"," li.appendChild(percent);\n","\n"," outputElement.appendChild(li);\n","\n"," const fileDataPromise = new Promise((resolve) => {\n"," const reader = new FileReader();\n"," reader.onload = (e) => {\n"," resolve(e.target.result);\n"," };\n"," reader.readAsArrayBuffer(file);\n"," });\n"," // Wait for the data to be ready.\n"," let fileData = yield {\n"," promise: fileDataPromise,\n"," response: {\n"," action: 'continue',\n"," }\n"," };\n","\n"," // Use a chunked sending to avoid message size limits. See b/62115660.\n"," let position = 0;\n"," do {\n"," const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n"," const chunk = new Uint8Array(fileData, position, length);\n"," position += length;\n","\n"," const base64 = btoa(String.fromCharCode.apply(null, chunk));\n"," yield {\n"," response: {\n"," action: 'append',\n"," file: file.name,\n"," data: base64,\n"," },\n"," };\n","\n"," let percentDone = fileData.byteLength === 0 ?\n"," 100 :\n"," Math.round((position / fileData.byteLength) * 100);\n"," percent.textContent = `${percentDone}% done`;\n","\n"," } while (position < fileData.byteLength);\n"," }\n","\n"," // All done.\n"," yield {\n"," response: {\n"," action: 'complete',\n"," }\n"," };\n","}\n","\n","scope.google = scope.google || {};\n","scope.google.colab = scope.google.colab || {};\n","scope.google.colab._files = {\n"," _uploadFiles,\n"," _uploadFilesContinue,\n","};\n","})(self);\n","</script> "]},"metadata":{}},{"output_type":"stream","name":"stdout","text":["Saving IMG_4523.webp to IMG_4523.webp\n","Saving IMG_4522.webp to IMG_4522.webp\n","Saving IMG_4521.webp to IMG_4521.webp\n","Saving IMG_4520.webp to IMG_4520.webp\n","Saving IMG_4519.webp to IMG_4519.webp\n","Saving IMG_4518.webp to IMG_4518.webp\n","Saving IMG_4517.webp to IMG_4517.webp\n","Saving IMG_4516.webp to IMG_4516.webp\n","Saving IMG_4515.webp to IMG_4515.webp\n","Saving IMG_4514.webp to IMG_4514.webp\n","Saving IMG_4513.webp to IMG_4513.webp\n","Saving IMG_4512.webp to IMG_4512.webp\n","Saving IMG_4511.webp to IMG_4511.webp\n","Saving IMG_4510.webp to IMG_4510.webp\n","Saving IMG_4509.webp to IMG_4509.webp\n","Saving IMG_4508.webp to IMG_4508.webp\n","Saving IMG_4507.webp to IMG_4507.webp\n","Saving IMG_4506.webp to IMG_4506.webp\n","Saving IMG_4505.webp to IMG_4505.webp\n","Saving IMG_4504.webp to IMG_4504.webp\n","Saving IMG_4503.webp to IMG_4503.webp\n","Saving IMG_4502.webp to IMG_4502.webp\n","Saving IMG_4501.webp to IMG_4501.webp\n","Saving IMG_4500.webp to IMG_4500.webp\n","Saving IMG_4499.webp to IMG_4499.webp\n","Saving IMG_4498.webp to IMG_4498.webp\n","Saving IMG_4497.webp to IMG_4497.webp\n","Saving IMG_4496.webp to IMG_4496.webp\n","Saving IMG_4495.webp to IMG_4495.webp\n","Saving IMG_4494.webp to IMG_4494.webp\n","Saving IMG_4493.webp to IMG_4493.webp\n","Saving IMG_4492.webp to IMG_4492.webp\n","Saving IMG_4491.webp to IMG_4491.webp\n","Saving IMG_4490.webp to IMG_4490.webp\n","Saving IMG_4489.webp to IMG_4489.webp\n","Saving IMG_4488.webp to IMG_4488.webp\n","Saving IMG_4487.webp to IMG_4487.webp\n","Saving IMG_4486.webp to IMG_4486.webp\n","Saving IMG_4485.webp to IMG_4485.webp\n","Saving IMG_4484.webp to IMG_4484.webp\n","Saving IMG_4483.webp to IMG_4483.webp\n","Saving IMG_4482.webp to IMG_4482.webp\n","Saving IMG_4481.webp to IMG_4481.webp\n","Saving IMG_4480.webp to IMG_4480.webp\n","Saving IMG_4479.webp to IMG_4479.webp\n","Saving IMG_4478.webp to IMG_4478.webp\n","Saving IMG_4477.webp to IMG_4477.webp\n","Saving IMG_4476.webp to IMG_4476.webp\n","Saving IMG_4475.webp to IMG_4475.webp\n","Saving IMG_4474.webp to IMG_4474.webp\n","Saving IMG_4473.webp to IMG_4473.webp\n","Saving IMG_4472.webp to IMG_4472.webp\n","Saving IMG_4471.webp to IMG_4471.webp\n","Saving IMG_4470.webp to IMG_4470.webp\n","Saving IMG_4469.webp to IMG_4469.webp\n","Saving IMG_4468.webp to IMG_4468.webp\n","Saving IMG_4467.webp to IMG_4467.webp\n","Saving IMG_4466.webp to IMG_4466.webp\n","Saving IMG_4465.webp to IMG_4465.webp\n","Saving IMG_4464.webp to IMG_4464.webp\n","Saving IMG_4463.webp to IMG_4463.webp\n","Saving IMG_4462.webp to IMG_4462.webp\n","Saving IMG_4461.webp to IMG_4461.webp\n","Saving IMG_4460.webp to IMG_4460.webp\n","Saving IMG_4459.webp to IMG_4459.webp\n","Saving IMG_4458.webp to IMG_4458.webp\n","Saving IMG_4457.webp to IMG_4457.webp\n","Saving IMG_4456.webp to IMG_4456.webp\n","Saving IMG_4455.webp to IMG_4455.webp\n","Saving IMG_4454.webp to IMG_4454.webp\n","Saving IMG_4453.webp to IMG_4453.webp\n","Saving IMG_4452.webp to IMG_4452.webp\n","Loaded 72 images\n","Splitting images horizontally (top + bottom half)...\n","β†’ Now working with 144 half-images\n","Extracted 576 vertical slices\n","Saved 50/500 frames...\n","Saved 100/500 frames...\n","Saved 150/500 frames...\n","Saved 200/500 frames...\n","Saved 250/500 frames...\n","Saved 300/500 frames...\n","Saved 350/500 frames...\n","Saved 400/500 frames...\n","Saved 450/500 frames...\n","Saved 500/500 frames...\n","\n","Done. Created 500 randomized frames in folder: /vertical_slice_frames\n"]},{"output_type":"display_data","data":{"text/plain":["<IPython.core.display.Javascript object>"],"application/javascript":["\n"," async function download(id, filename, size) {\n"," if (!google.colab.kernel.accessAllowed) {\n"," return;\n"," }\n"," const div = document.createElement('div');\n"," const label = document.createElement('label');\n"," label.textContent = `Downloading \"${filename}\": `;\n"," div.appendChild(label);\n"," const progress = document.createElement('progress');\n"," progress.max = size;\n"," div.appendChild(progress);\n"," document.body.appendChild(div);\n","\n"," const buffers = [];\n"," let downloaded = 0;\n","\n"," const channel = await google.colab.kernel.comms.open(id);\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n","\n"," for await (const message of channel.messages) {\n"," // Send a message to notify the kernel that we're ready.\n"," channel.send({})\n"," if (message.buffers) {\n"," for (const buffer of message.buffers) {\n"," buffers.push(buffer);\n"," downloaded += buffer.byteLength;\n"," progress.value = downloaded;\n"," }\n"," }\n"," }\n"," const blob = new Blob(buffers, {type: 'application/binary'});\n"," const a = document.createElement('a');\n"," a.href = window.URL.createObjectURL(blob);\n"," a.download = filename;\n"," div.appendChild(a);\n"," a.click();\n"," div.remove();\n"," }\n"," "]},"metadata":{}},{"output_type":"display_data","data":{"text/plain":["<IPython.core.display.Javascript object>"],"application/javascript":["download(\"download_f89903b8-f2f5-4744-a607-a353185c4aca\", \"vertical_frames.zip\", 173003232)"]},"metadata":{}}]}],"metadata":{"colab":{"provenance":[{"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":["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}