{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Download all the ETSI doucments from the website and extract the information from the documents." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "csv_path = 'ETSICatalog.csv'\n", "# load the CSV file\n", "df = pd.read_csv(csv_path, delimiter=';', skiprows=1, on_bad_lines='skip')\n" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index(['id', 'ETSI deliverable', 'title', 'Status', 'Details link', 'PDF link',\n", " 'Scope', 'Technical body', 'Keywords'],\n", " dtype='object')\n", " Number of rows: 26442\n" ] } ], "source": [ "print(df.columns)\n", "# get the number of rows and columns\n", "print(' Number of rows:', df.shape[0])" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "64372 Zero-touch network and Service Management\n", "63040 Zero-touch network and Service Management\n", "62010 Zero-touch network and Service Management\n", "61992 Zero-touch network and Service Management\n", "58436 Zero-touch network and Service Management\n", "Name: Scope, dtype: object\n" ] } ], "source": [ "# ge the 'PDF link' column from the dataframe and print first 5 rows\n", "pdf_links = df['Scope']\n", "print(pdf_links.head())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ " 8%|▊ | 2030/26442 [09:21<28:35:26, 4.22s/it]" ] } ], "source": [ "import os\n", "import requests\n", "from tqdm import tqdm\n", "import pandas as pd\n", "\n", "# Function to download files and save metadata, with pause and resume capability\n", "def download_etsi_documents(csv_path, download_dir, state_file='download_state.txt'):\n", " # Load the CSV file\n", " df = pd.read_csv(csv_path, delimiter=';', skiprows=1, on_bad_lines='skip', quotechar='\"')\n", " \n", " # Manually realign the columns\n", " corrected_rows = []\n", " for index, row in df.iterrows():\n", " corrected_row = {\n", " 'id': row['id'],\n", " 'ETSI deliverable': row['ETSI deliverable'],\n", " 'title': row['title'],\n", " 'Status': row['Status'],\n", " 'Details link': row['Details link'],\n", " 'PDF link': row['PDF link'],\n", " 'Scope': row['Scope'],\n", " 'Technical body': row['Technical body'],\n", " 'Keywords': row['Keywords']\n", " }\n", " \n", " # Correcting the misalignment\n", " corrected_row['PDF link'] = corrected_row['Details link']\n", " corrected_row['Details link'] = corrected_row['Status']\n", " corrected_row['Status'] = corrected_row['title']\n", " corrected_row['title'] = corrected_row['ETSI deliverable']\n", " corrected_row['ETSI deliverable'] = corrected_row['id']\n", " corrected_row['id'] = index # Reassigning ID to the index for unique identification\n", "\n", " corrected_rows.append(corrected_row)\n", "\n", " # Create a new DataFrame with the corrected rows\n", " corrected_df = pd.DataFrame(corrected_rows)\n", " \n", " # Create download directory if it doesn't exist\n", " os.makedirs(download_dir, exist_ok=True)\n", " \n", " # Load the state of downloaded documents\n", " if os.path.exists(state_file):\n", " with open(state_file, 'r') as file:\n", " completed_docs = set(file.read().splitlines())\n", " else:\n", " completed_docs = set()\n", " \n", " for index, row in tqdm(corrected_df.iterrows(), total=corrected_df.shape[0]):\n", " doc_id = str(row['id'])\n", " \n", " if doc_id in completed_docs:\n", " continue\n", " \n", " pdf_link = row['PDF link']\n", " title = row['ETSI deliverable']\n", " status = row['Status']\n", " details_link = row['Details link']\n", " scope = row['Scope']\n", " technical_body = row['Technical body']\n", " keywords = row['Keywords']\n", " \n", " try:\n", " response = requests.get(pdf_link, stream=True)\n", " if response.status_code == 200:\n", " file_path = os.path.join(download_dir, f\"{doc_id}.pdf\")\n", " with open(file_path, 'wb') as pdf_file:\n", " for chunk in response.iter_content(chunk_size=1024):\n", " if chunk:\n", " pdf_file.write(chunk)\n", " \n", " # Write metadata to a text file\n", " metadata_path = os.path.join(download_dir, f\"{doc_id}_metadata.txt\")\n", " with open(metadata_path, 'w') as metadata_file:\n", " metadata_file.write(f\"ID: {doc_id}\\n\")\n", " metadata_file.write(f\"Title: {title}\\n\")\n", " metadata_file.write(f\"Status: {status}\\n\")\n", " metadata_file.write(f\"Details Link: {details_link}\\n\")\n", " metadata_file.write(f\"Scope: {scope}\\n\")\n", " metadata_file.write(f\"Technical Body: {technical_body}\\n\")\n", " metadata_file.write(f\"Keywords: {keywords}\\n\")\n", " \n", " # Update the state file\n", " with open(state_file, 'a') as file:\n", " file.write(doc_id + '\\n')\n", " \n", " else:\n", " print(f\"Failed to download {pdf_link}\")\n", " except Exception as e:\n", " print(f\"Error downloading {pdf_link}: {e}\")\n", "\n", "# Example usage\n", "csv_path = 'ETSICatalog.csv'\n", "download_dir = './data/'\n", "download_etsi_documents(csv_path, download_dir) # Uncomment to execute\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# import os\n", "# import shutil\n", "# from math import ceil\n", "# from collections import defaultdict\n", "\n", "# def flatten_directory(root_dir):\n", "# \"\"\"\n", "# Moves all files from subdirectories into the root_dir.\n", "# \"\"\"\n", "# print(f\"Flattening directory: {root_dir}\")\n", "# for subdir, dirs, files in os.walk(root_dir):\n", "# # Skip the root directory itself\n", "# if subdir == root_dir:\n", "# continue\n", "# for file in files:\n", "# src_path = os.path.join(subdir, file)\n", "# dest_path = os.path.join(root_dir, file)\n", " \n", "# # Handle potential filename conflicts\n", "# if os.path.exists(dest_path):\n", "# base, extension = os.path.splitext(file)\n", "# count = 1\n", "# new_filename = f\"{base}_{count}{extension}\"\n", "# dest_path = os.path.join(root_dir, new_filename)\n", "# while os.path.exists(dest_path):\n", "# count += 1\n", "# new_filename = f\"{base}_{count}{extension}\"\n", "# dest_path = os.path.join(root_dir, new_filename)\n", "# print(f\"Filename conflict for '{file}'. Renamed to '{new_filename}'.\")\n", " \n", "# shutil.move(src_path, dest_path)\n", "# print(f\"Moved: {src_path} -> {dest_path}\")\n", " \n", "# # Remove the empty subdirectory after moving files\n", "# try:\n", "# os.rmdir(subdir)\n", "# print(f\"Removed empty directory: {subdir}\")\n", "# except OSError:\n", "# print(f\"Directory not empty, cannot remove: {subdir}\")\n", "\n", "# def group_files(root_dir):\n", "# \"\"\"\n", "# Groups files by their base name (without extension or metadata suffix).\n", "# Returns a dictionary where each key is a base name and the value is a list of associated files.\n", "# \"\"\"\n", "# print(\"Grouping files by base name.\")\n", "# files = os.listdir(root_dir)\n", "# groups = defaultdict(list)\n", " \n", "# for file in files:\n", "# if os.path.isfile(os.path.join(root_dir, file)):\n", "# if file.endswith('_metadata.txt'):\n", "# base_name = file.replace('_metadata.txt', '')\n", "# else:\n", "# base_name = os.path.splitext(file)[0]\n", "# groups[base_name].append(file)\n", " \n", "# print(f\"Total groups found: {len(groups)}\")\n", "# return groups\n", "\n", "# def split_groups_into_parts(groups, num_parts=3, max_files_per_dir=10000):\n", "# \"\"\"\n", "# Splits groups into specified number of parts without exceeding the maximum number of files per directory.\n", "# Each group is assumed to have multiple files (e.g., PDF and metadata).\n", "# Returns a list of lists, where each sublist contains group keys assigned to that part.\n", "# \"\"\"\n", "# print(f\"Splitting {len(groups)} groups into {num_parts} parts with up to {max_files_per_dir} files each.\")\n", " \n", "# # Each group has 2 files (PDF and metadata)\n", "# max_groups_per_dir = max_files_per_dir // 2\n", "# total_groups = len(groups)\n", "# groups_per_part = ceil(total_groups / num_parts)\n", " \n", "# parts = []\n", "# group_keys = list(groups.keys())\n", " \n", "# for i in range(num_parts):\n", "# start_index = i * groups_per_part\n", "# end_index = start_index + groups_per_part\n", "# part = group_keys[start_index:end_index]\n", "# parts.append(part)\n", "# print(f\"Part {i+1}: {len(part)} groups\")\n", " \n", "# return parts\n", "\n", "# def move_groups_to_subdirectories(root_dir, groups, parts):\n", "# \"\"\"\n", "# Moves groups of files into their respective subdirectories.\n", "# \"\"\"\n", "# for idx, part in enumerate(parts, start=1):\n", "# part_dir = os.path.join(root_dir, f\"part{idx}\")\n", "# os.makedirs(part_dir, exist_ok=True)\n", "# print(f\"Moving {len(part)} groups to '{part_dir}'\")\n", " \n", "# for group_key in part:\n", "# for file in groups[group_key]:\n", "# src_path = os.path.join(root_dir, file)\n", "# dest_path = os.path.join(part_dir, file)\n", " \n", "# # Handle potential filename conflicts (unlikely if grouped correctly)\n", "# if os.path.exists(dest_path):\n", "# base, extension = os.path.splitext(file)\n", "# count = 1\n", "# new_filename = f\"{base}_{count}{extension}\"\n", "# dest_path = os.path.join(part_dir, new_filename)\n", "# while os.path.exists(dest_path):\n", "# count += 1\n", "# new_filename = f\"{base}_{count}{extension}\"\n", "# dest_path = os.path.join(part_dir, new_filename)\n", "# print(f\"Filename conflict in part{idx} for '{file}'. Renamed to '{new_filename}'.\")\n", " \n", "# shutil.move(src_path, dest_path)\n", "# print(f\"Moved: {src_path} -> {dest_path}\")\n", " \n", "# print(f\"Completed moving to '{part_dir}'\\n\")\n", "\n", "# def main():\n", "# # Define the root data directory\n", "# root_dir = os.path.join(os.getcwd(), \"data\")\n", " \n", "# if not os.path.exists(root_dir):\n", "# print(f\"The directory '{root_dir}' does not exist.\")\n", "# return\n", " \n", "# # Step 1: Flatten the directory structure\n", "# flatten_directory(root_dir)\n", " \n", "# # # Step 2: Group files by base name\n", "# # groups = group_files(root_dir)\n", " \n", "# # # Step 3: Determine the number of parts based on total files and git limit\n", "# # # Git allows up to 10,000 files per directory, and each group has 2 files\n", "# # # So, max groups per directory = 10,000 / 2 = 5,000\n", "# # # Calculate the required number of parts\n", "# # total_groups = len(groups)\n", "# # max_groups_per_dir = 5000 # Each group has 2 files\n", "# # num_parts = ceil(total_groups / max_groups_per_dir)\n", " \n", "# # print(f\"Number of parts needed: {num_parts}\")\n", " \n", "# # # Adjust num_parts if you want to limit the number of parts (e.g., 3)\n", "# # # Uncomment the following lines if you prefer a fixed number of parts\n", "# # # desired_num_parts = 3\n", "# # # num_parts = ceil(total_groups / max_groups_per_dir)\n", "# # # num_parts = max(desired_num_parts, num_parts)\n", " \n", "# # # Step 4: Split groups into parts\n", "# # parts = split_groups_into_parts(groups, num_parts=num_parts, max_files_per_dir=10000)\n", " \n", "# # # Step 5: Move groups to their respective subdirectories\n", "# # move_groups_to_subdirectories(root_dir, groups, parts)\n", " \n", "# # print(\"All groups have been successfully moved into their respective subdirectories.\")\n", "\n", "# if __name__ == \"__main__\":\n", "# main()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 📁 Organize ETSI Documents by Working Group\n", "\n", "This script automates the organization of ETSI (European Telecommunications Standards Institute) documents and their corresponding metadata into dedicated folders based on their **Working Group** classifications. By categorizing files this way, you maintain a structured directory that adheres to Git's file limit constraints and enhances data manageability.\n", "\n", "## 🔍 Overview\n", "\n", "- **Input Files**:\n", " - **CSV File**: `Grouped_ETSI_Documents_with_Document_Number_by_Working_Group.csv`\n", " - **Columns**:\n", " - `Document_Number`: Unique identifier for each document.\n", " - `Working_Group`: Designates the working group (e.g., `GR`, `GS`).\n", " - `Concept`: Description of the document.\n", " - `ID`: Full ETSI deliverable ID.\n", " - **Data Directory**: `data/`\n", " - Contains all PDF files and their corresponding metadata files (e.g., `64372.pdf` and `64372_metadata.txt`).\n", "\n", "- **Output**:\n", " - Organized `data/` directory with subfolders for each **Working Group** (e.g., `GR`, `GS`).\n", " - Each subfolder contains the relevant PDF files and their metadata files.\n", "\n", "## 🛠️ Prerequisites\n", "\n", "- **Python 3.x**: Ensure Python is installed on your system.\n", "- **Python Packages**:\n", " - `pandas`: For handling CSV data.\n", " - `tqdm`: For displaying progress bars.\n", "- **Files**:\n", " - `Grouped_ETSI_Documents_with_Document_Number_by_Working_Group.csv`\n", " - `data/` directory with all relevant PDF and metadata files.\n", "\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Organizing Documents: 100%|██████████| 26442/26442 [00:16<00:00, 1641.14it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Some files were missing or could not be moved. Check 'missing_files.log' for details.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "import os\n", "import shutil\n", "import pandas as pd\n", "from tqdm import tqdm\n", "import logging\n", "\n", "# Configure logging\n", "logging.basicConfig(\n", " filename='organize_by_working_group.log',\n", " level=logging.INFO,\n", " format='%(asctime)s - %(levelname)s - %(message)s'\n", ")\n", "\n", "def read_csv_mapping(csv_path):\n", " \"\"\"\n", " Reads the CSV file and returns a DataFrame with necessary columns.\n", " \"\"\"\n", " try:\n", " df = pd.read_csv(csv_path)\n", " required_columns = ['Document_Number', 'Working_Group', 'Concept', 'ID']\n", " if not all(col in df.columns for col in required_columns):\n", " missing = list(set(required_columns) - set(df.columns))\n", " raise ValueError(f\"CSV file is missing columns: {missing}\")\n", " return df\n", " except Exception as e:\n", " logging.error(f\"Error reading CSV file: {e}\")\n", " print(f\"Error reading CSV file: {e}\")\n", " exit(1)\n", "\n", "def validate_files(root_dir, doc_number):\n", " \"\"\"\n", " Checks if the PDF and metadata files exist for a given Document_Number.\n", " Returns a tuple of (pdf_path, metadata_path) or (None, None) if missing.\n", " \"\"\"\n", " pdf_filename = f\"{doc_number}.pdf\"\n", " metadata_filename = f\"{doc_number}_metadata.txt\"\n", " pdf_path = os.path.join(root_dir, pdf_filename)\n", " metadata_path = os.path.join(root_dir, metadata_filename)\n", " \n", " pdf_exists = os.path.isfile(pdf_path)\n", " metadata_exists = os.path.isfile(metadata_path)\n", " \n", " return (pdf_path if pdf_exists else None, metadata_path if metadata_exists else None)\n", "\n", "def organize_documents(df, root_dir, log_file='missing_files.log'):\n", " \"\"\"\n", " Organizes documents into Working Group folders based on the DataFrame.\n", " \"\"\"\n", " missing_files = []\n", " \n", " # Iterate over each row with progress bar\n", " for index, row in tqdm(df.iterrows(), total=df.shape[0], desc=\"Organizing Documents\"):\n", " doc_number = str(row['Document_Number']).strip()\n", " working_group = str(row['Working_Group']).strip()\n", " \n", " pdf_path, metadata_path = validate_files(root_dir, doc_number)\n", " \n", " if not pdf_path and not metadata_path:\n", " missing_files.append((doc_number, 'Both PDF and metadata files are missing.'))\n", " logging.warning(f\"Document_Number {doc_number}: Both PDF and metadata files are missing.\")\n", " continue\n", " elif not pdf_path:\n", " missing_files.append((doc_number, 'PDF file is missing.'))\n", " logging.warning(f\"Document_Number {doc_number}: PDF file is missing.\")\n", " elif not metadata_path:\n", " missing_files.append((doc_number, 'Metadata file is missing.'))\n", " logging.warning(f\"Document_Number {doc_number}: Metadata file is missing.\")\n", " \n", " # Only proceed if both files exist\n", " if pdf_path and metadata_path:\n", " # Define destination directory\n", " dest_dir = os.path.join(root_dir, working_group)\n", " os.makedirs(dest_dir, exist_ok=True)\n", " \n", " # Define destination file paths\n", " dest_pdf = os.path.join(dest_dir, os.path.basename(pdf_path))\n", " dest_metadata = os.path.join(dest_dir, os.path.basename(metadata_path))\n", " \n", " # Handle potential filename conflicts\n", " if os.path.exists(dest_pdf):\n", " base, extension = os.path.splitext(os.path.basename(pdf_path))\n", " count = 1\n", " new_pdf_filename = f\"{base}_{count}{extension}\"\n", " dest_pdf = os.path.join(dest_dir, new_pdf_filename)\n", " while os.path.exists(dest_pdf):\n", " count += 1\n", " new_pdf_filename = f\"{base}_{count}{extension}\"\n", " dest_pdf = os.path.join(dest_dir, new_pdf_filename)\n", " logging.info(f\"Filename conflict for PDF '{base}.pdf'. Renamed to '{new_pdf_filename}'.\")\n", " \n", " if os.path.exists(dest_metadata):\n", " base, extension = os.path.splitext(os.path.basename(metadata_path))\n", " count = 1\n", " new_metadata_filename = f\"{base}_{count}{extension}\"\n", " dest_metadata = os.path.join(dest_dir, new_metadata_filename)\n", " while os.path.exists(dest_metadata):\n", " count += 1\n", " new_metadata_filename = f\"{base}_{count}{extension}\"\n", " dest_metadata = os.path.join(dest_dir, new_metadata_filename)\n", " logging.info(f\"Filename conflict for metadata '{base}_metadata.txt'. Renamed to '{new_metadata_filename}'.\")\n", " \n", " try:\n", " shutil.move(pdf_path, dest_pdf)\n", " shutil.move(metadata_path, dest_metadata)\n", " logging.info(f\"Moved Document_Number {doc_number} to {dest_dir}\")\n", " except Exception as e:\n", " missing_files.append((doc_number, f'Error moving files: {e}'))\n", " logging.error(f\"Document_Number {doc_number}: Error moving files: {e}\")\n", " \n", " # Log missing files\n", " if missing_files:\n", " with open(log_file, 'w') as f:\n", " for doc_num, message in missing_files:\n", " f.write(f\"Document_Number {doc_num}: {message}\\n\")\n", " print(f\"\\nSome files were missing or could not be moved. Check '{log_file}' for details.\")\n", " logging.info(f\"Organization completed with missing files. See {log_file} for details.\")\n", " else:\n", " print(\"\\nAll files have been successfully organized.\")\n", " logging.info(\"Organization completed successfully with no missing files.\")\n", "\n", "def main():\n", " # Configuration\n", " csv_path = 'Grouped_ETSI_Documents_with_Document_Number_by_Working_Group.csv' # Path to your CSV file\n", " root_dir = os.path.join(os.getcwd(), 'data') # Ensure this is the correct path\n", " log_file = 'missing_files.log' # Log file for missing or failed moves\n", " \n", " # Check if root_dir exists\n", " if not os.path.exists(root_dir):\n", " logging.error(f\"The directory '{root_dir}' does not exist.\")\n", " print(f\"The directory '{root_dir}' does not exist.\")\n", " exit(1)\n", " \n", " # Step 1: Read CSV mapping\n", " df = read_csv_mapping(csv_path)\n", " \n", " # Step 2: Organize documents\n", " organize_documents(df, root_dir, log_file)\n", "\n", "if __name__ == \"__main__\":\n", " main()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 📂 Function: `split_groups_into_parts`\n", "\n", "The `split_groups_into_parts` function is designed to divide a large set of file groups into smaller subsets. This is particularly useful for managing repositories with file system limitations, such as Git's restriction on the maximum number of files per directory.\n", "\n", "#### 🔍 **Purpose**\n", "\n", "- **Objective**: Split a collection of file groups into a specified number of parts without exceeding a defined maximum number of files per directory.\n", "- **Use Case**: Ensuring that no single directory contains more than 10,000 files, thereby adhering to repository constraints and maintaining optimal performance.\n", "\n", "#### 🛠️ **Function Signature**\n", "\n", "```python\n", "def split_groups_into_parts(groups, num_parts=3, max_files_per_dir=10000):\n", " \"\"\"\n", " Splits groups into specified number of parts without exceeding the maximum number of files per directory.\n", " Each group is assumed to have multiple files (e.g., PDF and metadata).\n", " Returns a list of lists, where each sublist contains group keys assigned to that part.\n", " \"\"\"\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Moved files 1 to 10000 into 'batch_1'\n", "Moved files 10001 to 20000 into 'batch_2'\n", "Moved files 20001 to 30000 into 'batch_3'\n", "Moved files 30001 to 35382 into 'batch_4'\n" ] } ], "source": [ "import os\n", "import shutil\n", "from math import ceil\n", "\n", "def split_directory(root_dir, max_files=10000, batch_size=1000):\n", " \"\"\"\n", " Splits a directory into subdirectories with a maximum number of files each.\n", "\n", " :param root_dir: Path to the directory to split.\n", " :param max_files: Maximum number of files per subdirectory.\n", " :param batch_size: Number of files to move per subdirectory.\n", " \"\"\"\n", " files = [f for f in os.listdir(root_dir) if os.path.isfile(os.path.join(root_dir, f))]\n", " total_files = len(files)\n", " total_subdirs = ceil(total_files / max_files)\n", " \n", " for i in range(total_subdirs):\n", " subdir_name = f\"batch_{i+1}\"\n", " subdir_path = os.path.join(root_dir, subdir_name)\n", " os.makedirs(subdir_path, exist_ok=True)\n", " \n", " start_index = i * max_files\n", " end_index = start_index + max_files\n", " batch_files = files[start_index:end_index]\n", " \n", " for file in batch_files:\n", " src_path = os.path.join(root_dir, file)\n", " dest_path = os.path.join(subdir_path, file)\n", " shutil.move(src_path, dest_path)\n", " \n", " print(f\"Moved files {start_index +1} to {min(end_index, total_files)} into '{subdir_name}'\")\n", "\n", "# Usage\n", "split_directory('./data/TS/', max_files=10000, batch_size=1000)\n" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 4 }