You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
210 lines
7.1 KiB
210 lines
7.1 KiB
import pymongo
|
|
from datetime import datetime
|
|
from config import MONGODB_URL, MONGODB_USERNAME, MONGODB_PASSWORD, MONGODB_DATABASE
|
|
from utils import get_password_hash
|
|
from PIL import Image
|
|
import io
|
|
import os
|
|
import uuid
|
|
import hashlib
|
|
|
|
client = pymongo.MongoClient(MONGODB_URL, username=MONGODB_USERNAME, password=MONGODB_PASSWORD)
|
|
db = client[MONGODB_DATABASE]
|
|
|
|
# Créer le dossier pour stocker les images s'il n'existe pas
|
|
IMAGES_DIR = "images"
|
|
if not os.path.exists(IMAGES_DIR):
|
|
os.makedirs(IMAGES_DIR)
|
|
|
|
def create_test_image(color='red', size=(100, 100)):
|
|
img = Image.new('RGB', size, color=color)
|
|
img_byte_arr = io.BytesIO()
|
|
img.save(img_byte_arr, format='JPEG')
|
|
img_byte_arr.seek(0)
|
|
return img_byte_arr
|
|
|
|
def process_image(file_path: str) -> tuple[str, str]:
|
|
"""Traite et optimise l'image"""
|
|
with Image.open(file_path) as img:
|
|
# Convertir en RGB si nécessaire
|
|
if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
|
|
bg = Image.new('RGB', img.size, (255, 255, 255))
|
|
bg.paste(img, mask=img.split()[-1])
|
|
img = bg
|
|
elif img.mode != 'RGB':
|
|
img = img.convert('RGB')
|
|
|
|
# Redimensionner si nécessaire pour le Full HD (1920x1080)
|
|
if img.size[0] > 1920 or img.size[1] > 1080:
|
|
img.thumbnail((1920, 1080), Image.Resampling.LANCZOS)
|
|
|
|
# Sauvegarder avec compression
|
|
img.save(file_path, 'JPEG', quality=85, optimize=True)
|
|
|
|
# Calculer le hash du fichier optimisé
|
|
with open(file_path, 'rb') as f:
|
|
file_hash = hashlib.sha256(f.read()).hexdigest()
|
|
|
|
return file_hash, 'jpg'
|
|
|
|
def populate_data():
|
|
users_collection = db["users"]
|
|
pins_collection = db["pins"]
|
|
images_collection = db["images"]
|
|
|
|
# Créer les utilisateurs
|
|
user1_id = users_collection.insert_one({
|
|
"username": "string",
|
|
"password": get_password_hash("string"),
|
|
"is_admin": True
|
|
}).inserted_id
|
|
|
|
user2_id = users_collection.insert_one({
|
|
"username": "test",
|
|
"password": get_password_hash("test"),
|
|
"is_admin": False
|
|
}).inserted_id
|
|
|
|
# Créer d'abord les pins
|
|
pin_a = pins_collection.insert_one({
|
|
"title": "Tour Eiffel",
|
|
"description": "Description A",
|
|
"complete_address": "Tour Eiffel, 5, Avenue Anatole France, Quartier du Gros-Caillou, Paris 7e Arrondissement, Paris, France métropolitaine, 75007, France",
|
|
"location": [48.858296, 2.294526],
|
|
"files": [],
|
|
"user_id": str(user1_id)
|
|
})
|
|
|
|
pin_b = pins_collection.insert_one({
|
|
"title": "Mont St Michel",
|
|
"description": "Description B",
|
|
"complete_address": "Mont Saint-Michel, Terrasse de l'Abside, Le Mont-Saint-Michel, Avranches, Manche, Normandie, France métropolitaine, 50170, France",
|
|
"location": [48.636111, -1.511389],
|
|
"files": [],
|
|
"user_id": str(user1_id)
|
|
})
|
|
|
|
pin_x = pins_collection.insert_one({
|
|
"title": "Eiffel Tower",
|
|
"description": "Description X",
|
|
"complete_address": "Tour Eiffel, 5, Avenue Anatole France, Quartier du Gros-Caillou, Paris 7e Arrondissement, Paris, France métropolitaine, 75007, France",
|
|
"location": [48.858296, 2.294526],
|
|
"files": [],
|
|
"user_id": str(user2_id)
|
|
})
|
|
|
|
pin_y = pins_collection.insert_one({
|
|
"title": "Mont Saint Michel",
|
|
"description": "Description Y",
|
|
"complete_address": "Mont Saint-Michel, Terrasse de l'Abside, Le Mont-Saint-Michel, Avranches, Manche, Normandie, France métropolitaine, 50170, France",
|
|
"location": [48.636111, -1.511389],
|
|
"files": [],
|
|
"user_id": str(user2_id)
|
|
})
|
|
|
|
# Créer les images de test
|
|
image_a = create_test_image(color='red')
|
|
image_b = create_test_image(color='blue')
|
|
image_x = create_test_image(color='green')
|
|
image_y = create_test_image(color='yellow')
|
|
|
|
# Sauvegarder temporairement les images
|
|
temp_paths = []
|
|
for img, name in [(image_a, 'a'), (image_b, 'b'), (image_x, 'x'), (image_y, 'y')]:
|
|
temp_path = os.path.join(IMAGES_DIR, f"temp_{name}.jpg")
|
|
with open(temp_path, 'wb') as f:
|
|
f.write(img.getvalue())
|
|
temp_paths.append(temp_path)
|
|
|
|
# Traiter les images et obtenir leurs hashes
|
|
image_hashes = []
|
|
for temp_path in temp_paths:
|
|
file_hash, extension = process_image(temp_path)
|
|
final_path = os.path.join(IMAGES_DIR, f"{file_hash}.{extension}")
|
|
|
|
# Si l'image n'existe pas déjà physiquement, la déplacer
|
|
if not os.path.exists(final_path):
|
|
os.rename(temp_path, final_path)
|
|
else:
|
|
os.remove(temp_path)
|
|
|
|
image_hashes.append(file_hash)
|
|
|
|
# Insérer les métadonnées des images dans la base de données avec leur pin_id
|
|
image_a_id = images_collection.insert_one({
|
|
"pin_id": pin_a.inserted_id,
|
|
"image_hash": image_hashes[0],
|
|
"metadata": {
|
|
"created_at": datetime.now().isoformat(),
|
|
"original_filename": "test_a.jpg",
|
|
"mime_type": "image/jpeg",
|
|
"size": len(image_a.getvalue())
|
|
},
|
|
"caption": "Tour Eiffel"
|
|
}).inserted_id
|
|
|
|
image_b_id = images_collection.insert_one({
|
|
"pin_id": pin_b.inserted_id,
|
|
"image_hash": image_hashes[1],
|
|
"metadata": {
|
|
"created_at": datetime.now().isoformat(),
|
|
"original_filename": "test_b.jpg",
|
|
"mime_type": "image/jpeg",
|
|
"size": len(image_b.getvalue())
|
|
},
|
|
"caption": "Mont St Michel"
|
|
}).inserted_id
|
|
|
|
image_x_id = images_collection.insert_one({
|
|
"pin_id": pin_x.inserted_id,
|
|
"image_hash": image_hashes[2],
|
|
"metadata": {
|
|
"created_at": datetime.now().isoformat(),
|
|
"original_filename": "test_x.jpg",
|
|
"mime_type": "image/jpeg",
|
|
"size": len(image_x.getvalue())
|
|
},
|
|
"caption": "Eiffel Tower"
|
|
}).inserted_id
|
|
|
|
image_y_id = images_collection.insert_one({
|
|
"pin_id": pin_y.inserted_id,
|
|
"image_hash": image_hashes[3],
|
|
"metadata": {
|
|
"created_at": datetime.now().isoformat(),
|
|
"original_filename": "test_y.jpg",
|
|
"mime_type": "image/jpeg",
|
|
"size": len(image_y.getvalue())
|
|
},
|
|
"caption": "Mont Saint Michel"
|
|
}).inserted_id
|
|
|
|
# Mettre à jour les pins avec les IDs des images
|
|
pins_collection.update_one(
|
|
{"_id": pin_a.inserted_id},
|
|
{"$set": {"files": [str(image_a_id)]}}
|
|
)
|
|
pins_collection.update_one(
|
|
{"_id": pin_b.inserted_id},
|
|
{"$set": {"files": [str(image_b_id)]}}
|
|
)
|
|
pins_collection.update_one(
|
|
{"_id": pin_x.inserted_id},
|
|
{"$set": {"files": [str(image_x_id)]}}
|
|
)
|
|
pins_collection.update_one(
|
|
{"_id": pin_y.inserted_id},
|
|
{"$set": {"files": [str(image_y_id)]}}
|
|
)
|
|
|
|
friends_collection = db["friends"]
|
|
friends_collection.insert_one({
|
|
"user_id": str(user1_id),
|
|
"friend_user_id": str(user2_id),
|
|
"status": "accepted"
|
|
})
|
|
|
|
if __name__ == "__main__":
|
|
populate_data()
|
|
print("Data inserted.")
|