From e2af5f3cea07eb445a68bf5457f08802d584443f Mon Sep 17 00:00:00 2001 From: Burhan <62214284+Burhan-Q@users.noreply.github.com> Date: Sat, 17 May 2025 11:06:35 -0400 Subject: [PATCH] Updates split ops to use `maxsplit` arg (#20514) Signed-off-by: Burhan <62214284+Burhan-Q@users.noreply.github.com> Co-authored-by: Laughing-q <1185102784@qq.com> Co-authored-by: Laughing <61612323+Laughing-q@users.noreply.github.com> Co-authored-by: Glenn Jocher --- docs/build_docs.py | 4 ++-- docs/en/guides/kfold-cross-validation.md | 2 +- ultralytics/cfg/__init__.py | 2 +- ultralytics/data/base.py | 2 +- ultralytics/data/loaders.py | 4 ++-- ultralytics/engine/exporter.py | 6 +++--- ultralytics/engine/trainer.py | 2 +- ultralytics/engine/validator.py | 2 +- ultralytics/hub/auth.py | 4 ++-- ultralytics/models/yolo/obb/val.py | 2 +- ultralytics/models/yolo/world/train.py | 2 +- ultralytics/models/yolo/yoloe/val.py | 6 +++--- ultralytics/solutions/streamlit_inference.py | 2 +- ultralytics/utils/__init__.py | 2 +- ultralytics/utils/checks.py | 10 +++++----- ultralytics/utils/downloads.py | 2 +- ultralytics/utils/export.py | 2 +- ultralytics/utils/plotting.py | 2 +- ultralytics/utils/triton.py | 2 +- 19 files changed, 30 insertions(+), 30 deletions(-) diff --git a/docs/build_docs.py b/docs/build_docs.py index 247ec99c..3e6d4055 100644 --- a/docs/build_docs.py +++ b/docs/build_docs.py @@ -108,7 +108,7 @@ def update_subdir_edit_links(subdir: str = "", docs_url: str = ""): # Find the anchor tag and update its href attribute a_tag = soup.find("a", {"class": "md-content__button md-icon"}) if a_tag and a_tag["title"] == "Edit this page": - a_tag["href"] = f"{docs_url}{a_tag['href'].split(subdir)[-1]}" + a_tag["href"] = f"{docs_url}{a_tag['href'].rpartition(subdir)[-1]}" # Write the updated HTML back to the file with open(html_file, "w", encoding="utf-8") as file: @@ -285,7 +285,7 @@ def remove_comments_and_empty_lines(content: str, file_type: str) -> str: for line in lines: # Only remove comments if they're not part of a URL if "//" in line and "http://" not in line and "https://" not in line: - processed_lines.append(line.split("//")[0]) + processed_lines.append(line.partition("//")[0]) else: processed_lines.append(line) content = "\n".join(processed_lines) diff --git a/docs/en/guides/kfold-cross-validation.md b/docs/en/guides/kfold-cross-validation.md index a42d67f6..a479b5a7 100644 --- a/docs/en/guides/kfold-cross-validation.md +++ b/docs/en/guides/kfold-cross-validation.md @@ -101,7 +101,7 @@ Without further ado, let's dive in! for line in lines: # classes for YOLO label uses integer at first position of each line - lbl_counter[int(line.split(" ")[0])] += 1 + lbl_counter[int(line.split(" ", 1)[0])] += 1 labels_df.loc[label.stem] = lbl_counter diff --git a/ultralytics/cfg/__init__.py b/ultralytics/cfg/__init__.py index 8988dc5b..fca8c6ff 100644 --- a/ultralytics/cfg/__init__.py +++ b/ultralytics/cfg/__init__.py @@ -311,7 +311,7 @@ def get_cfg(cfg: Union[str, Path, Dict, SimpleNamespace] = DEFAULT_CFG_DICT, ove if k in cfg and isinstance(cfg[k], (int, float)): cfg[k] = str(cfg[k]) if cfg.get("name") == "model": # assign model to 'name' arg - cfg["name"] = str(cfg.get("model", "")).split(".")[0] + cfg["name"] = str(cfg.get("model", "")).partition(".")[0] LOGGER.warning(f"'name=model' automatically updated to 'name={cfg['name']}'.") # Type and Value checks diff --git a/ultralytics/data/base.py b/ultralytics/data/base.py index 30d101ca..ed3c0e86 100644 --- a/ultralytics/data/base.py +++ b/ultralytics/data/base.py @@ -170,7 +170,7 @@ class BaseDataset(Dataset): # F += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib) else: raise FileNotFoundError(f"{self.prefix}{p} does not exist") - im_files = sorted(x.replace("/", os.sep) for x in f if x.split(".")[-1].lower() in IMG_FORMATS) + im_files = sorted(x.replace("/", os.sep) for x in f if x.rpartition(".")[-1].lower() in IMG_FORMATS) # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS]) # pathlib assert im_files, f"{self.prefix}No images found in {img_path}. {FORMATS_HELP_MSG}" except Exception as e: diff --git a/ultralytics/data/loaders.py b/ultralytics/data/loaders.py index 09277922..3214be13 100644 --- a/ultralytics/data/loaders.py +++ b/ultralytics/data/loaders.py @@ -353,7 +353,7 @@ class LoadImagesAndVideos: # Define files as images or videos images, videos = [], [] for f in files: - suffix = f.split(".")[-1].lower() # Get file extension without the dot and lowercase + suffix = f.rpartition(".")[-1].lower() # Get file extension without the dot and lowercase if suffix in IMG_FORMATS: images.append(f) elif suffix in VID_FORMATS: @@ -427,7 +427,7 @@ class LoadImagesAndVideos: else: # Handle image files (including HEIC) self.mode = "image" - if path.split(".")[-1].lower() == "heic": + if path.rpartition(".")[-1].lower() == "heic": # Load HEIC image using Pillow with pillow-heif check_requirements("pillow-heif") diff --git a/ultralytics/engine/exporter.py b/ultralytics/engine/exporter.py index 0812ac58..9789fac3 100644 --- a/ultralytics/engine/exporter.py +++ b/ultralytics/engine/exporter.py @@ -276,7 +276,7 @@ class Exporter: LOGGER.warning("TensorRT requires GPU export, automatically assigning device=0") self.args.device = "0" if fmt == "engine" and "dla" in str(self.args.device): # convert int/list to str first - dla = self.args.device.split(":")[-1] + dla = self.args.device.rsplit(":", 1)[-1] self.args.device = "0" # update device to "0" assert dla in {"0", "1"}, f"Expected self.args.device='dla:0' or 'dla:1, but got {self.args.device}." if imx and self.args.device is None and torch.cuda.is_available(): @@ -788,7 +788,7 @@ class Exporter: subprocess.run(cmd, check=True) # Remove debug files - pnnx_files = [x.split("=")[-1] for x in pnnx_args] + pnnx_files = [x.rsplit("=", 1)[-1] for x in pnnx_args] for f_debug in ("debug.bin", "debug.param", "debug2.bin", "debug2.param", *pnnx_files): Path(f_debug).unlink(missing_ok=True) @@ -1047,7 +1047,7 @@ class Exporter: "sudo apt-get install edgetpu-compiler", ): subprocess.run(c if is_sudo_available() else c.replace("sudo ", ""), shell=True, check=True) - ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1] + ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().rsplit(maxsplit=1)[-1] LOGGER.info(f"\n{prefix} starting export with Edge TPU compiler {ver}...") f = str(tflite_model).replace(".tflite", "_edgetpu.tflite") # Edge TPU model diff --git a/ultralytics/engine/trainer.py b/ultralytics/engine/trainer.py index 463afab7..8dcca565 100644 --- a/ultralytics/engine/trainer.py +++ b/ultralytics/engine/trainer.py @@ -578,7 +578,7 @@ class BaseTrainer: try: if self.args.task == "classify": data = check_cls_dataset(self.args.data) - elif self.args.data.split(".")[-1] in {"yaml", "yml"} or self.args.task in { + elif self.args.data.rsplit(".", 1)[-1] in {"yaml", "yml"} or self.args.task in { "detect", "segment", "pose", diff --git a/ultralytics/engine/validator.py b/ultralytics/engine/validator.py index 5ce63dc0..7f477a4e 100644 --- a/ultralytics/engine/validator.py +++ b/ultralytics/engine/validator.py @@ -175,7 +175,7 @@ class BaseValidator: self.args.batch = model.metadata.get("batch", 1) # export.py models default to batch-size 1 LOGGER.info(f"Setting batch={self.args.batch} input of shape ({self.args.batch}, 3, {imgsz}, {imgsz})") - if str(self.args.data).split(".")[-1] in {"yaml", "yml"}: + if str(self.args.data).rsplit(".", 1)[-1] in {"yaml", "yml"}: self.data = check_det_dataset(self.args.data) elif self.args.task == "classify": self.data = check_cls_dataset(self.args.data, split=self.args.split) diff --git a/ultralytics/hub/auth.py b/ultralytics/hub/auth.py index e428365a..ba6781d4 100644 --- a/ultralytics/hub/auth.py +++ b/ultralytics/hub/auth.py @@ -37,7 +37,7 @@ class Auth: verbose (bool): Enable verbose logging. """ # Split the input API key in case it contains a combined key_model and keep only the API key part - api_key = api_key.split("_")[0] + api_key = api_key.split("_", 1)[0] # Set API key attribute as value passed or SETTINGS API key if none passed self.api_key = api_key or SETTINGS.get("api_key", "") @@ -77,7 +77,7 @@ class Auth: for attempts in range(max_attempts): LOGGER.info(f"{PREFIX}Login. Attempt {attempts + 1} of {max_attempts}") input_key = getpass.getpass(f"Enter API key from {API_KEY_URL} ") - self.api_key = input_key.split("_")[0] # remove model id if present + self.api_key = input_key.split("_", 1)[0] # remove model id if present if self.authenticate(): return True raise ConnectionError(emojis(f"{PREFIX}Failed to authenticate ❌")) diff --git a/ultralytics/models/yolo/obb/val.py b/ultralytics/models/yolo/obb/val.py index e65a2a7a..5f080d20 100644 --- a/ultralytics/models/yolo/obb/val.py +++ b/ultralytics/models/yolo/obb/val.py @@ -252,7 +252,7 @@ class OBBValidator(DetectionValidator): merged_results = defaultdict(list) LOGGER.info(f"Saving merged predictions with DOTA format to {pred_merged_txt}...") for d in data: - image_id = d["image_id"].split("__")[0] + image_id = d["image_id"].split("__", 1)[0] pattern = re.compile(r"\d+___\d+") x, y = (int(c) for c in re.findall(pattern, d["image_id"])[0].split("___")) bbox, score, cls = d["rbox"], d["score"], d["category_id"] - 1 diff --git a/ultralytics/models/yolo/world/train.py b/ultralytics/models/yolo/world/train.py index 3c7c893e..4432777c 100644 --- a/ultralytics/models/yolo/world/train.py +++ b/ultralytics/models/yolo/world/train.py @@ -16,7 +16,7 @@ def on_pretrain_routine_end(trainer): """Callback to set up model classes and text encoder at the end of the pretrain routine.""" if RANK in {-1, 0}: # Set class names for evaluation - names = [name.split("/")[0] for name in list(trainer.test_loader.dataset.data["names"].values())] + names = [name.split("/", 1)[0] for name in list(trainer.test_loader.dataset.data["names"].values())] de_parallel(trainer.ema.ema).set_classes(names, cache_clip_model=False) diff --git a/ultralytics/models/yolo/yoloe/val.py b/ultralytics/models/yolo/yoloe/val.py index 3f7805a2..6574a138 100644 --- a/ultralytics/models/yolo/yoloe/val.py +++ b/ultralytics/models/yolo/yoloe/val.py @@ -47,7 +47,7 @@ class YOLOEDetectValidator(DetectionValidator): (torch.Tensor): Visual prompt embeddings with shape (1, num_classes, embed_dim). """ assert isinstance(model, YOLOEModel) - names = [name.split("/")[0] for name in list(dataloader.dataset.data["names"].values())] + names = [name.split("/", 1)[0] for name in list(dataloader.dataset.data["names"].values())] visual_pe = torch.zeros(len(names), model.model[-1].embed, device=self.device) cls_visual_num = torch.zeros(len(names)) @@ -140,7 +140,7 @@ class YOLOEDetectValidator(DetectionValidator): if trainer is not None: self.device = trainer.device model = trainer.ema.ema - names = [name.split("/")[0] for name in list(self.dataloader.dataset.data["names"].values())] + names = [name.split("/", 1)[0] for name in list(self.dataloader.dataset.data["names"].values())] if load_vp: LOGGER.info("Validate using the visual prompt.") @@ -164,7 +164,7 @@ class YOLOEDetectValidator(DetectionValidator): model = attempt_load_weights(model, device=self.device, inplace=True) model.eval().to(self.device) data = check_det_dataset(refer_data or self.args.data) - names = [name.split("/")[0] for name in list(data["names"].values())] + names = [name.split("/", 1)[0] for name in list(data["names"].values())] if load_vp: LOGGER.info("Validate using the visual prompt.") diff --git a/ultralytics/solutions/streamlit_inference.py b/ultralytics/solutions/streamlit_inference.py index 1fbbca66..58ca6152 100644 --- a/ultralytics/solutions/streamlit_inference.py +++ b/ultralytics/solutions/streamlit_inference.py @@ -130,7 +130,7 @@ class Inference: # Add dropdown menu for model selection available_models = [x.replace("yolo", "YOLO") for x in GITHUB_ASSETS_STEMS if x.startswith("yolo11")] if self.model_path: # If user provided the custom model, insert model without suffix as *.pt is added later - available_models.insert(0, self.model_path.split(".pt")[0]) + available_models.insert(0, self.model_path.split(".pt", 1)[0]) selected_model = self.st.sidebar.selectbox("Model", available_models) with self.st.spinner("Model is downloading..."): diff --git a/ultralytics/utils/__init__.py b/ultralytics/utils/__init__.py index 200cd519..52306002 100644 --- a/ultralytics/utils/__init__.py +++ b/ultralytics/utils/__init__.py @@ -1387,7 +1387,7 @@ def deprecation_warn(arg, new_arg=None): def clean_url(url): """Strip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt.""" url = Path(url).as_posix().replace(":/", "://") # Pathlib turns :// -> :/, as_posix() for Windows - return unquote(url).split("?")[0] # '%2F' to '/', split https://url.com/file.txt?auth + return unquote(url).split("?", 1)[0] # '%2F' to '/', split https://url.com/file.txt?auth def url2file(url): diff --git a/ultralytics/utils/checks.py b/ultralytics/utils/checks.py index 004f02dd..8bec3be0 100644 --- a/ultralytics/utils/checks.py +++ b/ultralytics/utils/checks.py @@ -73,7 +73,7 @@ def parse_requirements(file_path=ROOT.parent / "requirements.txt", package=""): for line in requires: line = line.strip() if line and not line.startswith("#"): - line = line.split("#")[0].strip() # ignore inline comments + line = line.partition("#")[0].strip() # ignore inline comments if match := re.match(r"([a-zA-Z0-9-_]+)\s*([<>!=~]+.*)?", line): requirements.append(SimpleNamespace(name=match[1], specifier=match[2].strip() if match[2] else "")) @@ -379,7 +379,7 @@ def check_requirements(requirements=ROOT.parent / "requirements.txt", exclude=() pkgs = [] for r in requirements: - r_stripped = r.split("/")[-1].replace(".git", "") # replace git+https://org/repo.git -> 'repo' + r_stripped = r.rpartition("/")[-1].replace(".git", "") # replace git+https://org/repo.git -> 'repo' match = re.match(r"([a-zA-Z0-9-_]+)([<>!=~]+.*)?", r_stripped) name, required = match[1], match[2].strip() if match[2] else "" try: @@ -436,10 +436,10 @@ def check_torchvision(): } # Check major and minor versions - v_torch = ".".join(torch.__version__.split("+")[0].split(".")[:2]) + v_torch = ".".join(torch.__version__.split("+", 1)[0].split(".")[:2]) if v_torch in compatibility_table: compatible_versions = compatibility_table[v_torch] - v_torchvision = ".".join(TORCHVISION_VERSION.split("+")[0].split(".")[:2]) + v_torchvision = ".".join(TORCHVISION_VERSION.split("+", 1)[0].split(".")[:2]) if all(v_torchvision != v for v in compatible_versions): LOGGER.warning( f"torchvision=={v_torchvision} is incompatible with torch=={v_torch}.\n" @@ -838,7 +838,7 @@ def cuda_device_count() -> int: ) # Take the first line and strip any leading/trailing white space - first_line = output.strip().split("\n")[0] + first_line = output.strip().split("\n", 1)[0] return int(first_line) except (subprocess.CalledProcessError, FileNotFoundError, ValueError): diff --git a/ultralytics/utils/downloads.py b/ultralytics/utils/downloads.py index b1b4a2ab..e96e3069 100644 --- a/ultralytics/utils/downloads.py +++ b/ultralytics/utils/downloads.py @@ -247,7 +247,7 @@ def get_google_drive_file_info(link): """ import requests # slow import - file_id = link.split("/d/")[1].split("/view")[0] + file_id = link.split("/d/")[1].split("/view", 1)[0] drive_url = f"https://drive.google.com/uc?export=download&id={file_id}" filename = None diff --git a/ultralytics/utils/export.py b/ultralytics/utils/export.py index ab18ca80..6738a929 100644 --- a/ultralytics/utils/export.py +++ b/ultralytics/utils/export.py @@ -97,7 +97,7 @@ def export_engine( builder = trt.Builder(logger) config = builder.create_builder_config() workspace = int((workspace or 0) * (1 << 30)) - is_trt10 = int(trt.__version__.split(".")[0]) >= 10 # is TensorRT >= 10 + is_trt10 = int(trt.__version__.split(".", 1)[0]) >= 10 # is TensorRT >= 10 if is_trt10 and workspace > 0: config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace) elif workspace > 0: # TensorRT versions 7, 8 diff --git a/ultralytics/utils/plotting.py b/ultralytics/utils/plotting.py index b412e887..d205102f 100644 --- a/ultralytics/utils/plotting.py +++ b/ultralytics/utils/plotting.py @@ -1000,7 +1000,7 @@ def feature_visualization(x, module_type, stage, n=32, save_dir=Path("runs/detec if isinstance(x, torch.Tensor): _, channels, height, width = x.shape # batch, channels, height, width if height > 1 and width > 1: - f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename + f = save_dir / f"stage{stage}_{module_type.rsplit('.', 1)[-1]}_features.png" # filename blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels n = min(n, channels) # number of plots diff --git a/ultralytics/utils/triton.py b/ultralytics/utils/triton.py index e1152401..0396874a 100644 --- a/ultralytics/utils/triton.py +++ b/ultralytics/utils/triton.py @@ -53,7 +53,7 @@ class TritonRemoteModel: """ if not endpoint and not scheme: # Parse all args from URL string splits = urlsplit(url) - endpoint = splits.path.strip("/").split("/")[0] + endpoint = splits.path.strip("/").split("/", 1)[0] scheme = splits.scheme url = splits.netloc