File size: 28,344 Bytes
827a4fd d45fe25 b47a9ae 827a4fd b47a9ae 827a4fd b47a9ae 827a4fd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 |
{
"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
}
|