codeShare commited on
Commit
33e0333
·
verified ·
1 Parent(s): cffe7c5

Upload tag_randomizer.ipynb

Browse files
Files changed (1) hide show
  1. tag_randomizer.ipynb +1 -1
tag_randomizer.ipynb CHANGED
@@ -1 +1 @@
1
- {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/tag_randomizer.ipynb","timestamp":1756665629195},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/tag_randomizer.ipynb","timestamp":1756583352986},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/tag_randomizer.ipynb","timestamp":1756465686090}],"authorship_tag":"ABX9TyM+i3seWqjEpfyz4moPXDqv"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"code","source":["import os\n","import random\n","import string\n","from google.colab import files\n","\n","# Create output directory if it doesn't exist\n","output_dir = '/content/output/'\n","os.makedirs(output_dir, exist_ok=True)\n","\n","# Upload text files\n","print(\"Please upload your text files:\")\n","uploaded = files.upload()\n","\n","# Process uploaded files\n","all_items = []\n","for filename, content in uploaded.items():\n"," if filename.endswith('.txt'):\n"," # Decode content and treat entire file content as one item, removing trailing whitespace\n"," file_content = content.decode('utf-8').rstrip()\n"," if file_content: # Only add non-empty content\n"," # Replace newlines with empty string\n"," file_content = file_content.replace('\\n', ' ')\n"," # Replace double quotes with single quotes\n"," file_content = file_content.replace('\"', \"'\")\n"," # Remove specified symbols: {}, [], ^\n"," for symbol in '{}[]^':\n"," file_content = file_content.replace(symbol, '')\n"," all_items.append(file_content)\n","\n","# Join items with '|' separator\n","combined_text = '|'.join(all_items)\n","\n","# Generate random filename (e.g., 8 characters long)\n","random_filename = ''.join(random.choices(string.ascii_lowercase + string.digits, k=8)) + '.txt'\n","output_path = os.path.join(output_dir, random_filename)\n","\n","# Write combined text to output file\n","with open(output_path, 'w') as f:\n"," f.write(combined_text)\n","\n","print(f\"Combined text saved to: {output_path}\")\n","print(f\"Content: {combined_text}\")\n","\n","# Optional: Display the output file content\n","with open(output_path, 'r') as f:\n"," print(f\"Verified content from file: {f.read()}\")"],"metadata":{"id":"rIBdbHYDhKvE"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Import required library\n","import random\n","\n","# Input text\n","input_text = 'A,B,C|D,E,F|G,H,I' #@param {type:'string'}\n","\n","# Split the text into groups\n","groups = input_text.split('|')\n","\n","# Randomize letters within each group\n","randomized_groups = []\n","for group in groups:\n"," letters = group.split(',')\n"," random.shuffle(letters)\n"," randomized_groups.append(','.join(letters))\n","\n","# Join the groups back together\n","output_text = '|'.join(randomized_groups)\n","\n","# Write to a text file\n","with open('randomized_output.txt', 'w') as file:\n"," file.write(output_text)\n","\n","# Print the result to verify\n","print(\"Randomized output:\", output_text)\n","\n","# Download the file in Colab\n","from google.colab import files\n","files.download('randomized_output.txt')"],"metadata":{"id":"XifDdzLoC-P2"},"execution_count":null,"outputs":[]}]}
 
1
+ {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/tag_randomizer.ipynb","timestamp":1758655941612},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/tag_randomizer.ipynb","timestamp":1756665629195},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/tag_randomizer.ipynb","timestamp":1756583352986},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/tag_randomizer.ipynb","timestamp":1756465686090}],"authorship_tag":"ABX9TyM6ZobxKmtJHV7qktFB4zbd"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"code","source":["import os\n","import random\n","import string\n","from google.colab import files\n","\n","# Create output directory if it doesn't exist\n","output_dir = '/content/output/'\n","os.makedirs(output_dir, exist_ok=True)\n","\n","# Upload text files\n","print(\"Please upload your text files:\")\n","uploaded = files.upload()\n","\n","# Process uploaded files\n","all_items = []\n","for filename, content in uploaded.items():\n"," if filename.endswith('.txt'):\n"," # Decode content and treat entire file content as one item, removing trailing whitespace\n"," file_content = content.decode('utf-8').rstrip()\n"," if file_content: # Only add non-empty content\n"," # Replace newlines with empty string\n"," file_content = file_content.replace('\\n', ' ')\n"," # Replace double quotes with single quotes\n"," file_content = file_content.replace('\"', \"'\")\n"," # Remove specified symbols: {}, [], ^\n"," for symbol in '{}[]^':\n"," file_content = file_content.replace(symbol, '')\n"," all_items.append(file_content)\n","\n","# Join items with '|' separator\n","combined_text = '|'.join(all_items)\n","\n","# Generate random filename (e.g., 8 characters long)\n","random_filename = ''.join(random.choices(string.ascii_lowercase + string.digits, k=8)) + '.txt'\n","output_path = os.path.join(output_dir, random_filename)\n","\n","# Write combined text to output file\n","with open(output_path, 'w') as f:\n"," f.write(combined_text)\n","\n","print(f\"Combined text saved to: {output_path}\")\n","print(f\"Content: {combined_text}\")\n","\n","# Optional: Display the output file content\n","with open(output_path, 'r') as f:\n"," print(f\"Verified content from file: {f.read()}\")"],"metadata":{"id":"rIBdbHYDhKvE"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Import required library\n","import random\n","\n","# Input text\n","input_text = 'A,B,C|D,E,F|G,H,I' #@param {type:'string'}\n","\n","# Split the text into groups\n","groups = input_text.split('|')\n","\n","# Randomize letters within each group\n","randomized_groups = []\n","for group in groups:\n"," letters = group.split(',')\n"," random.shuffle(letters)\n"," randomized_groups.append(','.join(letters))\n","\n","# Join the groups back together\n","output_text = '|'.join(randomized_groups)\n","\n","# Write to a text file\n","with open('randomized_output.txt', 'w') as file:\n"," file.write(output_text)\n","\n","# Print the result to verify\n","print(\"Randomized output:\", output_text)\n","\n","# Download the file in Colab\n","from google.colab import files\n","files.download('randomized_output.txt')"],"metadata":{"id":"XifDdzLoC-P2"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Install required libraries\n","!pip install pdf2image\n","!apt-get install poppler-utils\n","\n","from pdf2image import convert_from_path\n","from google.colab import files\n","import os\n","import zipfile\n","from datetime import datetime\n","\n","# Create output directory\n","output_dir = \"converted_pngs\"\n","if not os.path.exists(output_dir):\n"," os.makedirs(output_dir)\n","\n","# Upload PDF files\n","print(\"Please upload your PDF files:\")\n","uploaded = files.upload()\n","\n","# Convert PDFs to PNGs\n","for pdf_file in uploaded.keys():\n"," if pdf_file.lower().endswith('.pdf'):\n"," print(f\"Converting {pdf_file}...\")\n"," # Convert PDF to images with high quality (300 DPI)\n"," images = convert_from_path(pdf_file, dpi=300, fmt='png')\n","\n"," # Save each page as PNG\n"," pdf_name = os.path.splitext(pdf_file)[0]\n"," for i, image in enumerate(images):\n"," output_path = os.path.join(output_dir, f\"{pdf_name}_page_{i+1}.png\")\n"," image.save(output_path, 'PNG', quality=100)\n"," print(f\"Finished converting {pdf_file}\")\n","\n","# Create zip file\n","timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n","zip_filename = f\"converted_pngs_{timestamp}.zip\"\n","with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:\n"," for root, _, files_to_zip in os.walk(output_dir):\n"," for file_to_zip in files_to_zip:\n"," if file_to_zip.endswith('.png'):\n"," zipf.write(os.path.join(root, file_to_zip),\n"," os.path.join(\"converted_pngs\", file_to_zip))\n","\n","# Download the zip file\n","files.download(zip_filename)\n","\n","print(f\"All PNGs have been saved to {zip_filename} and download initiated.\")"],"metadata":{"id":"dUzHKM75ACOu","outputId":"a6276f7b-aa60-46e6-8c7c-cf30acaa4331","colab":{"base_uri":"https://localhost:8080/","height":491}},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Collecting pdf2image\n"," Downloading pdf2image-1.17.0-py3-none-any.whl.metadata (6.2 kB)\n","Requirement already satisfied: pillow in /usr/local/lib/python3.12/dist-packages (from pdf2image) (11.3.0)\n","Downloading pdf2image-1.17.0-py3-none-any.whl (11 kB)\n","Installing collected packages: pdf2image\n","Successfully installed pdf2image-1.17.0\n","Reading package lists... Done\n","Building dependency tree... Done\n","Reading state information... Done\n","The following NEW packages will be installed:\n"," poppler-utils\n","0 upgraded, 1 newly installed, 0 to remove and 38 not upgraded.\n","Need to get 186 kB of archives.\n","After this operation, 697 kB of additional disk space will be used.\n","Get:1 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 poppler-utils amd64 22.02.0-2ubuntu0.10 [186 kB]\n","Fetched 186 kB in 0s (1,139 kB/s)\n","Selecting previously unselected package poppler-utils.\n","(Reading database ... 126441 files and directories currently installed.)\n","Preparing to unpack .../poppler-utils_22.02.0-2ubuntu0.10_amd64.deb ...\n","Unpacking poppler-utils (22.02.0-2ubuntu0.10) ...\n","Setting up poppler-utils (22.02.0-2ubuntu0.10) ...\n","Processing triggers for man-db (2.10.2-1) ...\n","Please upload your PDF files:\n"]},{"output_type":"display_data","data":{"text/plain":["<IPython.core.display.HTML object>"],"text/html":["\n"," <input type=\"file\" id=\"files-0206a4d2-f6f4-4d7c-908b-7132bf2cb965\" name=\"files[]\" multiple disabled\n"," style=\"border:none\" />\n"," <output id=\"result-0206a4d2-f6f4-4d7c-908b-7132bf2cb965\">\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":{}}]}]}