Skip to content

Commit

Permalink
Use uuid5 associated with file SHA1 instead of randomly generated uuid4
Browse files Browse the repository at this point in the history
  • Loading branch information
pk5ls20 committed Dec 30, 2023
1 parent 2b035d8 commit 3479685
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
20 changes: 20 additions & 0 deletions app/util/generate_uuid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import io
import pathlib
import hashlib
from uuid import UUID, uuid5, NAMESPACE_DNS

NAMESPACE_STR = 'github.com/hv0905/NekoImageGallary'


def generate(file_input: pathlib.Path | io.BytesIO) -> UUID:
namespace_uuid = uuid5(NAMESPACE_DNS, NAMESPACE_STR)
if isinstance(file_input, pathlib.Path):
with open(file_input, 'rb') as f:
file_content = f.read()
elif isinstance(file_input, io.BytesIO):
file_input.seek(0)
file_content = file_input.read()
else:
raise ValueError("Unsupported file type. Must be pathlib.Path or io.BytesIO.")
file_hash = hashlib.sha1(file_content).hexdigest()
return uuid5(namespace_uuid, file_hash)
4 changes: 2 additions & 2 deletions scripts/local_indexing.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from datetime import datetime
from pathlib import Path
from shutil import copy2
from uuid import uuid4

import PIL
from PIL import Image
Expand All @@ -10,6 +9,7 @@
from app.Models.img_data import ImageData
from app.Services.provider import index_service
from app.config import config
from app.util import generate_uuid
from .local_utility import gather_valid_files


Expand All @@ -19,7 +19,7 @@ async def copy_and_index(file_path: Path):
except PIL.UnidentifiedImageError as e:
logger.error("Error when opening image {}: {}", file_path, e)
return
image_id = uuid4()
image_id = generate_uuid.generate(file_path)
img_ext = file_path.suffix
imgdata = ImageData(id=image_id,
url=f'/static/{image_id}{img_ext}',
Expand Down

0 comments on commit 3479685

Please sign in to comment.