NguyenDinhHieu commited on
Commit
acd278f
·
verified ·
1 Parent(s): 24203aa

Sync pipeline package (EquiFashionDB_pipeline)

Browse files
Files changed (35) hide show
  1. EquiFashionDB_pipeline/__pycache__/__init__.cpython-312.pyc +0 -0
  2. EquiFashionDB_pipeline/__pycache__/__init__.cpython-313.pyc +0 -0
  3. EquiFashionDB_pipeline/__pycache__/__main__.cpython-312.pyc +0 -0
  4. EquiFashionDB_pipeline/__pycache__/__main__.cpython-313.pyc +0 -0
  5. EquiFashionDB_pipeline/__pycache__/config.cpython-312.pyc +0 -0
  6. EquiFashionDB_pipeline/__pycache__/config.cpython-313.pyc +0 -0
  7. EquiFashionDB_pipeline/__pycache__/dedup.cpython-312.pyc +0 -0
  8. EquiFashionDB_pipeline/__pycache__/dedup.cpython-313.pyc +0 -0
  9. EquiFashionDB_pipeline/__pycache__/ingest.cpython-312.pyc +0 -0
  10. EquiFashionDB_pipeline/__pycache__/ingest.cpython-313.pyc +0 -0
  11. EquiFashionDB_pipeline/__pycache__/package.cpython-312.pyc +0 -0
  12. EquiFashionDB_pipeline/__pycache__/package.cpython-313.pyc +0 -0
  13. EquiFashionDB_pipeline/__pycache__/pose_unify.cpython-312.pyc +0 -0
  14. EquiFashionDB_pipeline/__pycache__/pose_unify.cpython-313.pyc +0 -0
  15. EquiFashionDB_pipeline/__pycache__/pose_vis.cpython-312.pyc +0 -0
  16. EquiFashionDB_pipeline/__pycache__/pose_vis.cpython-313.pyc +0 -0
  17. EquiFashionDB_pipeline/__pycache__/quality.cpython-312.pyc +0 -0
  18. EquiFashionDB_pipeline/__pycache__/quality.cpython-313.pyc +0 -0
  19. EquiFashionDB_pipeline/__pycache__/runner.cpython-312.pyc +0 -0
  20. EquiFashionDB_pipeline/__pycache__/runner.cpython-313.pyc +0 -0
  21. EquiFashionDB_pipeline/__pycache__/sketch_fabric.cpython-312.pyc +0 -0
  22. EquiFashionDB_pipeline/__pycache__/sketch_fabric.cpython-313.pyc +0 -0
  23. EquiFashionDB_pipeline/__pycache__/standardize.cpython-312.pyc +0 -0
  24. EquiFashionDB_pipeline/__pycache__/standardize.cpython-313.pyc +0 -0
  25. EquiFashionDB_pipeline/__pycache__/taxonomy.cpython-312.pyc +0 -0
  26. EquiFashionDB_pipeline/__pycache__/taxonomy.cpython-313.pyc +0 -0
  27. EquiFashionDB_pipeline/__pycache__/text_noise.cpython-312.pyc +0 -0
  28. EquiFashionDB_pipeline/__pycache__/text_noise.cpython-313.pyc +0 -0
  29. EquiFashionDB_pipeline/config.py +187 -166
  30. EquiFashionDB_pipeline/defaults.yaml +40 -50
  31. EquiFashionDB_pipeline/ingest.py +54 -9
  32. EquiFashionDB_pipeline/package.py +46 -53
  33. EquiFashionDB_pipeline/runner.py +310 -282
  34. EquiFashionDB_pipeline/sketch_fabric.py +3 -72
  35. EquiFashionDB_pipeline/standardize.py +15 -1
EquiFashionDB_pipeline/__pycache__/__init__.cpython-312.pyc CHANGED
Binary files a/EquiFashionDB_pipeline/__pycache__/__init__.cpython-312.pyc and b/EquiFashionDB_pipeline/__pycache__/__init__.cpython-312.pyc differ
 
EquiFashionDB_pipeline/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (191 Bytes). View file
 
EquiFashionDB_pipeline/__pycache__/__main__.cpython-312.pyc ADDED
Binary file (271 Bytes). View file
 
EquiFashionDB_pipeline/__pycache__/__main__.cpython-313.pyc ADDED
Binary file (273 Bytes). View file
 
EquiFashionDB_pipeline/__pycache__/config.cpython-312.pyc ADDED
Binary file (11.1 kB). View file
 
EquiFashionDB_pipeline/__pycache__/config.cpython-313.pyc ADDED
Binary file (11.5 kB). View file
 
EquiFashionDB_pipeline/__pycache__/dedup.cpython-312.pyc ADDED
Binary file (3.56 kB). View file
 
EquiFashionDB_pipeline/__pycache__/dedup.cpython-313.pyc ADDED
Binary file (3.58 kB). View file
 
EquiFashionDB_pipeline/__pycache__/ingest.cpython-312.pyc ADDED
Binary file (5.84 kB). View file
 
EquiFashionDB_pipeline/__pycache__/ingest.cpython-313.pyc ADDED
Binary file (6.05 kB). View file
 
EquiFashionDB_pipeline/__pycache__/package.cpython-312.pyc ADDED
Binary file (2.37 kB). View file
 
EquiFashionDB_pipeline/__pycache__/package.cpython-313.pyc ADDED
Binary file (2.41 kB). View file
 
EquiFashionDB_pipeline/__pycache__/pose_unify.cpython-312.pyc ADDED
Binary file (2.43 kB). View file
 
EquiFashionDB_pipeline/__pycache__/pose_unify.cpython-313.pyc ADDED
Binary file (2.43 kB). View file
 
EquiFashionDB_pipeline/__pycache__/pose_vis.cpython-312.pyc ADDED
Binary file (3.97 kB). View file
 
EquiFashionDB_pipeline/__pycache__/pose_vis.cpython-313.pyc ADDED
Binary file (3.95 kB). View file
 
EquiFashionDB_pipeline/__pycache__/quality.cpython-312.pyc ADDED
Binary file (1.39 kB). View file
 
EquiFashionDB_pipeline/__pycache__/quality.cpython-313.pyc ADDED
Binary file (1.38 kB). View file
 
EquiFashionDB_pipeline/__pycache__/runner.cpython-312.pyc ADDED
Binary file (16.9 kB). View file
 
EquiFashionDB_pipeline/__pycache__/runner.cpython-313.pyc ADDED
Binary file (17.3 kB). View file
 
EquiFashionDB_pipeline/__pycache__/sketch_fabric.cpython-312.pyc CHANGED
Binary files a/EquiFashionDB_pipeline/__pycache__/sketch_fabric.cpython-312.pyc and b/EquiFashionDB_pipeline/__pycache__/sketch_fabric.cpython-312.pyc differ
 
EquiFashionDB_pipeline/__pycache__/sketch_fabric.cpython-313.pyc ADDED
Binary file (5.2 kB). View file
 
EquiFashionDB_pipeline/__pycache__/standardize.cpython-312.pyc ADDED
Binary file (2.96 kB). View file
 
EquiFashionDB_pipeline/__pycache__/standardize.cpython-313.pyc ADDED
Binary file (2.88 kB). View file
 
EquiFashionDB_pipeline/__pycache__/taxonomy.cpython-312.pyc ADDED
Binary file (2.43 kB). View file
 
EquiFashionDB_pipeline/__pycache__/taxonomy.cpython-313.pyc ADDED
Binary file (2.48 kB). View file
 
EquiFashionDB_pipeline/__pycache__/text_noise.cpython-312.pyc ADDED
Binary file (4.98 kB). View file
 
EquiFashionDB_pipeline/__pycache__/text_noise.cpython-313.pyc ADDED
Binary file (5.09 kB). View file
 
EquiFashionDB_pipeline/config.py CHANGED
@@ -1,166 +1,187 @@
1
- from __future__ import annotations
2
-
3
- from dataclasses import dataclass, field
4
- from pathlib import Path
5
- from typing import Any, Optional
6
-
7
- import yaml
8
-
9
-
10
- @dataclass
11
- class SourceEntry:
12
- """One logical source (dataset). May scan multiple folders via `images_dirs`."""
13
-
14
- id: str
15
- images_dirs: list[str] = field(default_factory=list)
16
- recursive: bool = True
17
- extensions: list[str] = field(default_factory=lambda: [".jpg", ".jpeg", ".png", ".webp"])
18
-
19
-
20
- @dataclass
21
- class DedupConfig:
22
- enabled: bool = True
23
- hash_size: int = 16
24
-
25
-
26
- @dataclass
27
- class QualityConfig:
28
- enabled: bool = False
29
- min_short_side_ratio: float = 0.35
30
- min_keypoint_conf: float = 0.2
31
-
32
-
33
- @dataclass
34
- class TextConfig:
35
- seed: int = 42
36
- typo_prob: float = 0.03
37
- token_dropout_prob: float = 0.12
38
- truncate_tail_prob: float = 0.08
39
-
40
-
41
- @dataclass
42
- class EnrichConfig:
43
- fabric_patch: int = 128
44
- pose_conf_thresh: float = 0.25
45
- workers: int = 0
46
- pose_json_dir: Optional[str] = None
47
-
48
-
49
- @dataclass
50
- class PackageConfig:
51
- relative_paths: bool = True
52
-
53
-
54
- @dataclass
55
- class PipelineConfig:
56
- output_root: Path
57
- target_size: int = 512
58
- sources: list[SourceEntry] = field(default_factory=list)
59
- raw_manifest_jsonl: Optional[str] = None
60
- dedup: DedupConfig = field(default_factory=DedupConfig)
61
- quality: QualityConfig = field(default_factory=QualityConfig)
62
- taxonomy: dict[str, Any] = field(default_factory=dict)
63
- text: TextConfig = field(default_factory=TextConfig)
64
- enrich: EnrichConfig = field(default_factory=EnrichConfig)
65
- package: PackageConfig = field(default_factory=PackageConfig)
66
-
67
- @property
68
- def work_dir(self) -> Path:
69
- return self.output_root / "work"
70
-
71
- @property
72
- def images512_dir(self) -> Path:
73
- return self.output_root / "images_512"
74
-
75
- @property
76
- def sketch_dir(self) -> Path:
77
- return self.output_root / "sketch"
78
-
79
- @property
80
- def fabric_dir(self) -> Path:
81
- return self.output_root / "fabric"
82
-
83
- @property
84
- def pose_dir(self) -> Path:
85
- return self.output_root / "pose_json"
86
-
87
-
88
- def _collect_image_dirs(s: dict[str, Any]) -> list[str]:
89
- """YAML may use `images_dir` (string or list) and/or `images_dirs` (list)."""
90
- out: list[str] = []
91
- if s.get("images_dirs") is not None:
92
- v = s["images_dirs"]
93
- if isinstance(v, list):
94
- out.extend(str(x).strip() for x in v if str(x).strip())
95
- elif isinstance(v, str) and v.strip():
96
- out.append(v.strip())
97
- v = s.get("images_dir")
98
- if v is not None:
99
- if isinstance(v, list):
100
- out.extend(str(x).strip() for x in v if str(x).strip())
101
- elif isinstance(v, str) and v.strip():
102
- out.append(v.strip())
103
- seen: set[str] = set()
104
- uniq: list[str] = []
105
- for d in out:
106
- if d not in seen:
107
- seen.add(d)
108
- uniq.append(d)
109
- return uniq
110
-
111
-
112
- def _parse_sources(raw: list[dict[str, Any]]) -> list[SourceEntry]:
113
- out: list[SourceEntry] = []
114
- for s in raw or []:
115
- out.append(
116
- SourceEntry(
117
- id=str(s.get("id", "source")),
118
- images_dirs=_collect_image_dirs(s),
119
- recursive=bool(s.get("recursive", True)),
120
- extensions=list(s.get("extensions", [".jpg", ".jpeg", ".png", ".webp"])),
121
- )
122
- )
123
- return out
124
-
125
-
126
- def load_config(path: Path) -> PipelineConfig:
127
- with open(path, encoding="utf-8") as f:
128
- raw = yaml.safe_load(f) or {}
129
- out_root = Path(raw.get("output_root", "./processed_equifashion")).resolve()
130
- ded = raw.get("dedup") or {}
131
- qual = raw.get("quality") or {}
132
- txt = raw.get("text") or {}
133
- enr = raw.get("enrich") or {}
134
- pkg = raw.get("package") or {}
135
- return PipelineConfig(
136
- output_root=out_root,
137
- target_size=int(raw.get("target_size", 512)),
138
- sources=_parse_sources(raw.get("sources") or []),
139
- raw_manifest_jsonl=raw.get("raw_manifest_jsonl"),
140
- dedup=DedupConfig(enabled=bool(ded.get("enabled", True)), hash_size=int(ded.get("hash_size", 16))),
141
- quality=QualityConfig(
142
- enabled=bool(qual.get("enabled", False)),
143
- min_short_side_ratio=float(qual.get("min_short_side_ratio", 0.35)),
144
- min_keypoint_conf=float(qual.get("min_keypoint_conf", 0.2)),
145
- ),
146
- taxonomy=dict(raw.get("taxonomy") or {}),
147
- text=TextConfig(
148
- seed=int(txt.get("seed", 42)),
149
- typo_prob=float(txt.get("typo_prob", 0.03)),
150
- token_dropout_prob=float(txt.get("token_dropout_prob", 0.12)),
151
- truncate_tail_prob=float(txt.get("truncate_tail_prob", 0.08)),
152
- ),
153
- enrich=EnrichConfig(
154
- fabric_patch=int(enr.get("fabric_patch", 128)),
155
- pose_conf_thresh=float(enr.get("pose_conf_thresh", 0.25)),
156
- workers=int(enr.get("workers", 0)),
157
- pose_json_dir=enr.get("pose_json_dir"),
158
- ),
159
- package=PackageConfig(relative_paths=bool(pkg.get("relative_paths", True))),
160
- )
161
-
162
-
163
- def write_default_config(dest: Path) -> None:
164
- here = Path(__file__).resolve().parent / "defaults.yaml"
165
- dest.parent.mkdir(parents=True, exist_ok=True)
166
- dest.write_text(here.read_text(encoding="utf-8"), encoding="utf-8")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ from typing import Any, Optional
6
+
7
+ import yaml
8
+
9
+
10
+ @dataclass
11
+ class SourceEntry:
12
+ """One logical source (dataset). May scan multiple folders via `images_dirs`."""
13
+
14
+ id: str
15
+ images_dirs: list[str] = field(default_factory=list)
16
+ recursive: bool = True
17
+ extensions: list[str] = field(default_factory=lambda: [".jpg", ".jpeg", ".png", ".webp"])
18
+ split: str = "train" # train | test
19
+ captions_file: Optional[str] = None
20
+ captions_format: str = "none" # none | equifashion_json_list | deepfashion_json_dict | facad_jsonl
21
+
22
+
23
+ @dataclass
24
+ class DedupConfig:
25
+ enabled: bool = True
26
+ hash_size: int = 16
27
+
28
+
29
+ @dataclass
30
+ class QualityConfig:
31
+ enabled: bool = False
32
+ min_short_side_ratio: float = 0.35
33
+
34
+
35
+ @dataclass
36
+ class TextConfig:
37
+ seed: int = 42
38
+ typo_prob: float = 0.03
39
+ token_dropout_prob: float = 0.12
40
+ truncate_tail_prob: float = 0.08
41
+
42
+
43
+ @dataclass
44
+ class EnrichConfig:
45
+ fabric_patch: int = 128
46
+ workers: int = 0
47
+
48
+
49
+ @dataclass
50
+ class PackageConfig:
51
+ relative_paths: bool = True
52
+
53
+
54
+ @dataclass
55
+ class PipelineConfig:
56
+ output_root: Path
57
+ target_size: int = 512
58
+ sources: list[SourceEntry] = field(default_factory=list)
59
+ raw_manifest_jsonl: Optional[str] = None
60
+ dedup: DedupConfig = field(default_factory=DedupConfig)
61
+ quality: QualityConfig = field(default_factory=QualityConfig)
62
+ taxonomy: dict[str, Any] = field(default_factory=dict)
63
+ text: TextConfig = field(default_factory=TextConfig)
64
+ enrich: EnrichConfig = field(default_factory=EnrichConfig)
65
+ package: PackageConfig = field(default_factory=PackageConfig)
66
+
67
+ @property
68
+ def work_dir(self) -> Path:
69
+ return self.output_root / "work"
70
+
71
+ @property
72
+ def images512_dir(self) -> Path:
73
+ return self.output_root / "images_512"
74
+
75
+ # EquiFashion_DB-like output layout
76
+ @property
77
+ def train_dir(self) -> Path:
78
+ return self.output_root / "train"
79
+
80
+ @property
81
+ def test_dir(self) -> Path:
82
+ return self.output_root / "test"
83
+
84
+ @property
85
+ def train_sketch_dir(self) -> Path:
86
+ return self.output_root / "train_sketch"
87
+
88
+ @property
89
+ def train_fabric_dir(self) -> Path:
90
+ return self.output_root / "train_fabric"
91
+
92
+ @property
93
+ def test_sketch_dir(self) -> Path:
94
+ return self.output_root / "test_sketch"
95
+
96
+ @property
97
+ def test_fabric_dir(self) -> Path:
98
+ return self.output_root / "test_fabric"
99
+
100
+ @property
101
+ def sketch_dir(self) -> Path:
102
+ return self.output_root / "sketch"
103
+
104
+ @property
105
+ def fabric_dir(self) -> Path:
106
+ return self.output_root / "fabric"
107
+
108
+
109
+ def _collect_image_dirs(s: dict[str, Any]) -> list[str]:
110
+ """YAML may use `images_dir` (string or list) and/or `images_dirs` (list)."""
111
+ out: list[str] = []
112
+ if s.get("images_dirs") is not None:
113
+ v = s["images_dirs"]
114
+ if isinstance(v, list):
115
+ out.extend(str(x).strip() for x in v if str(x).strip())
116
+ elif isinstance(v, str) and v.strip():
117
+ out.append(v.strip())
118
+ v = s.get("images_dir")
119
+ if v is not None:
120
+ if isinstance(v, list):
121
+ out.extend(str(x).strip() for x in v if str(x).strip())
122
+ elif isinstance(v, str) and v.strip():
123
+ out.append(v.strip())
124
+ seen: set[str] = set()
125
+ uniq: list[str] = []
126
+ for d in out:
127
+ if d not in seen:
128
+ seen.add(d)
129
+ uniq.append(d)
130
+ return uniq
131
+
132
+
133
+ def _parse_sources(raw: list[dict[str, Any]]) -> list[SourceEntry]:
134
+ out: list[SourceEntry] = []
135
+ for s in raw or []:
136
+ out.append(
137
+ SourceEntry(
138
+ id=str(s.get("id", "source")),
139
+ images_dirs=_collect_image_dirs(s),
140
+ recursive=bool(s.get("recursive", True)),
141
+ extensions=list(s.get("extensions", [".jpg", ".jpeg", ".png", ".webp"])),
142
+ split=str(s.get("split", "train")),
143
+ captions_file=s.get("captions_file"),
144
+ captions_format=str(s.get("captions_format", "none")),
145
+ )
146
+ )
147
+ return out
148
+
149
+
150
+ def load_config(path: Path) -> PipelineConfig:
151
+ with open(path, encoding="utf-8") as f:
152
+ raw = yaml.safe_load(f) or {}
153
+ out_root = Path(raw.get("output_root", "./processed_equifashion")).resolve()
154
+ ded = raw.get("dedup") or {}
155
+ qual = raw.get("quality") or {}
156
+ txt = raw.get("text") or {}
157
+ enr = raw.get("enrich") or {}
158
+ pkg = raw.get("package") or {}
159
+ return PipelineConfig(
160
+ output_root=out_root,
161
+ target_size=int(raw.get("target_size", 512)),
162
+ sources=_parse_sources(raw.get("sources") or []),
163
+ raw_manifest_jsonl=raw.get("raw_manifest_jsonl"),
164
+ dedup=DedupConfig(enabled=bool(ded.get("enabled", True)), hash_size=int(ded.get("hash_size", 16))),
165
+ quality=QualityConfig(
166
+ enabled=bool(qual.get("enabled", False)),
167
+ min_short_side_ratio=float(qual.get("min_short_side_ratio", 0.35)),
168
+ ),
169
+ taxonomy=dict(raw.get("taxonomy") or {}),
170
+ text=TextConfig(
171
+ seed=int(txt.get("seed", 42)),
172
+ typo_prob=float(txt.get("typo_prob", 0.03)),
173
+ token_dropout_prob=float(txt.get("token_dropout_prob", 0.12)),
174
+ truncate_tail_prob=float(txt.get("truncate_tail_prob", 0.08)),
175
+ ),
176
+ enrich=EnrichConfig(
177
+ fabric_patch=int(enr.get("fabric_patch", 128)),
178
+ workers=int(enr.get("workers", 0)),
179
+ ),
180
+ package=PackageConfig(relative_paths=bool(pkg.get("relative_paths", True))),
181
+ )
182
+
183
+
184
+ def write_default_config(dest: Path) -> None:
185
+ here = Path(__file__).resolve().parent / "defaults.yaml"
186
+ dest.parent.mkdir(parents=True, exist_ok=True)
187
+ dest.write_text(here.read_text(encoding="utf-8"), encoding="utf-8")
EquiFashionDB_pipeline/defaults.yaml CHANGED
@@ -1,50 +1,40 @@
1
- utput_root: ./processed_equifashion
2
- target_size: 512
3
-
4
- # Nhiều nguồn: mỗi phần tử là một dataset (source_id). Mỗi dataset có thể có NHIỀU thư mục ảnh.
5
- # Cách khai báo (chọn một hoặc kết hợp):
6
- # - images_dirs: [ "D:/data/FashionGen/batch1", "D:/data/FashionGen/batch2" ]
7
- # - images_dir: "một_thư_mục"
8
- # - images_dir: [ "thư_mục_a", "thư_mục_b" ]
9
- sources:
10
- - id: FashionGen
11
- images_dirs:
12
- - "" # ví dụ: D:/datasets/FashionGen/part_a
13
- - "" # ví dụ: D:/datasets/FashionGen/part_b
14
- recursive: true
15
- extensions: [".jpg", ".jpeg", ".png", ".webp"]
16
-
17
- - id: DeepFashion
18
- images_dir: "" # một thư mục (tương đương images_dirs: [một phần tử])
19
- recursive: true
20
-
21
- # Hoặc chỉ dùng manifest (mỗi dòng JSON) — hợp khi ảnh nằm rải rác nhiều nơi đã ghi trong file:
22
- # raw_manifest_jsonl: ./my_manifest.jsonl
23
- # Mỗi dòng: {"id": "...", "image_path": "...", "caption": "...", "category_raw": "...", "source_id": "..."}
24
-
25
- dedup:
26
- enabled: true
27
- hash_size: 16
28
-
29
- quality:
30
- enabled: false
31
- min_short_side_ratio: 0.35
32
- min_keypoint_conf: 0.2
33
-
34
- taxonomy:
35
- map_file: null
36
-
37
- text:
38
- seed: 42
39
- typo_prob: 0.03
40
- token_dropout_prob: 0.12
41
- truncate_tail_prob: 0.08
42
-
43
- enrich:
44
- fabric_patch: 128
45
- pose_conf_thresh: 0.25
46
- workers: 0
47
- pose_json_dir: null
48
-
49
- package:
50
- relative_paths: true
 
1
+ output_root: ./processed_equifashion
2
+ target_size: 512
3
+
4
+
5
+ sources:
6
+ - id: FashionGen
7
+ images_dirs:
8
+ - "" # ví dụ: D:/datasets/FashionGen/part_a
9
+ - "" # ví dụ: D:/datasets/FashionGen/part_b
10
+ recursive: true
11
+ extensions: [".jpg", ".jpeg", ".png", ".webp"]
12
+
13
+ - id: DeepFashion
14
+ images_dir: "" # một thư mục (tương đương images_dirs: [một phần tử])
15
+ recursive: true
16
+
17
+
18
+ dedup:
19
+ enabled: true
20
+ hash_size: 16
21
+
22
+ quality:
23
+ enabled: false
24
+ min_short_side_ratio: 0.35
25
+
26
+ taxonomy:
27
+ map_file: null
28
+
29
+ text:
30
+ seed: 42
31
+ typo_prob: 0.03
32
+ token_dropout_prob: 0.12
33
+ truncate_tail_prob: 0.08
34
+
35
+ enrich:
36
+ fabric_patch: 128
37
+ workers: 0
38
+
39
+ package:
40
+ relative_paths: true
 
 
 
 
 
 
 
 
 
 
EquiFashionDB_pipeline/ingest.py CHANGED
@@ -1,23 +1,65 @@
1
- """Build raw_index.jsonl by scanning configured source directories."""
2
 
3
  from __future__ import annotations
4
 
5
- import hashlib
6
  import json
7
  from pathlib import Path
 
8
 
9
  from .config import PipelineConfig, SourceEntry
10
 
11
 
12
- def _stable_id(source_id: str, root_resolved: Path, rel: str) -> str:
13
- # Include root so the same rel_path under different folders never collides.
14
- key = f"{source_id}|{root_resolved.resolve()}|{rel}"
15
- return hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
 
18
  def scan_source(entry: SourceEntry) -> list[dict]:
19
  rows: list[dict] = []
20
  exts = {e.lower() for e in entry.extensions}
 
21
  for dir_str in entry.images_dirs:
22
  root = Path(dir_str).expanduser().resolve()
23
  if not dir_str.strip() or not root.is_dir():
@@ -29,15 +71,18 @@ def scan_source(entry: SourceEntry) -> list[dict]:
29
  if p.suffix.lower() not in exts:
30
  continue
31
  rel = str(p.relative_to(root)).replace("\\", "/")
32
- sid = _stable_id(entry.id, root, rel)
 
33
  rows.append(
34
  {
35
- "id": sid,
36
  "source_id": entry.id,
37
  "source_root": str(root),
38
  "image_path": str(p),
39
  "rel_path": rel,
40
- "caption": "",
 
 
41
  "category_raw": "",
42
  }
43
  )
 
1
+ """Build raw_index.jsonl by scanning configured source directories (with captions)."""
2
 
3
  from __future__ import annotations
4
 
 
5
  import json
6
  from pathlib import Path
7
+ from typing import Dict, Optional
8
 
9
  from .config import PipelineConfig, SourceEntry
10
 
11
 
12
+ def _load_caption_map(entry: SourceEntry) -> Dict[str, str]:
13
+ """
14
+ Returns mapping from gt filename (basename) -> caption.
15
+ """
16
+ if not entry.captions_file or entry.captions_format == "none":
17
+ return {}
18
+ p = Path(entry.captions_file).expanduser().resolve()
19
+ if not p.is_file():
20
+ return {}
21
+
22
+ fmt = entry.captions_format
23
+ if fmt == "equifashion_json_list":
24
+ data = json.loads(p.read_text(encoding="utf-8"))
25
+ out: Dict[str, str] = {}
26
+ for r in data or []:
27
+ gt = str(r.get("gt", "")).strip()
28
+ cap = str(r.get("caption", "")).strip()
29
+ if gt:
30
+ out[Path(gt).name] = cap
31
+ return out
32
+
33
+ if fmt == "deepfashion_json_dict":
34
+ data = json.loads(p.read_text(encoding="utf-8"))
35
+ if isinstance(data, dict):
36
+ return {Path(k).name: str(v) for k, v in data.items()}
37
+ return {}
38
+
39
+ if fmt == "facad_jsonl":
40
+ out: Dict[str, str] = {}
41
+ with open(p, encoding="utf-8") as f:
42
+ for line in f:
43
+ line = line.strip()
44
+ if not line:
45
+ continue
46
+ try:
47
+ r = json.loads(line)
48
+ except Exception:
49
+ continue
50
+ img = str(r.get("image", "")).strip()
51
+ txt = str(r.get("text", "")).strip()
52
+ if img:
53
+ out[Path(img).name] = txt
54
+ return out
55
+
56
+ return {}
57
 
58
 
59
  def scan_source(entry: SourceEntry) -> list[dict]:
60
  rows: list[dict] = []
61
  exts = {e.lower() for e in entry.extensions}
62
+ cap_map = _load_caption_map(entry)
63
  for dir_str in entry.images_dirs:
64
  root = Path(dir_str).expanduser().resolve()
65
  if not dir_str.strip() or not root.is_dir():
 
71
  if p.suffix.lower() not in exts:
72
  continue
73
  rel = str(p.relative_to(root)).replace("\\", "/")
74
+ gt = Path(rel).name
75
+ stem = Path(gt).stem
76
  rows.append(
77
  {
78
+ "id": stem,
79
  "source_id": entry.id,
80
  "source_root": str(root),
81
  "image_path": str(p),
82
  "rel_path": rel,
83
+ "gt": gt,
84
+ "split": entry.split,
85
+ "caption": cap_map.get(gt, ""),
86
  "category_raw": "",
87
  }
88
  )
EquiFashionDB_pipeline/package.py CHANGED
@@ -1,53 +1,46 @@
1
- """Write final unified manifest JSON (list of records with modality paths)."""
2
-
3
- from __future__ import annotations
4
-
5
- import json
6
- from pathlib import Path
7
- from typing import Any
8
-
9
- from .config import PipelineConfig
10
-
11
-
12
- def _rel(cfg: PipelineConfig, p: Path) -> str:
13
- if cfg.package.relative_paths:
14
- try:
15
- return str(p.relative_to(cfg.output_root)).replace("\\", "/")
16
- except ValueError:
17
- return str(p).replace("\\", "/")
18
- return str(p).replace("\\", "/")
19
-
20
-
21
- def build_final_records(rows: list[dict[str, Any]], cfg: PipelineConfig) -> list[dict[str, Any]]:
22
- out: list[dict[str, Any]] = []
23
- for row in rows:
24
- if not row.get("use_in_training", True):
25
- continue
26
- rid = row["id"]
27
- img = cfg.images512_dir / f"{rid}.jpg"
28
- sk = cfg.sketch_dir / f"{rid}.png"
29
- fb = cfg.fabric_dir / f"{rid}.png"
30
- pose = cfg.pose_dir / f"{rid}.json"
31
- rec = {
32
- "id": rid,
33
- "source_id": row.get("source_id", ""),
34
- "category": row.get("category_normalized") or row.get("category_raw", ""),
35
- "caption_clean": row.get("caption_clean", ""),
36
- "caption_noisy": row.get("caption_noisy", ""),
37
- "paths": {
38
- "image_512": _rel(cfg, img),
39
- "sketch": _rel(cfg, sk),
40
- "fabric_patch": _rel(cfg, fb),
41
- "pose_json": _rel(cfg, pose) if pose.is_file() else None,
42
- },
43
- }
44
- out.append(rec)
45
- return out
46
-
47
-
48
- def write_manifest(records: list[dict[str, Any]], cfg: PipelineConfig, name: str = "equifashion_manifest.json") -> Path:
49
- path = cfg.output_root / name
50
- path.parent.mkdir(parents=True, exist_ok=True)
51
- with open(path, "w", encoding="utf-8") as f:
52
- json.dump(records, f, ensure_ascii=False, indent=2)
53
- return path
 
1
+ """Write EquiFashion_DB-like captions JSONs and aligned modality paths."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from .config import PipelineConfig
9
+
10
+
11
+ def _dump_json_list(path: Path, data: list[dict[str, Any]]) -> None:
12
+ import json
13
+
14
+ path.parent.mkdir(parents=True, exist_ok=True)
15
+ with open(path, "w", encoding="utf-8") as f:
16
+ json.dump(data, f, ensure_ascii=False, indent=2)
17
+
18
+
19
+ def write_equifashion_style_outputs(rows: list[dict[str, Any]], cfg: PipelineConfig) -> dict[str, Path]:
20
+ """
21
+ Writes:
22
+ - train.json / test.json: list of {gt, caption}
23
+ """
24
+ train_caps: list[dict[str, Any]] = []
25
+ test_caps: list[dict[str, Any]] = []
26
+
27
+ for row in rows:
28
+ if not row.get("use_in_training", True):
29
+ continue
30
+ split = str(row.get("split") or "train").lower()
31
+ gt = str(row.get("gt") or Path(str(row.get("image_path", ""))).name)
32
+ cap = str(row.get("caption") or row.get("caption_raw") or "")
33
+
34
+ item = {"gt": gt, "caption": cap}
35
+ if split == "test":
36
+ test_caps.append(item)
37
+ else:
38
+ train_caps.append(item)
39
+
40
+ out = {
41
+ "train_json": cfg.output_root / "train.json",
42
+ "test_json": cfg.output_root / "test.json",
43
+ }
44
+ _dump_json_list(out["train_json"], train_caps)
45
+ _dump_json_list(out["test_json"], test_caps)
46
+ return out
 
 
 
 
 
 
 
EquiFashionDB_pipeline/runner.py CHANGED
@@ -1,282 +1,310 @@
1
- """Orchestrate pipeline stages (ingest → standardize → dedup → text → enrich → package)."""
2
-
3
- from __future__ import annotations
4
-
5
- import json
6
- import os
7
- from concurrent.futures import ProcessPoolExecutor, as_completed
8
- from pathlib import Path
9
- from typing import Any, Optional
10
-
11
- import cv2
12
- from tqdm import tqdm
13
-
14
- from . import dedup, ingest, package, pose_unify, quality as quality_mod, sketch_fabric, standardize, taxonomy, text_noise
15
- from .config import PipelineConfig, load_config
16
-
17
-
18
- def _load_jsonl(path: Path) -> list[dict[str, Any]]:
19
- if not path.is_file():
20
- return []
21
- rows: list[dict[str, Any]] = []
22
- with open(path, encoding="utf-8") as f:
23
- for line in f:
24
- line = line.strip()
25
- if line:
26
- rows.append(json.loads(line))
27
- return rows
28
-
29
-
30
- def _save_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
31
- path.parent.mkdir(parents=True, exist_ok=True)
32
- with open(path, "w", encoding="utf-8") as f:
33
- for r in rows:
34
- f.write(json.dumps(r, ensure_ascii=False) + "\n")
35
-
36
-
37
- def _default_workers(cfg: PipelineConfig) -> int:
38
- w = cfg.enrich.workers
39
- if w and w > 0:
40
- return w
41
- return max(1, (os.cpu_count() or 4) - 1)
42
-
43
-
44
- def stage_ingest(cfg: PipelineConfig) -> Path:
45
- cfg.output_root.mkdir(parents=True, exist_ok=True)
46
- out = ingest.run_ingest(cfg)
47
- idx = cfg.work_dir / "index.jsonl"
48
- if out.is_file():
49
- rows = _load_jsonl(out)
50
- _save_jsonl(idx, rows)
51
- return cfg.work_dir / "index.jsonl"
52
-
53
-
54
- def stage_standardize(cfg: PipelineConfig) -> None:
55
- idx_path = cfg.work_dir / "index.jsonl"
56
- rows = _load_jsonl(idx_path)
57
- if not rows and cfg.raw_manifest_jsonl:
58
- rows = _load_jsonl(Path(cfg.raw_manifest_jsonl))
59
- _save_jsonl(idx_path, rows)
60
- if not rows:
61
- raise FileNotFoundError(
62
- "No index rows. Run ingest with sources (images_dir / images_dirs) or set raw_manifest_jsonl."
63
- )
64
-
65
- cfg.images512_dir.mkdir(parents=True, exist_ok=True)
66
- for row in tqdm(rows, desc="standardize"):
67
- src = Path(row["image_path"])
68
- if not src.is_file():
69
- row["standardize_error"] = "missing_source_image"
70
- continue
71
- bgr = standardize.read_image_bgr(src)
72
- if bgr is None:
73
- row["standardize_error"] = "read_fail"
74
- continue
75
- if cfg.quality.enabled:
76
- quality_mod.annotate_quality(row, bgr, cfg.quality.min_short_side_ratio)
77
- if row.get("quality_ok") is False:
78
- row["skip_reason"] = "quality_aspect"
79
- continue
80
- try:
81
- sq = standardize.letterbox_square_bgr(bgr, cfg.target_size)
82
- except Exception as e:
83
- row["standardize_error"] = str(e)
84
- continue
85
- rid = str(row["id"])
86
- dst = cfg.images512_dir / f"{rid}.jpg"
87
- standardize.write_jpg(dst, sq)
88
- row["image_512"] = str(dst)
89
- row["image_size"] = [cfg.target_size, cfg.target_size]
90
-
91
- for row in rows:
92
- ok = True
93
- if cfg.quality.enabled:
94
- ok = bool(row.get("quality_ok", True))
95
- row["use_in_training"] = ok and not row.get("skip_reason")
96
-
97
- _save_jsonl(idx_path, rows)
98
-
99
-
100
- def stage_dedup(cfg: PipelineConfig) -> None:
101
- idx_path = cfg.work_dir / "index.jsonl"
102
- rows = _load_jsonl(idx_path)
103
- if not cfg.dedup.enabled:
104
- _save_jsonl(idx_path, rows)
105
- return
106
- without = [r for r in rows if not r.get("image_512")]
107
- for row in without:
108
- row.setdefault("dedup_status", "no_image")
109
- with_img = [r for r in rows if r.get("image_512")]
110
- updated, logs = dedup.cluster_duplicates(with_img, "image_512", cfg.dedup.hash_size)
111
- by_id = {r["id"]: r for r in without}
112
- for r in updated:
113
- by_id[r["id"]] = r
114
- merged = list(by_id.values())
115
- for r in merged:
116
- st = r.get("dedup_status")
117
- if st == "duplicate":
118
- r["use_in_training"] = False
119
- elif st == "canonical":
120
- r["use_in_training"] = r.get("use_in_training", True)
121
- elif st == "hash_fail":
122
- r.setdefault("use_in_training", True)
123
- _save_jsonl(idx_path, merged)
124
- log_path = cfg.work_dir / "dedup_log.txt"
125
- log_path.write_text("\n".join(logs), encoding="utf-8")
126
-
127
-
128
- def stage_taxonomy(cfg: PipelineConfig) -> None:
129
- idx_path = cfg.work_dir / "index.jsonl"
130
- rows = _load_jsonl(idx_path)
131
- map_path = cfg.taxonomy.get("map_file") if cfg.taxonomy else None
132
- mp = taxonomy.load_taxonomy_map(Path(map_path) if map_path else None)
133
- for row in rows:
134
- raw = row.get("category_raw") or ""
135
- row["category_normalized"] = taxonomy.normalize_category(str(raw), mp)
136
- _save_jsonl(idx_path, rows)
137
-
138
-
139
- def stage_text(cfg: PipelineConfig) -> None:
140
- idx_path = cfg.work_dir / "index.jsonl"
141
- rows = _load_jsonl(idx_path)
142
- tc = cfg.text
143
- for row in rows:
144
- cap = row.get("caption") or row.get("caption_raw") or ""
145
- clean = text_noise.clean_caption(str(cap))
146
- row["caption_clean"] = clean
147
- row["caption_noisy"] = text_noise.noisy_caption(
148
- clean,
149
- seed=tc.seed + hash(str(row["id"])) % (2**20),
150
- typo_prob=tc.typo_prob,
151
- token_dropout_prob=tc.token_dropout_prob,
152
- truncate_tail_prob=tc.truncate_tail_prob,
153
- )
154
- _save_jsonl(idx_path, rows)
155
-
156
-
157
- def _enrich_job(args: tuple) -> tuple[str, Optional[str]]:
158
- row, cfg_dict = args
159
- cfg = cfg_dict # type: ignore
160
- from pathlib import Path as P
161
-
162
- rid = str(row["id"])
163
- img_path = P(row["image_512"])
164
- pose_dir = cfg.get("pose_json_dir")
165
- pose_json = P(pose_dir) / f"{rid}.json" if pose_dir else None
166
- if pose_json is not None and not pose_json.is_file():
167
- pose_json = None
168
- out_sk = P(cfg["sketch_dir"])
169
- out_fb = P(cfg["fabric_dir"])
170
- out_pose = P(cfg["pose_dir"])
171
- stem = rid
172
- err: Optional[str] = None
173
- bgr = cv2.imread(str(img_path), cv2.IMREAD_COLOR)
174
- if bgr is None:
175
- return rid, "read_fail"
176
- h, w = bgr.shape[:2]
177
- pose_unify.copy_or_unify_pose(pose_json, out_pose / f"{stem}.json", (h, w))
178
- _, err = sketch_fabric.process_one_sample(
179
- img_path,
180
- out_sk,
181
- out_fb,
182
- stem,
183
- pose_json,
184
- float(cfg["pose_conf_thresh"]),
185
- int(cfg["fabric_patch"]),
186
- )
187
- return stem, err
188
-
189
-
190
- def stage_enrich(cfg: PipelineConfig) -> None:
191
- idx_path = cfg.work_dir / "index.jsonl"
192
- rows = _load_jsonl(idx_path)
193
- rows = [r for r in rows if r.get("use_in_training", True) and r.get("image_512")]
194
- cfg.pose_dir.mkdir(parents=True, exist_ok=True)
195
- cfg.sketch_dir.mkdir(parents=True, exist_ok=True)
196
- cfg.fabric_dir.mkdir(parents=True, exist_ok=True)
197
-
198
- pose_json_dir = cfg.enrich.pose_json_dir
199
- cfg_dict: dict[str, Any] = {
200
- "pose_json_dir": pose_json_dir,
201
- "sketch_dir": str(cfg.sketch_dir),
202
- "fabric_dir": str(cfg.fabric_dir),
203
- "pose_dir": str(cfg.pose_dir),
204
- "pose_conf_thresh": cfg.enrich.pose_conf_thresh,
205
- "fabric_patch": cfg.enrich.fabric_patch,
206
- }
207
- jobs = [(r, cfg_dict) for r in rows]
208
- errs: list[tuple[str, str]] = []
209
- n_workers = _default_workers(cfg)
210
- if n_workers <= 1:
211
- for job in tqdm(jobs, desc="enrich"):
212
- rid, err = _enrich_job(job)
213
- if err:
214
- errs.append((rid, err))
215
- else:
216
- with ProcessPoolExecutor(max_workers=n_workers) as ex:
217
- futs = [ex.submit(_enrich_job, job) for job in jobs]
218
- for fut in tqdm(as_completed(futs), total=len(futs), desc="enrich"):
219
- rid, err = fut.result()
220
- if err:
221
- errs.append((rid, err))
222
-
223
- if errs:
224
- p = cfg.work_dir / "enrich_errors.txt"
225
- p.write_text("\n".join(f"{a}\t{b}" for a, b in errs), encoding="utf-8")
226
-
227
-
228
- def stage_package(cfg: PipelineConfig) -> Path:
229
- idx_path = cfg.work_dir / "index.jsonl"
230
- rows = _load_jsonl(idx_path)
231
- recs = package.build_final_records(rows, cfg)
232
- return package.write_manifest(recs, cfg)
233
-
234
-
235
- def run_stages(cfg: PipelineConfig, stages: list[str]) -> None:
236
- order = ["ingest", "standardize", "dedup", "taxonomy", "text", "enrich", "package"]
237
- want = set(stages)
238
- if "all" in want:
239
- want = set(order)
240
- for name in order:
241
- if name not in want:
242
- continue
243
- if name == "ingest":
244
- stage_ingest(cfg)
245
- elif name == "standardize":
246
- stage_standardize(cfg)
247
- elif name == "dedup":
248
- stage_dedup(cfg)
249
- elif name == "taxonomy":
250
- stage_taxonomy(cfg)
251
- elif name == "text":
252
- stage_text(cfg)
253
- elif name == "enrich":
254
- stage_enrich(cfg)
255
- elif name == "package":
256
- out = stage_package(cfg)
257
- print(f"Wrote manifest: {out}")
258
-
259
-
260
- def main_cli() -> None:
261
- import argparse
262
-
263
- ap = argparse.ArgumentParser(description="EquiFashion-style data pipeline")
264
- ap.add_argument("--config", type=Path, default=Path("pipeline_config.yaml"))
265
- ap.add_argument(
266
- "--stage",
267
- default="all",
268
- help="Comma-separated: ingest,standardize,dedup,taxonomy,text,enrich,package,all",
269
- )
270
- ap.add_argument("--init-config", action="store_true", help="Write defaults to --config and exit")
271
- args = ap.parse_args()
272
-
273
- if args.init_config:
274
- from .config import write_default_config
275
-
276
- write_default_config(args.config.resolve())
277
- print(f"Wrote {args.config}")
278
- return
279
-
280
- cfg = load_config(args.config.resolve())
281
- stages = [s.strip() for s in args.stage.split(",") if s.strip()]
282
- run_stages(cfg, stages)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Orchestrate pipeline stages (ingest → standardize → dedup → text → enrich → package)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ from concurrent.futures import ProcessPoolExecutor, as_completed
9
+ from pathlib import Path
10
+ from typing import Any, Optional
11
+
12
+ import cv2
13
+ from tqdm import tqdm
14
+
15
+ from . import dedup, ingest, package, quality as quality_mod, sketch_fabric, standardize, taxonomy, text_noise
16
+ from .config import PipelineConfig, load_config
17
+
18
+
19
+ def _load_jsonl(path: Path) -> list[dict[str, Any]]:
20
+ if not path.is_file():
21
+ return []
22
+ rows: list[dict[str, Any]] = []
23
+ with open(path, encoding="utf-8") as f:
24
+ for line in f:
25
+ line = line.strip()
26
+ if line:
27
+ rows.append(json.loads(line))
28
+ return rows
29
+
30
+
31
+ def _save_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
32
+ path.parent.mkdir(parents=True, exist_ok=True)
33
+ with open(path, "w", encoding="utf-8") as f:
34
+ for r in rows:
35
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
36
+
37
+
38
+ def _default_workers(cfg: PipelineConfig) -> int:
39
+ w = cfg.enrich.workers
40
+ if w and w > 0:
41
+ return w
42
+ return max(1, (os.cpu_count() or 4) - 1)
43
+
44
+
45
+ def stage_ingest(cfg: PipelineConfig) -> Path:
46
+ cfg.output_root.mkdir(parents=True, exist_ok=True)
47
+ out = ingest.run_ingest(cfg)
48
+ idx = cfg.work_dir / "index.jsonl"
49
+ if out.is_file():
50
+ rows = _load_jsonl(out)
51
+ _save_jsonl(idx, rows)
52
+ return cfg.work_dir / "index.jsonl"
53
+
54
+
55
+ def stage_standardize(cfg: PipelineConfig) -> None:
56
+ idx_path = cfg.work_dir / "index.jsonl"
57
+ rows = _load_jsonl(idx_path)
58
+ if not rows and cfg.raw_manifest_jsonl:
59
+ rows = _load_jsonl(Path(cfg.raw_manifest_jsonl))
60
+ _save_jsonl(idx_path, rows)
61
+ if not rows:
62
+ raise FileNotFoundError(
63
+ "No index rows. In pipeline_config.yaml, set non-empty paths under `sources` "
64
+ "(`images_dir` / `images_dirs` pointing to folders that contain images), "
65
+ "or set `raw_manifest_jsonl` to a JSONL manifest. "
66
+ "The default template uses empty placeholders — you must replace them with real paths."
67
+ )
68
+
69
+ cfg.train_dir.mkdir(parents=True, exist_ok=True)
70
+ cfg.test_dir.mkdir(parents=True, exist_ok=True)
71
+ for row in tqdm(rows, desc="standardize"):
72
+ src = Path(row["image_path"])
73
+ if not src.is_file():
74
+ row["standardize_error"] = "missing_source_image"
75
+ continue
76
+ bgr = None
77
+ if cfg.target_size > 0 or cfg.quality.enabled:
78
+ bgr = standardize.read_image_bgr(src)
79
+ if bgr is None:
80
+ row["standardize_error"] = "read_fail"
81
+ continue
82
+ if cfg.quality.enabled:
83
+ assert bgr is not None
84
+ quality_mod.annotate_quality(row, bgr, cfg.quality.min_short_side_ratio)
85
+ if row.get("quality_ok") is False:
86
+ row["skip_reason"] = "quality_aspect"
87
+ continue
88
+ split = str(row.get("split") or "train").lower()
89
+ gt = str(row.get("gt") or Path(row["image_path"]).name)
90
+ dst_root = cfg.test_dir if split == "test" else cfg.train_dir
91
+ # Keep original filename; if collision, rename and update `gt` accordingly.
92
+ dst = dst_root / gt
93
+ if dst.exists():
94
+ stem = Path(gt).stem
95
+ ext = Path(gt).suffix
96
+ src_tag = str(row.get("source_id") or "src")
97
+ k = 1
98
+ while True:
99
+ cand = dst_root / f"{stem}__{src_tag}__{k}{ext}"
100
+ if not cand.exists():
101
+ dst = cand
102
+ row["gt"] = dst.name
103
+ row["id"] = dst.stem
104
+ break
105
+ k += 1
106
+ if cfg.target_size <= 0:
107
+ # No resize: byte-copy original file.
108
+ dst.parent.mkdir(parents=True, exist_ok=True)
109
+ shutil.copy2(src, dst)
110
+ # Record size if possible (best-effort).
111
+ bgr2 = cv2.imread(str(dst), cv2.IMREAD_COLOR)
112
+ if bgr2 is not None:
113
+ h2, w2 = bgr2.shape[:2]
114
+ row["image_size"] = [int(w2), int(h2)]
115
+ else:
116
+ assert bgr is not None
117
+ try:
118
+ sq = standardize.letterbox_square_bgr(bgr, cfg.target_size)
119
+ except Exception as e:
120
+ row["standardize_error"] = str(e)
121
+ continue
122
+ standardize.write_image(dst, sq)
123
+ row["image_size"] = [cfg.target_size, cfg.target_size]
124
+ row["image_512"] = str(dst)
125
+
126
+ for row in rows:
127
+ ok = True
128
+ if cfg.quality.enabled:
129
+ ok = bool(row.get("quality_ok", True))
130
+ row["use_in_training"] = ok and not row.get("skip_reason")
131
+
132
+ _save_jsonl(idx_path, rows)
133
+
134
+
135
+ def stage_dedup(cfg: PipelineConfig) -> None:
136
+ idx_path = cfg.work_dir / "index.jsonl"
137
+ rows = _load_jsonl(idx_path)
138
+ if not cfg.dedup.enabled:
139
+ _save_jsonl(idx_path, rows)
140
+ return
141
+ without = [r for r in rows if not r.get("image_512")]
142
+ for row in without:
143
+ row.setdefault("dedup_status", "no_image")
144
+ with_img = [r for r in rows if r.get("image_512")]
145
+ updated, logs = dedup.cluster_duplicates(with_img, "image_512", cfg.dedup.hash_size)
146
+ by_id = {r["id"]: r for r in without}
147
+ for r in updated:
148
+ by_id[r["id"]] = r
149
+ merged = list(by_id.values())
150
+ for r in merged:
151
+ st = r.get("dedup_status")
152
+ if st == "duplicate":
153
+ r["use_in_training"] = False
154
+ elif st == "canonical":
155
+ r["use_in_training"] = r.get("use_in_training", True)
156
+ elif st == "hash_fail":
157
+ r.setdefault("use_in_training", True)
158
+ _save_jsonl(idx_path, merged)
159
+ log_path = cfg.work_dir / "dedup_log.txt"
160
+ log_path.write_text("\n".join(logs), encoding="utf-8")
161
+
162
+
163
+ def stage_taxonomy(cfg: PipelineConfig) -> None:
164
+ idx_path = cfg.work_dir / "index.jsonl"
165
+ rows = _load_jsonl(idx_path)
166
+ map_path = cfg.taxonomy.get("map_file") if cfg.taxonomy else None
167
+ mp = taxonomy.load_taxonomy_map(Path(map_path) if map_path else None)
168
+ for row in rows:
169
+ raw = row.get("category_raw") or ""
170
+ row["category_normalized"] = taxonomy.normalize_category(str(raw), mp)
171
+ _save_jsonl(idx_path, rows)
172
+
173
+
174
+ def stage_text(cfg: PipelineConfig) -> None:
175
+ idx_path = cfg.work_dir / "index.jsonl"
176
+ rows = _load_jsonl(idx_path)
177
+ tc = cfg.text
178
+ for row in rows:
179
+ cap = row.get("caption") or row.get("caption_raw") or ""
180
+ clean = text_noise.clean_caption(str(cap))
181
+ row["caption_clean"] = clean
182
+ row["caption_noisy"] = text_noise.noisy_caption(
183
+ clean,
184
+ seed=tc.seed + hash(str(row["id"])) % (2**20),
185
+ typo_prob=tc.typo_prob,
186
+ token_dropout_prob=tc.token_dropout_prob,
187
+ truncate_tail_prob=tc.truncate_tail_prob,
188
+ )
189
+ _save_jsonl(idx_path, rows)
190
+
191
+
192
+ def _enrich_job(args: tuple) -> tuple[str, Optional[str]]:
193
+ row, cfg_dict = args
194
+ cfg = cfg_dict # type: ignore
195
+ from pathlib import Path as P
196
+
197
+ rid = str(row["id"])
198
+ img_path = P(row["image_512"])
199
+ split = str(row.get("split") or "train").lower()
200
+ out_sk = P(cfg["train_sketch_dir"] if split == "train" else cfg["test_sketch_dir"])
201
+ out_fb = P(cfg["train_fabric_dir"] if split == "train" else cfg["test_fabric_dir"])
202
+ stem = str(Path(str(row.get("gt") or rid)).stem)
203
+ err: Optional[str] = None
204
+ bgr = cv2.imread(str(img_path), cv2.IMREAD_COLOR)
205
+ if bgr is None:
206
+ return rid, "read_fail"
207
+ _, err = sketch_fabric.process_one_sample(
208
+ img_path,
209
+ out_sk,
210
+ out_fb,
211
+ stem,
212
+ int(cfg["fabric_patch"]),
213
+ )
214
+ return stem, err
215
+
216
+
217
+ def stage_enrich(cfg: PipelineConfig) -> None:
218
+ idx_path = cfg.work_dir / "index.jsonl"
219
+ rows = _load_jsonl(idx_path)
220
+ # Only enrich TRAIN split. We intentionally do not create test_* modalities.
221
+ rows = [
222
+ r
223
+ for r in rows
224
+ if r.get("use_in_training", True)
225
+ and r.get("image_512")
226
+ and str(r.get("split") or "train").lower() == "train"
227
+ ]
228
+ cfg.train_sketch_dir.mkdir(parents=True, exist_ok=True)
229
+ cfg.train_fabric_dir.mkdir(parents=True, exist_ok=True)
230
+ cfg_dict: dict[str, Any] = {
231
+ "train_sketch_dir": str(cfg.train_sketch_dir),
232
+ "train_fabric_dir": str(cfg.train_fabric_dir),
233
+ "fabric_patch": cfg.enrich.fabric_patch,
234
+ }
235
+ jobs = [(r, cfg_dict) for r in rows]
236
+ errs: list[tuple[str, str]] = []
237
+ n_workers = _default_workers(cfg)
238
+ if n_workers <= 1:
239
+ for job in tqdm(jobs, desc="enrich"):
240
+ rid, err = _enrich_job(job)
241
+ if err:
242
+ errs.append((rid, err))
243
+ else:
244
+ with ProcessPoolExecutor(max_workers=n_workers) as ex:
245
+ futs = [ex.submit(_enrich_job, job) for job in jobs]
246
+ for fut in tqdm(as_completed(futs), total=len(futs), desc="enrich"):
247
+ rid, err = fut.result()
248
+ if err:
249
+ errs.append((rid, err))
250
+
251
+ if errs:
252
+ p = cfg.work_dir / "enrich_errors.txt"
253
+ p.write_text("\n".join(f"{a}\t{b}" for a, b in errs), encoding="utf-8")
254
+
255
+
256
+ def stage_package(cfg: PipelineConfig) -> Path:
257
+ idx_path = cfg.work_dir / "index.jsonl"
258
+ rows = _load_jsonl(idx_path)
259
+ outs = package.write_equifashion_style_outputs(rows, cfg)
260
+ return outs["train_json"]
261
+
262
+
263
+ def run_stages(cfg: PipelineConfig, stages: list[str]) -> None:
264
+ order = ["ingest", "standardize", "dedup", "taxonomy", "text", "enrich", "package"]
265
+ want = set(stages)
266
+ if "all" in want:
267
+ want = set(order)
268
+ for name in order:
269
+ if name not in want:
270
+ continue
271
+ if name == "ingest":
272
+ stage_ingest(cfg)
273
+ elif name == "standardize":
274
+ stage_standardize(cfg)
275
+ elif name == "dedup":
276
+ stage_dedup(cfg)
277
+ elif name == "taxonomy":
278
+ stage_taxonomy(cfg)
279
+ elif name == "text":
280
+ stage_text(cfg)
281
+ elif name == "enrich":
282
+ stage_enrich(cfg)
283
+ elif name == "package":
284
+ out = stage_package(cfg)
285
+ print(f"Wrote manifest: {out}")
286
+
287
+
288
+ def main_cli() -> None:
289
+ import argparse
290
+
291
+ ap = argparse.ArgumentParser(description="EquiFashion-style data pipeline")
292
+ ap.add_argument("--config", type=Path, default=Path("pipeline_config.yaml"))
293
+ ap.add_argument(
294
+ "--stage",
295
+ default="all",
296
+ help="Comma-separated: ingest,standardize,dedup,taxonomy,text,enrich,package,all",
297
+ )
298
+ ap.add_argument("--init-config", action="store_true", help="Write defaults to --config and exit")
299
+ args = ap.parse_args()
300
+
301
+ if args.init_config:
302
+ from .config import write_default_config
303
+
304
+ write_default_config(args.config.resolve())
305
+ print(f"Wrote {args.config}")
306
+ return
307
+
308
+ cfg = load_config(args.config.resolve())
309
+ stages = [s.strip() for s in args.stage.split(",") if s.strip()]
310
+ run_stages(cfg, stages)
EquiFashionDB_pipeline/sketch_fabric.py CHANGED
@@ -2,7 +2,6 @@
2
 
3
  from __future__ import annotations
4
 
5
- import json
6
  from pathlib import Path
7
  from typing import Optional, Tuple
8
 
@@ -10,75 +9,9 @@ import cv2
10
  import numpy as np
11
 
12
 
13
- def load_pose_candidates(pose_path: Path) -> Optional[np.ndarray]:
14
- if not pose_path.is_file():
15
- return None
16
- with open(pose_path, encoding="utf-8") as f:
17
- data = json.load(f)
18
- cand = data.get("candidate")
19
- if not cand:
20
- return None
21
- arr = np.asarray(cand, dtype=np.float64)
22
- if arr.ndim != 2 or arr.shape[1] < 4:
23
- return None
24
- return arr
25
-
26
-
27
- def pose_mask_from_candidates(
28
- candidates: np.ndarray,
29
- hw: Tuple[int, int],
30
- conf_thresh: float = 0.25,
31
- dilate_px: int = 24,
32
- ) -> np.ndarray:
33
  h, w = hw
34
- mask = np.zeros((h, w), dtype=np.uint8)
35
- pts = []
36
- for row in candidates:
37
- x, y, conf = float(row[0]), float(row[1]), float(row[2])
38
- if conf < conf_thresh:
39
- continue
40
- xi = int(round(np.clip(x, 0, w - 1)))
41
- yi = int(round(np.clip(y, 0, h - 1)))
42
- pts.append([xi, yi])
43
- pts = np.asarray(pts, dtype=np.int32)
44
- if len(pts) >= 3:
45
- hull = cv2.convexHull(pts)
46
- cv2.fillConvexPoly(mask, hull, 255)
47
- elif len(pts) == 2:
48
- cv2.line(mask, tuple(pts[0]), tuple(pts[1]), 255, thickness=max(dilate_px, 8))
49
- elif len(pts) == 1:
50
- cv2.circle(mask, tuple(pts[0]), dilate_px * 2, 255, thickness=-1)
51
- else:
52
- return fallback_center_mask(hw)
53
-
54
- if dilate_px > 0:
55
- k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (dilate_px * 2 + 1, dilate_px * 2 + 1))
56
- mask = cv2.dilate(mask, k, iterations=1)
57
- return mask
58
-
59
-
60
- def fallback_center_mask(hw: Tuple[int, int], margin: float = 0.08) -> np.ndarray:
61
- h, w = hw
62
- mask = np.zeros((h, w), dtype=np.uint8)
63
- x0 = int(w * margin)
64
- y0 = int(h * margin)
65
- x1 = int(w * (1 - margin))
66
- y1 = int(h * (1 - margin))
67
- mask[y0:y1, x0:x1] = 255
68
- return mask
69
-
70
-
71
- def build_garment_mask(
72
- pose_json: Optional[Path],
73
- hw: Tuple[int, int],
74
- conf_thresh: float,
75
- ) -> np.ndarray:
76
- if pose_json is None:
77
- return fallback_center_mask(hw)
78
- cand = load_pose_candidates(pose_json)
79
- if cand is None:
80
- return fallback_center_mask(hw)
81
- return pose_mask_from_candidates(cand, hw, conf_thresh=conf_thresh)
82
 
83
 
84
  def sketch_canny_masked(
@@ -148,15 +81,13 @@ def process_one_sample(
148
  out_sketch: Path,
149
  out_fabric: Path,
150
  stem: str,
151
- pose_json: Optional[Path],
152
- conf_thresh: float,
153
  fabric_patch: int,
154
  ) -> Tuple[str, Optional[str]]:
155
  bgr = cv2.imread(str(image_path), cv2.IMREAD_COLOR)
156
  if bgr is None:
157
  return stem, f"failed read: {image_path}"
158
  h, w = bgr.shape[:2]
159
- mask = build_garment_mask(pose_json, (h, w), conf_thresh=conf_thresh)
160
  sketch = sketch_canny_masked(bgr, mask)
161
  fabric = best_texture_patch(bgr, mask, patch_size=fabric_patch)
162
  out_sketch.mkdir(parents=True, exist_ok=True)
 
2
 
3
  from __future__ import annotations
4
 
 
5
  from pathlib import Path
6
  from typing import Optional, Tuple
7
 
 
9
  import numpy as np
10
 
11
 
12
+ def full_image_mask(hw: Tuple[int, int]) -> np.ndarray:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  h, w = hw
14
+ return np.full((h, w), 255, dtype=np.uint8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
 
17
  def sketch_canny_masked(
 
81
  out_sketch: Path,
82
  out_fabric: Path,
83
  stem: str,
 
 
84
  fabric_patch: int,
85
  ) -> Tuple[str, Optional[str]]:
86
  bgr = cv2.imread(str(image_path), cv2.IMREAD_COLOR)
87
  if bgr is None:
88
  return stem, f"failed read: {image_path}"
89
  h, w = bgr.shape[:2]
90
+ mask = full_image_mask((h, w))
91
  sketch = sketch_canny_masked(bgr, mask)
92
  fabric = best_texture_patch(bgr, mask, patch_size=fabric_patch)
93
  out_sketch.mkdir(parents=True, exist_ok=True)
EquiFashionDB_pipeline/standardize.py CHANGED
@@ -18,7 +18,8 @@ def letterbox_square_bgr(bgr: np.ndarray, size: int) -> np.ndarray:
18
  nw = max(1, int(round(w * scale)))
19
  nh = max(1, int(round(h * scale)))
20
  resized = cv2.resize(bgr, (nw, nh), interpolation=cv2.INTER_AREA)
21
- out = np.zeros((size, size, 3), dtype=np.uint8)
 
22
  pad_y = (size - nh) // 2
23
  pad_x = (size - nw) // 2
24
  out[pad_y : pad_y + nh, pad_x : pad_x + nw] = resized
@@ -35,3 +36,16 @@ def write_jpg(path: Path, bgr: np.ndarray, quality: int = 92) -> None:
35
  cv2.imwrite(str(path), bgr, [int(cv2.IMWRITE_JPEG_QUALITY), quality])
36
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  nw = max(1, int(round(w * scale)))
19
  nh = max(1, int(round(h * scale)))
20
  resized = cv2.resize(bgr, (nw, nh), interpolation=cv2.INTER_AREA)
21
+ # Padding nền trắng để tránh viền đen ảnh hưởng Canny/edge.
22
+ out = np.full((size, size, 3), 255, dtype=np.uint8)
23
  pad_y = (size - nh) // 2
24
  pad_x = (size - nw) // 2
25
  out[pad_y : pad_y + nh, pad_x : pad_x + nw] = resized
 
36
  cv2.imwrite(str(path), bgr, [int(cv2.IMWRITE_JPEG_QUALITY), quality])
37
 
38
 
39
+ def write_image(path: Path, bgr: np.ndarray) -> None:
40
+ """
41
+ Write image using file extension.
42
+ Supports .jpg/.jpeg/.png/.webp (via OpenCV).
43
+ """
44
+ path.parent.mkdir(parents=True, exist_ok=True)
45
+ suf = path.suffix.lower()
46
+ if suf in {".jpg", ".jpeg"}:
47
+ write_jpg(path, bgr)
48
+ return
49
+ cv2.imwrite(str(path), bgr)
50
+
51
+