─░├žeri─če ge├ž

Referans i├žin ultralytics/utils/files.py

Not

Bu dosya https://github.com/ultralytics/ultralytics/blob/main/ ultralytics/utils/files .py adresinde mevcuttur. Bir sorun tespit ederseniz l├╝tfen bir ├çekme ─░ste─či ­čŤá´ŞĆ ile katk─▒da bulunarak d├╝zeltilmesine yard─▒mc─▒ olun. Te┼čekk├╝rler ­čÖĆ!



ultralytics.utils.files.WorkingDirectory

├ťsler: ContextDecorator

Kullan─▒m ┼čekli: @WorkingDirectory(dir) dekorat├Âr├╝ veya 'with WorkingDirectory(dir):' ba─člam y├Âneticisi.

Kaynak kodu ultralytics/utils/files.py
class WorkingDirectory(contextlib.ContextDecorator):
    """Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager."""

    def __init__(self, new_dir):
        """Sets the working directory to 'new_dir' upon instantiation."""
        self.dir = new_dir  # new dir
        self.cwd = Path.cwd().resolve()  # current dir

    def __enter__(self):
        """Changes the current directory to the specified directory."""
        os.chdir(self.dir)

    def __exit__(self, exc_type, exc_val, exc_tb):  # noqa
        """Restore the current working directory on context exit."""
        os.chdir(self.cwd)

__enter__()

Ge├žerli dizini belirtilen dizine de─či┼čtirir.

Kaynak kodu ultralytics/utils/files.py
def __enter__(self):
    """Changes the current directory to the specified directory."""
    os.chdir(self.dir)

__exit__(exc_type, exc_val, exc_tb)

Ba─člamdan ├ž─▒k─▒ld─▒─č─▒nda ge├žerli ├žal─▒┼čma dizinini geri y├╝kleyin.

Kaynak kodu ultralytics/utils/files.py
def __exit__(self, exc_type, exc_val, exc_tb):  # noqa
    """Restore the current working directory on context exit."""
    os.chdir(self.cwd)

__init__(new_dir)

├ľrnekleme s─▒ras─▒nda ├žal─▒┼čma dizinini 'new_dir' olarak ayarlar.

Kaynak kodu ultralytics/utils/files.py
def __init__(self, new_dir):
    """Sets the working directory to 'new_dir' upon instantiation."""
    self.dir = new_dir  # new dir
    self.cwd = Path.cwd().resolve()  # current dir



ultralytics.utils.files.spaces_in_path(path)

Adlar─▒nda bo┼čluk bulunan yollar─▒ i┼člemek i├žin ba─člam y├Âneticisi. Bir yol bo┼čluk i├žeriyorsa, bunlar─▒ dosyay─▒/dizini yeni yola kopyalar, ba─člam kod blo─čunu ├žal─▒┼čt─▒r─▒r ve ard─▒ndan dosya/dizini orijinal konumuna geri d├Ând├╝r├╝r.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
path str | Path

Orijinal yol.

gerekli

Verim:

Tip A├ž─▒klama
Path

Bo┼čluklar varsa alt ├žizgilerle de─či┼čtirilmi┼č ge├žici yol, aksi takdirde orijinal yol.

├ľrnek
with ultralytics.utils.files import spaces_in_path

with spaces_in_path('/path/with spaces') as new_path:
    # Your code here
Kaynak kodu ultralytics/utils/files.py
@contextmanager
def spaces_in_path(path):
    """
    Context manager to handle paths with spaces in their names. If a path contains spaces, it replaces them with
    underscores, copies the file/directory to the new path, executes the context code block, then copies the
    file/directory back to its original location.

    Args:
        path (str | Path): The original path.

    Yields:
        (Path): Temporary path with spaces replaced by underscores if spaces were present, otherwise the original path.

    Example:
        ```python
        with ultralytics.utils.files import spaces_in_path

        with spaces_in_path('/path/with spaces') as new_path:
            # Your code here
        ```
    """

    # If path has spaces, replace them with underscores
    if " " in str(path):
        string = isinstance(path, str)  # input type
        path = Path(path)

        # Create a temporary directory and construct the new path
        with tempfile.TemporaryDirectory() as tmp_dir:
            tmp_path = Path(tmp_dir) / path.name.replace(" ", "_")

            # Copy file/directory
            if path.is_dir():
                # tmp_path.mkdir(parents=True, exist_ok=True)
                shutil.copytree(path, tmp_path)
            elif path.is_file():
                tmp_path.parent.mkdir(parents=True, exist_ok=True)
                shutil.copy2(path, tmp_path)

            try:
                # Yield the temporary path
                yield str(tmp_path) if string else tmp_path

            finally:
                # Copy file/directory back
                if tmp_path.is_dir():
                    shutil.copytree(tmp_path, path, dirs_exist_ok=True)
                elif tmp_path.is_file():
                    shutil.copy2(tmp_path, path)  # Copy back the file

    else:
        # If there are no spaces, just yield the original path
        yield path



ultralytics.utils.files.increment_path(path, exist_ok=False, sep='', mkdir=False)

Bir dosya veya dizin yolunu art─▒r─▒r, ├Ârn. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... vb.

Yol mevcutsa ve exist_ok True olarak ayarlanmam─▒┼čsa, yol bir say─▒ ve sep eklenerek art─▒r─▒lacakt─▒r. yolun sonu. Yol bir dosya ise, dosya uzant─▒s─▒ korunacakt─▒r. Yol bir dizin ise numaras─▒ do─črudan yolun sonuna eklenecektir. E─čer mkdir True olarak ayarlan─▒rsa, yol bir dizininde zaten mevcut de─čilse.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
path (str, Path)

Art─▒┼ča giden yol.

gerekli
exist_ok bool

True ise, yol art─▒r─▒lmaz ve oldu─ču gibi d├Ând├╝r├╝l├╝r. Varsay─▒lan de─čer False'dir.

False
sep str

Yol ve art─▒┼č numaras─▒ aras─▒nda kullan─▒lacak ay─▒r─▒c─▒. Varsay─▒lan de─čer '' ┼čeklindedir.

''
mkdir bool

Mevcut de─čilse bir dizin olu┼čturun. Varsay─▒lan de─čer False'dir.

False

─░ade:

Tip A├ž─▒klama
Path

Art─▒r─▒lm─▒┼č yol.

Kaynak kodu ultralytics/utils/files.py
def increment_path(path, exist_ok=False, sep="", mkdir=False):
    """
    Increments a file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.

    If the path exists and exist_ok is not set to True, the path will be incremented by appending a number and sep to
    the end of the path. If the path is a file, the file extension will be preserved. If the path is a directory, the
    number will be appended directly to the end of the path. If mkdir is set to True, the path will be created as a
    directory if it does not already exist.

    Args:
        path (str, pathlib.Path): Path to increment.
        exist_ok (bool, optional): If True, the path will not be incremented and returned as-is. Defaults to False.
        sep (str, optional): Separator to use between the path and the incrementation number. Defaults to ''.
        mkdir (bool, optional): Create a directory if it does not exist. Defaults to False.

    Returns:
        (pathlib.Path): Incremented path.
    """
    path = Path(path)  # os-agnostic
    if path.exists() and not exist_ok:
        path, suffix = (path.with_suffix(""), path.suffix) if path.is_file() else (path, "")

        # Method 1
        for n in range(2, 9999):
            p = f"{path}{sep}{n}{suffix}"  # increment path
            if not os.path.exists(p):
                break
        path = Path(p)

    if mkdir:
        path.mkdir(parents=True, exist_ok=True)  # make directory

    return path



ultralytics.utils.files.file_age(path=__file__)

Son dosya g├╝ncellemesinden bu yana ge├žen g├╝nleri d├Ând├╝r├╝r.

Kaynak kodu ultralytics/utils/files.py
def file_age(path=__file__):
    """Return days since last file update."""
    dt = datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime)  # delta
    return dt.days  # + dt.seconds / 86400  # fractional days



ultralytics.utils.files.file_date(path=__file__)

─░nsan taraf─▒ndan okunabilir dosya de─či┼čiklik tarihi d├Ând├╝r├╝r, ├Ârne─čin '2021-3-26'.

Kaynak kodu ultralytics/utils/files.py
def file_date(path=__file__):
    """Return human-readable file modification date, i.e. '2021-3-26'."""
    t = datetime.fromtimestamp(Path(path).stat().st_mtime)
    return f"{t.year}-{t.month}-{t.day}"



ultralytics.utils.files.file_size(path)

Dosya/dir boyutunu d├Ând├╝r (MB).

Kaynak kodu ultralytics/utils/files.py
def file_size(path):
    """Return file/dir size (MB)."""
    if isinstance(path, (str, Path)):
        mb = 1 << 20  # bytes to MiB (1024 ** 2)
        path = Path(path)
        if path.is_file():
            return path.stat().st_size / mb
        elif path.is_dir():
            return sum(f.stat().st_size for f in path.glob("**/*") if f.is_file()) / mb
    return 0.0



ultralytics.utils.files.get_latest_run(search_dir='.')

/runs i├žindeki en son 'last.pt' dosyas─▒n─▒n yolunu d├Ând├╝r├╝r (yani --resume from).

Kaynak kodu ultralytics/utils/files.py
def get_latest_run(search_dir="."):
    """Return path to most recent 'last.pt' in /runs (i.e. to --resume from)."""
    last_list = glob.glob(f"{search_dir}/**/last*.pt", recursive=True)
    return max(last_list, key=os.path.getctime) if last_list else ""



ultralytics.utils.files.update_models(model_names=('yolov8n.pt'), source_dir=Path('.'), update_names=False)

Belirtilen YOLO modellerini bir 'updated_models' alt dizininde g├╝nceller ve yeniden kaydeder.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
model_names tuple

G├╝ncellenecek model dosya adlar─▒, varsay─▒lan de─čer ("yolov8n.pt").

('yolov8n.pt')
source_dir Path

Modelleri ve hedef alt dizini i├žeren dizin, varsay─▒lan olarak ge├žerli dizin.

Path('.')
update_names bool

Bir veri YAML'sinden model adlar─▒n─▒ g├╝ncelleyin.

False
├ľrnek
from ultralytics.utils.files import update_models

model_names = (f"rtdetr-{size}.pt" for size in "lx")
update_models(model_names)
Kaynak kodu ultralytics/utils/files.py
def update_models(model_names=("yolov8n.pt",), source_dir=Path("."), update_names=False):
    """
    Updates and re-saves specified YOLO models in an 'updated_models' subdirectory.

    Args:
        model_names (tuple, optional): Model filenames to update, defaults to ("yolov8n.pt").
        source_dir (Path, optional): Directory containing models and target subdirectory, defaults to current directory.
        update_names (bool, optional): Update model names from a data YAML.

    Example:
        ```python
        from ultralytics.utils.files import update_models

        model_names = (f"rtdetr-{size}.pt" for size in "lx")
        update_models(model_names)
        ```
    """
    from ultralytics import YOLO
    from ultralytics.nn.autobackend import default_class_names

    target_dir = source_dir / "updated_models"
    target_dir.mkdir(parents=True, exist_ok=True)  # Ensure target directory exists

    for model_name in model_names:
        model_path = source_dir / model_name
        print(f"Loading model from {model_path}")

        # Load model
        model = YOLO(model_path)
        model.half()
        if update_names:  # update model names from a dataset YAML
            model.model.names = default_class_names("coco8.yaml")

        # Define new save path
        save_path = target_dir / model_name

        # Save model using model.save()
        print(f"Re-saving {model_name} model to {save_path}")
        model.save(save_path, use_dill=False)





Created 2023-11-12, Updated 2024-06-02
Authors: glenn-jocher (6), Burhan-Q (1), Laughing-q (1)