mchelali commited on
Commit
0b37fd3
·
verified ·
1 Parent(s): 086ae43

Delete forbin_dataset.py

Browse files
Files changed (1) hide show
  1. forbin_dataset.py +0 -176
forbin_dataset.py DELETED
@@ -1,176 +0,0 @@
1
- from collections import defaultdict
2
- import json
3
- import os
4
- import datasets
5
- from datasets import (
6
- Value,
7
- Image,
8
- Sequence,
9
- ClassLabel,
10
- )
11
- from typing import Dict, Any
12
- import tarfile
13
- from io import BytesIO
14
-
15
- _DESCRIPTION = """
16
- Forbin Dataset — a curated collection of heritage photographs and documents, combining digitized facsimiles, historical context, and fine-grained annotations.
17
-
18
- This collection brings together images from the archives of the French explorer and writer Victor Forbin (1868–1947), enhanced with semantic structures following the COCO Segmentation format for scientific reuse.
19
- """
20
- _HOMEPAGE = "https://huggingface.co/mchelali/forbin_dataset"
21
- _LICENSE = "CC-BY-NC-4.0" # Licence de votre choix
22
- _ANNOTATIONS_JSON = "forbin_annotated.json"
23
-
24
-
25
- def _load_image_from_tar(
26
- dl_manager: datasets.DownloadManager,
27
- repo_url: str,
28
- tar_filename: str,
29
- image_key_in_tar: str,
30
- ) -> BytesIO:
31
- """
32
- Fonction CRITIQUE : Ouvre un fichier .tar distant en streaming et extrait un fichier spécifique par sa clé.
33
- """
34
- tar_url = f"{repo_url}/{tar_filename}"
35
-
36
- # 1. Ouverture du fichier .tar en streaming via l'outil de téléchargement de datasets
37
- # Cela évite de télécharger le fichier en entier.
38
- with dl_manager.open(tar_url) as f:
39
- # 2. Utilisation de tarfile pour lire le flux. Le mode 'r|*' est pour la lecture par flux (non-seekable).
40
- with tarfile.open(fileobj=f, mode="r|*") as tar:
41
- try:
42
- # 3. Recherche du membre (l'image) par son chemin exact à l'intérieur du .tar
43
- member = tar.getmember(image_key_in_tar)
44
- except KeyError:
45
- raise FileNotFoundError(
46
- f"Image '{image_key_in_tar}' non trouvée dans {tar_filename}."
47
- )
48
-
49
- # 4. Extraction du contenu binaire de l'image
50
- image_file = tar.extractfile(member)
51
- if image_file is None:
52
- raise Exception(
53
- f"Impossible d'extraire le fichier pour {image_key_in_tar}."
54
- )
55
-
56
- # 5. Lecture du contenu dans un objet BytesIO pour la feature Image()
57
- return BytesIO(image_file.read())
58
-
59
-
60
- class ForbinDataset(datasets.GeneratorBasedBuilder):
61
-
62
- VERSION = datasets.Version("1.0.0")
63
-
64
- # Définir le fichier de données (le manifeste Parquet)
65
- DEFAULT_CONFIG_NAME = "default"
66
- BUILDER_CONFIGS = [
67
- datasets.BuilderConfig(
68
- name=DEFAULT_CONFIG_NAME,
69
- version=VERSION,
70
- description=_DESCRIPTION,
71
- )
72
- ]
73
-
74
- def _info(self) -> datasets.DatasetInfo:
75
- # Définition des catégories
76
- categories = ["legende", "texte", "image", "tampon", "etc"]
77
-
78
- features = datasets.Features(
79
- {
80
- "image_id": Value("int32"),
81
- # Utiliser Image() avec les URL générées (pipe:curl...)
82
- "recto_image": Image(),
83
- "verso_image": Image(),
84
- # "tar_file": Value("string"),
85
- # "dpi": Value("float32"),
86
- "Carton": Value("string"),
87
- "Pays": Value("string"),
88
- # ...
89
- "annotations": Sequence(
90
- {
91
- # ... Définition des champs d'annotations
92
- "id": Value("int32"),
93
- "category_id": ClassLabel(names=categories),
94
- "bbox": Sequence(Value("float32")),
95
- "text": Value("string"),
96
- # ...
97
- }
98
- ),
99
- }
100
- )
101
- return datasets.DatasetInfo(description=_DESCRIPTION, features=features)
102
-
103
- def _split_generators(
104
- self, dl_manager: datasets.DownloadManager
105
- ) -> list[datasets.SplitGenerator]:
106
-
107
- urls = {"annotations": os.path.join(dl_manager.manual_dir, _ANNOTATIONS_JSON)}
108
- downloaded_files = dl_manager.download(urls)
109
-
110
- return [
111
- datasets.SplitGenerator(
112
- name=datasets.Split.TRAIN,
113
- gen_kwargs={"annotations_filepath": downloaded_files["annotations"]},
114
- )
115
- ]
116
-
117
- def _generate_examples(self, annotations_filepath: str):
118
- """Lit le manifeste Parquet et génère les exemples."""
119
-
120
- # Lire le fichier Parquet
121
- repo_id = "mchelali/forbin_dataset"
122
- repo_url = f"https://huggingface.co/datasets/{repo_id}/resolve/main/data"
123
-
124
- with open(annotations_filepath, "r", encoding="utf-8") as f:
125
- annotations = json.load(f)
126
-
127
- for _id, record in enumerate(annotations):
128
-
129
- # Conversion de la chaîne JSON des annotations en objet Python
130
- # --- STRUCTURE DE VOTRE ENREGISTREMENT JSON (À ADAPTER) ---
131
- image_id = record.get("image_id", str(_id))
132
- annotations_data = record.get(
133
- "annotations", {}
134
- ) # Votre champ d'annotations
135
- recto_path_in_tar = record["recto_path"] # Ex: SHDGR.../0001.jpg
136
- verso_path_in_tar = record["verso_path"] # Ex: SHDGR.../0002.jpg
137
- # -----------------------------------------------------------
138
-
139
- # 2. Déduction du nom de l'archive .tar (le dossier parent ou la clé principale)
140
- # Cette logique suppose que le nom du dossier parent de l'image est aussi la base du nom du .tar
141
- tar_name = (
142
- recto_path_in_tar.split(os.path.sep)[2] + ".tar"
143
- ) # Ex: SHDGR..._2.tar
144
-
145
- try:
146
- # 3. Chargement de l'image Recto
147
- recto_image_bytes = _load_image_from_tar(
148
- self.dl_manager, repo_url, tar_name, recto_path_in_tar
149
- )
150
-
151
- # 4. Chargement de l'image Verso
152
- verso_image_bytes = _load_image_from_tar(
153
- self.dl_manager, repo_url, tar_name, verso_path_in_tar
154
- )
155
-
156
- # 5. Génération de l'exemple
157
- yield _id, {
158
- "id": image_id,
159
- # L'Image feature de datasets utilise le dict {"path": ..., "bytes": ...} pour charger l'image.
160
- "recto_image": {
161
- "path": recto_path_in_tar,
162
- "bytes": recto_image_bytes,
163
- },
164
- "verso_image": {
165
- "path": verso_path_in_tar,
166
- "bytes": verso_image_bytes,
167
- },
168
- "annotations": json.dumps(annotations_data),
169
- }
170
-
171
- except Exception as e:
172
- # Gérer les erreurs de fichiers manquants ou de lecture
173
- print(f"ERREUR (Exemple {_id}): {e}")
174
- continue
175
-
176
- _id += 1