Jules Musquin commited on
Commit
c6e077b
·
1 Parent(s): 2839cb6

update on html_generator

Browse files
Files changed (9) hide show
  1. .gitignore +3 -1
  2. .python-version +1 -0
  3. html_generator.py +180 -0
  4. main.py +6 -0
  5. pyproject.toml +11 -0
  6. requirement.txt +2 -2
  7. split.py +0 -1
  8. uv.lock +0 -0
  9. visualisation.py +0 -80
.gitignore CHANGED
@@ -8,6 +8,7 @@ share/
8
  log/
9
  lib64
10
  pyvenv.cfg
 
11
  # Variables d'environnement — NE JAMAIS commiter ce fichier !
12
  .env
13
 
@@ -23,4 +24,5 @@ lib/
23
  lib64/
24
 
25
  #website
26
- generated_html/
 
 
8
  log/
9
  lib64
10
  pyvenv.cfg
11
+
12
  # Variables d'environnement — NE JAMAIS commiter ce fichier !
13
  .env
14
 
 
24
  lib64/
25
 
26
  #website
27
+ generated_html/
28
+ annotations/
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.13
html_generator.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import os
3
+ import numpy as np
4
+ import glob
5
+ import matplotlib.pyplot as plt
6
+
7
+ from collections import Counter
8
+ from PIL import Image, ImageDraw, ImageFont
9
+ from tqdm import tqdm
10
+ from ultralytics.utils.plotting import Annotator, colors
11
+
12
+ images_path = "./images"
13
+ labels_path = "./labels"
14
+
15
+ images = glob.glob(os.path.join(images_path, "*.jpg")) + \
16
+ glob.glob(os.path.join(images_path, "*.JPG"))
17
+
18
+ label_map = {
19
+ 0: "Illustration",
20
+ 1: "Initial",
21
+ 2: "Ornament",
22
+ 3: "Stamp",
23
+ 4: "Table",
24
+ }
25
+
26
+ output_dir = "./generated_html"
27
+ if os.path.isdir(output_dir):
28
+ print(f"{output_dir} existe déjà")
29
+ else:
30
+ os.mkdir(output_dir)
31
+
32
+ annotations_dir = "./annotations"
33
+ if os.path.isdir(annotations_dir):
34
+ print(f"{annotations_dir} existe déjà")
35
+ else:
36
+ os.mkdir(annotations_dir)
37
+
38
+
39
+ def classes_visualisation(labels_path: str, label_map: dict, output_dir: str):
40
+ total_files = 0
41
+ total_labels = []
42
+
43
+ for filename in os.listdir(labels_path):
44
+ if not filename.endswith(".txt"):
45
+ continue
46
+
47
+ total_files += 1
48
+ input_path = os.path.join(labels_path, filename)
49
+
50
+ with open(input_path, "r") as f:
51
+ lines = f.readlines()
52
+
53
+ for line in lines:
54
+ parts = line.strip().split()
55
+ if not parts:
56
+ continue
57
+ label = int(parts[0])
58
+ total_labels.append(label)
59
+
60
+ counts = Counter(total_labels)
61
+ labels = [label_map[k] for k in counts.keys()]
62
+ values = list(counts.values())
63
+ total_count = sum(values)
64
+
65
+ # Fonction pour afficher pourcentage + valeur absolue dans chaque part
66
+ def make_autopct(values):
67
+ def my_autopct(pct):
68
+ absolute = int(round(pct / 100.0 * sum(values)))
69
+ return f"{pct:.1f}%\n({absolute})"
70
+ return my_autopct
71
+
72
+ plt.figure(figsize=(7, 7))
73
+ plt.pie(
74
+ values,
75
+ labels=labels,
76
+ autopct=make_autopct(values),
77
+ textprops={"fontsize": 9},
78
+ )
79
+ plt.title(
80
+ f"GenHisDoc classes distribution\n"
81
+ f"Total files: {total_files} | Total labels: {total_count}"
82
+ )
83
+
84
+ # Légende avec le détail des effectifs par classe
85
+ legend_labels = [f"{lab} (n={val})" for lab, val in zip(labels, values)]
86
+ plt.legend(
87
+ legend_labels,
88
+ title="Classes",
89
+ loc="center left",
90
+ bbox_to_anchor=(1, 0, 0.5, 1),
91
+ )
92
+
93
+ plt.tight_layout()
94
+ plt.savefig(
95
+ os.path.join(output_dir, "GenHisDoc_class_distribution.png"),
96
+ bbox_inches="tight",
97
+ )
98
+ plt.close()
99
+
100
+ with open(f"{output_dir}/index.html", "w") as f:
101
+ f.write(
102
+ """<!DOCTYPE html>
103
+ <html>
104
+ <head>
105
+ <meta charset="UTF-8">
106
+ <link type="text/css" rel="stylesheet" href="style.css">
107
+ </head>
108
+ <body>
109
+ <header>
110
+ </header>
111
+ <img src="./GenHisDoc_class_distribution.png">
112
+ </body>
113
+ </html>
114
+ """
115
+ )
116
+
117
+ def draw_yolo_annotations(image_path: str, label_path: str, label_map: dict) -> Image.Image | None:
118
+ """Dessine les bounding boxes YOLO sur l'image et retourne une PIL Image."""
119
+ if not os.path.exists(image_path):
120
+ print(f"Image introuvable : {image_path}")
121
+ return None
122
+
123
+ if not os.path.exists(label_path):
124
+ print(f"Label introuvable : {label_path}")
125
+ return None
126
+ img = np.array(Image.open(image_path).convert("RGB"))
127
+ h, w = img.shape[:2]
128
+ annotator = Annotator(img, line_width=2)
129
+
130
+ with open(label_path, "r") as f:
131
+ for line in f:
132
+ parts = line.strip().split()
133
+ if len(parts) < 5:
134
+ continue
135
+ cls_id = int(parts[0])
136
+ cx, cy, bw, bh = map(float, parts[1:5])
137
+ # Conversion YOLO (normalisé) → pixels (x1, y1, x2, y2)
138
+ x1 = int((cx - bw / 2) * w)
139
+ y1 = int((cy - bh / 2) * h)
140
+ x2 = int((cx + bw / 2) * w)
141
+ y2 = int((cy + bh / 2) * h)
142
+ label = label_map.get(cls_id, str(cls_id))
143
+ annotator.box_label([x1, y1, x2, y2], label=label, color=colors(cls_id, True))
144
+
145
+ result = annotator.result()
146
+ return Image.fromarray(result)
147
+
148
+ def controle(label_map: dict):
149
+ images_dir = images_path
150
+ labels_dir = labels_path
151
+ identifier_list = []
152
+ annotations_crées = 0
153
+ annotations_ignorées = 0
154
+ print("génération des annotations")
155
+
156
+ for filename in tqdm(os.listdir(labels_dir)):
157
+ if not filename.endswith(".txt"):
158
+ continue
159
+ identifier = filename.replace(".txt", "")
160
+ identifier_list.append(identifier)
161
+ output_path = os.path.join(annotations_dir, f"{identifier}.jpg")
162
+ image = draw_yolo_annotations(
163
+ os.path.join(images_dir, f"{identifier}.jpg"),
164
+ os.path.join(labels_dir, f"{identifier}.txt"),
165
+ label_map,
166
+ )
167
+ if image is None:
168
+ annotations_ignorées += 1
169
+ continue
170
+ if not os.path.isfile(output_path):
171
+ image.save(output_path)
172
+ annotations_crées += 1
173
+ else:
174
+ annotations_ignorées += 1
175
+
176
+ print(f"Annotations créées : {annotations_crées}")
177
+ print(f"Annotations ignorées : {annotations_ignorées}")
178
+
179
+ classes_visualisation(labels_path, label_map, output_dir)
180
+ #controle(label_map)
main.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ def main():
2
+ print("Hello from genhisdoc-dataset!")
3
+
4
+
5
+ if __name__ == "__main__":
6
+ main()
pyproject.toml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "genhisdoc-dataset"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ dependencies = [
8
+ "matplotlib>=3.11.0",
9
+ "tqdm>=4.68.4",
10
+ "ultralytics>=8.4.92",
11
+ ]
requirement.txt CHANGED
@@ -34,7 +34,6 @@ nvidia-nvshmem-cu13==3.4.5
34
  nvidia-nvtx==13.0.85
35
  opencv-python==5.0.0.93
36
  packaging==26.2
37
- pathlib==1.0.1
38
  pillow==12.3.0
39
  polars==1.42.1
40
  polars-runtime-32==1.42.1
@@ -48,8 +47,9 @@ six==1.17.0
48
  sympy==1.14.0
49
  torch==2.13.0
50
  torchvision==0.28.0
 
51
  triton==3.7.1
52
  typing_extensions==4.16.0
53
- ultralytics==8.4.91
54
  ultralytics-thop==2.0.20
55
  urllib3==2.7.0
 
34
  nvidia-nvtx==13.0.85
35
  opencv-python==5.0.0.93
36
  packaging==26.2
 
37
  pillow==12.3.0
38
  polars==1.42.1
39
  polars-runtime-32==1.42.1
 
47
  sympy==1.14.0
48
  torch==2.13.0
49
  torchvision==0.28.0
50
+ tqdm==4.68.4
51
  triton==3.7.1
52
  typing_extensions==4.16.0
53
+ ultralytics==8.4.92
54
  ultralytics-thop==2.0.20
55
  urllib3==2.7.0
split.py CHANGED
@@ -9,7 +9,6 @@ import random
9
  current_dir = "./images"
10
  val_pct = 10 # 10% validation
11
  test_pct = 10 # 10% test
12
- # le reste (80%) va dans train
13
 
14
  # Récupère toutes les images (en gérant .jpg et .JPG)
15
  images = glob.glob(os.path.join(current_dir, "*.jpg")) + \
 
9
  current_dir = "./images"
10
  val_pct = 10 # 10% validation
11
  test_pct = 10 # 10% test
 
12
 
13
  # Récupère toutes les images (en gérant .jpg et .JPG)
14
  images = glob.glob(os.path.join(current_dir, "*.jpg")) + \
uv.lock ADDED
The diff for this file is too large to render. See raw diff
 
visualisation.py DELETED
@@ -1,80 +0,0 @@
1
- from pathlib import Path
2
- from PIL import Image, ImageDraw, ImageFont
3
- from tqdm import tqdm
4
- import random
5
- import os
6
- import numpy as np
7
- from ultralytics.utils.plotting import Annotator, colors
8
-
9
-
10
- def draw_yolo_annotations(image_path: Path, label_path: Path, label_map: dict) -> Image.Image | None:
11
- """Dessine les bounding boxes YOLO sur l'image et retourne une PIL Image."""
12
- if not image_path.exists():
13
- print(f"Image introuvable : {image_path}")
14
- return None
15
- if not label_path.exists():
16
- print(f"Label introuvable : {label_path}")
17
- return None
18
- img = np.array(Image.open(image_path).convert("RGB"))
19
- h, w = img.shape[:2]
20
- annotator = Annotator(img, line_width=2)
21
- with open(label_path, "r") as f:
22
- for line in f:
23
- parts = line.strip().split()
24
- if len(parts) < 5:
25
- continue
26
- cls_id = int(parts[0])
27
- cx, cy, bw, bh = map(float, parts[1:5])
28
- # Conversion YOLO (normalisé) → pixels (x1, y1, x2, y2)
29
- x1 = int((cx - bw / 2) * w)
30
- y1 = int((cy - bh / 2) * h)
31
- x2 = int((cx + bw / 2) * w)
32
- y2 = int((cy + bh / 2) * h)
33
- label = label_map.get(cls_id, str(cls_id))
34
- annotator.box_label([x1, y1, x2, y2], label=label, color=colors(cls_id, True))
35
-
36
- result = annotator.result()
37
- return Image.fromarray(result)
38
-
39
- def controle():
40
-
41
- label_map = {
42
- 0: "Illustration",
43
- 1: "Ornament",
44
- 2: "Initial",
45
- 3: "Stamp",
46
- 4: "Table",
47
- }
48
-
49
- images_dir = Path("images")
50
- labels_dir = Path("labels")
51
-
52
- identifier_list = []
53
- annotations_crées = 0
54
- annotations_ignorées = 0
55
-
56
- print("génération des annotations")
57
-
58
- for filename in tqdm(os.listdir(labels_dir)):
59
- if not filename.endswith(".txt"):
60
- continue
61
- identifier = filename.replace(".txt", "")
62
- output_path = Path(f'annotations/{identifier}.jpg')
63
-
64
- image = draw_yolo_annotations(
65
- images_dir / f'{identifier}.jpg',
66
- labels_dir / f'{identifier}.txt',
67
- label_map,
68
- )
69
-
70
- if image is None:
71
- annotations_ignorées += 1
72
- continue # on passe à l'image suivante
73
-
74
- if not output_path.is_file():
75
- image.save(output_path)
76
- annotations_crées += 1
77
- else:
78
- annotations_ignorées += 1
79
-
80
- controle()