File size: 2,239 Bytes
c388140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import os
from typing import List, Optional

from blockdiffusion.data.captions import CaptionItem


_IMG_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".bmp")


def _caption_from_filename(filename: str) -> str:
    """

    从文件名提取“弱标注提示词”。



    适配命名格式:

    - HASH-tag_tag_tag.png

    - HASH-side.png / HASH-top.png / HASH-bottom.png



    提取规则:

    - 去掉扩展名

    - 以第一个 '-' 作为分隔,取其后部分(若不存在 '-' 则使用全名)

    - '_' / '-' 统一当作空格

    """
    name = os.path.splitext(os.path.basename(filename))[0]
    if "-" in name:
        # 只切一次,避免 tag 本身含 '-' 时被过度切分
        _, tail = name.split("-", 1)
    else:
        tail = name
    tail = tail.replace("_", " ").replace("-", " ").strip().lower()
    # 多空格归一
    tail = " ".join([t for t in tail.split(" ") if t])
    return tail


def build_caption_items_from_filenames(

    root_dir: str,

    verbose: bool = False,

    log_every: int = 10_000,

) -> List[CaptionItem]:
    """

    扫描目录下所有图片(含子目录),用文件名自动生成 captions。

    返回 CaptionItem 列表,可直接用于 TextureCaptionDataset。

    """
    root_dir = os.path.abspath(root_dir)
    items: List[CaptionItem] = []
    seen = 0
    for dirpath, _, filenames in os.walk(root_dir):
        for fn in filenames:
            if not fn.lower().endswith(_IMG_EXTS):
                continue
            path = os.path.join(dirpath, fn)
            text = _caption_from_filename(fn)
            # 若提取失败就给空字符串;TextEncoder 会把空句子当作“无条件”
            items.append(CaptionItem(image_path=path, text=text))
            seen += 1
            if verbose and log_every > 0 and (seen % int(log_every) == 0):
                print(f"[scan] 已发现图片 {seen} 张...")
    items.sort(key=lambda x: x.image_path)
    if len(items) == 0:
        raise ValueError(f"目录下未找到图片:{root_dir}")
    if verbose:
        print(f"[scan] 完成:共 {len(items)} 张图片")
    return items