-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_atlas.py
146 lines (126 loc) · 5.53 KB
/
create_atlas.py
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
from nomic import embed, AtlasDataset
import os
from PIL import Image, UnidentifiedImageError
import uuid
import numpy as np
from PyPDF2 import PdfReader
# Chemins des répertoires
CASE_DIR = "Kyron_Horman"
TEXT_DIRS = {
"podcast_topics": os.path.join(CASE_DIR, "podcast_topics"),
"scraped_sources": os.path.join(CASE_DIR, "scraped_sources"),
"others": os.path.join(CASE_DIR, "texts")
}
PDF_DIR = os.path.join(CASE_DIR, "official_documents")
IMAGE_DIR = os.path.join(CASE_DIR, "images")
def load_texts():
"""Charge les fichiers texte des répertoires spécifiés et les intègre comme entrées au dataset."""
all_text_data = []
for category, text_dir in TEXT_DIRS.items():
if not os.path.exists(text_dir):
continue
for filename in os.listdir(text_dir):
if filename.endswith('.txt'):
try:
with open(os.path.join(text_dir, filename), 'r', encoding='utf-8') as f:
text_content = f.read().strip()
all_text_data.append({
"type": "text",
"filename": f"text_{uuid.uuid4().hex[:8]}", # Identifier unique
"content_type": category,
"content": text_content
})
except Exception as e:
print(f"Erreur lecture fichier texte {filename}: {e}")
return all_text_data
def load_pdfs():
"""Extrait le texte des fichiers PDF et les intègre comme entrées au dataset."""
all_pdf_data = []
if not os.path.exists(PDF_DIR):
return all_pdf_data
for filename in os.listdir(PDF_DIR):
if filename.lower().endswith('.pdf'):
pdf_path = os.path.join(PDF_DIR, filename)
try:
reader = PdfReader(pdf_path)
all_text = ""
for page in reader.pages:
text = page.extract_text()
if text:
all_text += text.strip()
all_pdf_data.append({
"type": "text",
"filename": f"pdf_{uuid.uuid4().hex[:8]}", # Identifier unique
"content_type": "official_document",
"content": all_text
})
except Exception as e:
print(f"Impossible de lire le PDF {filename}: {str(e)}")
return all_pdf_data
def load_images():
"""Charge les images en vérifiant les formats et les intègre comme entrées au dataset."""
all_image_data = []
if not os.path.exists(IMAGE_DIR):
return all_image_data
for filename in os.listdir(IMAGE_DIR):
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
try:
img_path = os.path.join(IMAGE_DIR, filename)
with Image.open(img_path) as img:
img.verify()
# Création d'un nom unique pour chaque image
extension = img.format.lower() if img.format else "jpg" # Par défaut .jpg
all_image_data.append({
"type": "image",
"filename": f"image_{uuid.uuid4().hex[:8]}.{extension}", # Identifier unique
"content_type": "evidence",
"content": img_path # Chemin absolu vers l'image
})
except UnidentifiedImageError:
print(f"Image non valide ignorée : {filename}")
return all_image_data
def create_case_map():
"""Crée une carte multimodale combinant textes et images."""
text_data = load_texts()
pdf_data = load_pdfs()
image_data = load_images()
# Texte total = fichiers texte + PDF
all_text_data = text_data + pdf_data
print(f"Chargé : {len(all_text_data)} documents texte et {len(image_data)} images.")
# Création du dataset sur Atlas
dataset = AtlasDataset(
identifier=f"kyron-horman-multimodal-{uuid.uuid4().hex[:8]}",
description="Carte multimodale textes/images.",
unique_id_field="filename", # Identifier unique pour chaque entrée,
is_public=True
)
if all_text_data:
# Récupérer les contenus textuels
text_contents = [item['content'] for item in all_text_data]
# Générer les embeddings pour les textes
text_embeddings = embed.text(
texts=text_contents,
model="nomic-embed-text-v1.5"
)['embeddings']
# Convertir en tableau NumPy 2D
text_embeddings = np.array(text_embeddings)
dataset.add_data(data=all_text_data, embeddings=text_embeddings)
if image_data:
# Générer les embeddings pour les images
image_paths = [img['content'] for img in image_data if os.path.exists(img['content'])]
image_embeddings = embed.image(
images=image_paths,
model="nomic-embed-vision-v1.5"
)['embeddings']
# Convertir en tableau NumPy 2D
image_embeddings = np.array(image_embeddings)
dataset.add_data(data=image_data, embeddings=image_embeddings)
# Créer un index et générer un lien pour la carte
return dataset.create_index(name="multimodal-map", modality="embedding", topic_model={"build_topic_model": True, "topic_label_field": "content"}).dataset_link
if __name__ == "__main__":
print("Création de la carte multimodale Atlas...")
try:
atlas_url = create_case_map()
print(f"Carte disponible à : {atlas_url}")
except Exception as e:
print(f"Erreur : {e}")