Surn commited on
Commit
0b202ef
·
1 Parent(s): 6a8a7e3

User History 0.3.0

Browse files
Files changed (2) hide show
  1. modules/file_utils.py +27 -1
  2. modules/user_history.py +63 -43
modules/file_utils.py CHANGED
@@ -88,4 +88,30 @@ def delete_file(file_path: str) -> None:
88
  except FileNotFoundError:
89
  print(f"File not found: {file_path}")
90
  except Exception as e:
91
- print(f"Error deleting file: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  except FileNotFoundError:
89
  print(f"File not found: {file_path}")
90
  except Exception as e:
91
+ print(f"Error deleting file: {e}")
92
+
93
+ def get_unique_file_path(directory, filename, file_ext, counter=0):
94
+ """
95
+ Recursively increments the filename until a unique path is found.
96
+
97
+ Parameters:
98
+ directory (str): The directory for the file.
99
+ filename (str): The base filename.
100
+ file_ext (str): The file extension including the leading dot.
101
+ counter (int): The current counter value to append.
102
+
103
+ Returns:
104
+ str: A unique file path that does not exist.
105
+ """
106
+ if counter == 0:
107
+ filepath = os.path.join(directory, f"{filename}{file_ext}")
108
+ else:
109
+ filepath = os.path.join(directory, f"{filename}{counter}{file_ext}")
110
+
111
+ if not os.path.exists(filepath):
112
+ return filepath
113
+ else:
114
+ return get_unique_file_path(directory, filename, file_ext, counter + 1)
115
+
116
+ # Example usage:
117
+ # new_file_path = get_unique_file_path(video_dir, title_file_name, video_new_ext)
modules/user_history.py CHANGED
@@ -18,7 +18,7 @@ Useful links:
18
  Update by Surn (Charles Fettinger)
19
  """
20
 
21
- __version__ = "0.2.3"
22
 
23
  import json
24
  import os
@@ -34,7 +34,7 @@ import gradio as gr
34
  import numpy as np
35
  import requests
36
  from filelock import FileLock
37
- from PIL.Image import Image
38
  import filetype
39
  import wave
40
  from mutagen.mp3 import MP3, EasyMP3
@@ -112,7 +112,7 @@ def render() -> None:
112
  columns=5,
113
  height=600,
114
  preview=False,
115
- show_share_button=False,
116
  show_download_button=True,
117
  )
118
  gr.Markdown(
@@ -149,7 +149,7 @@ def render() -> None:
149
 
150
  def save_image(
151
  profile: gr.OAuthProfile | None,
152
- image: Image | np.ndarray | str | Path,
153
  label: str | None = None,
154
  metadata: Dict | None = None,
155
  ):
@@ -182,7 +182,7 @@ def save_image(
182
 
183
  def save_file(
184
  profile: gr.OAuthProfile | None,
185
- image: Image | np.ndarray | str | Path | None = None,
186
  video: str | Path | None = None,
187
  audio: str | Path | None = None,
188
  document: str | Path | None = None,
@@ -202,35 +202,38 @@ def save_file(
202
  " first."
203
  )
204
  return
205
-
 
 
206
  # Save new files + metadata
207
  if metadata is None:
208
  metadata = {}
209
  if "datetime" not in metadata:
210
  metadata["datetime"] = str(datetime.now())
211
-
212
- # Copy image to storage
213
- image_path = None
214
- if image is not None:
215
- image_path = _copy_image(image, dst_folder=user_history._user_images_path(username))
216
- image_path = _add_metadata(image_path, metadata)
217
-
218
- video_path = None
219
- # Copy video to storage
220
- if video is not None:
221
- video_path = _copy_file(video, dst_folder=user_history._user_file_path(username, "videos"))
222
- video_path = _add_metadata(video_path, metadata)
223
 
224
  audio_path = None
225
  # Copy audio to storage
226
  if audio is not None:
227
- audio_path = _copy_file(audio, dst_folder=user_history._user_file_path(username, "audios"))
228
  audio_path = _add_metadata(audio_path, metadata)
229
-
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  document_path = None
231
  # Copy document to storage
232
  if document is not None:
233
- document_path = _copy_file(document, dst_folder=user_history._user_file_path(username, "documents"))
234
  document_path = _add_metadata(document_path, metadata)
235
 
236
 
@@ -262,6 +265,7 @@ class _UserHistory(object):
262
  _instance = None
263
  initialized: bool = False
264
  folder_path: Path
 
265
 
266
  def __new__(cls):
267
  # Using singleton pattern => we don't want to expose an object (more complex to use) but still want to keep
@@ -287,7 +291,7 @@ class _UserHistory(object):
287
  path.mkdir(parents=True, exist_ok=True)
288
  return path
289
 
290
- def _user_file_path(self, username: str, filetype: str = "images") -> Path:
291
  path = self._user_path(username) / filetype
292
  path.mkdir(parents=True, exist_ok=True)
293
  return path
@@ -336,7 +340,7 @@ def _fetch_user_history(profile: gr.OAuthProfile | None) -> List[Tuple[str, str]
336
  images = []
337
  for line in jsonl_path.read_text().splitlines():
338
  data = json.loads(line)
339
- images.append((data["image_path"], data["label"] or ""))
340
  return list(reversed(images))
341
 
342
 
@@ -382,22 +386,22 @@ def _delete_user_history(profile: gr.OAuthProfile | None) -> None:
382
  ####################
383
 
384
 
385
- def _copy_image(image: Image | np.ndarray | str | Path, dst_folder: Path) -> Path:
386
  try:
387
  """Copy image to the images folder."""
388
  # Already a path => copy it
389
  if isinstance(image, str):
390
  image = Path(image)
391
  if isinstance(image, Path):
392
- dst = dst_folder / f"{uuid4().hex[:4]}_{Path(image).name}_h.png" # keep file ext
393
  shutil.copyfile(image, dst)
394
  return dst
395
 
396
  # Still a Python object => serialize it
397
  if isinstance(image, np.ndarray):
398
- image = Image.fromarray(image)
399
  if isinstance(image, Image):
400
- dst = dst_folder / f"{Path(image).name}_h.png"
401
  image.save(dst)
402
  return dst
403
 
@@ -409,28 +413,28 @@ def _copy_image(image: Image | np.ndarray | str | Path, dst_folder: Path) -> Pat
409
  dst = Path(image)
410
  return dst # Return the original file_location if an error occurs
411
 
412
- def _copy_file(file: Any | np.ndarray | str | Path, dst_folder: Path) -> Path:
413
  try:
414
  """Copy file to the appropriate folder."""
415
  # Already a path => copy it
416
  if isinstance(file, str):
417
  file = Path(file)
418
  if isinstance(file, Path):
419
- dst = dst_folder / f"{file.stem}_{uuid4().hex[:4]}{file.suffix}" # keep file ext
420
  shutil.copyfile(file, dst)
421
  return dst
422
 
423
  # Still a Python object => serialize it
424
  if isinstance(file, np.ndarray):
425
  file = Image.fromarray(file)
426
- dst = dst_folder / f"{file.filename}_{uuid4().hex[:4]}{file.suffix}"
427
  file.save(dst)
428
  return dst
429
 
430
  # try other file types
431
  kind = filetype.guess(file)
432
  if kind is not None:
433
- dst = dst_folder / f"{Path(file).stem}_{uuid4().hex[:4]}.{kind.extension}"
434
  shutil.copyfile(file, dst)
435
  return dst
436
  raise ValueError(f"Unsupported file type: {type(file)}")
@@ -442,7 +446,7 @@ def _copy_file(file: Any | np.ndarray | str | Path, dst_folder: Path) -> Path:
442
  return dst # Return the original file_location if an error occurs
443
 
444
 
445
- def _add_metadata(file_location: Path, metadata: Dict[str, Any]) -> Path:
446
  try:
447
  file_type = file_location.suffix
448
  valid_file_types = [".wav", ".mp3", ".mp4", ".png"]
@@ -480,17 +484,21 @@ def _add_metadata(file_location: Path, metadata: Dict[str, Any]) -> Path:
480
  elif file_type == ".mp4":
481
  # Open and process .mp4 file
482
  # Add metadata to the file
483
- wav_file_location = file_location.with_suffix(".wav")
484
- wave_exists = wav_file_location.exists()
 
 
 
 
485
  if not wave_exists:
486
  # Use torchaudio to create the WAV file if it doesn't exist
487
- audio, sample_rate = torchaudio.load(file_location, normalize=True)
488
  torchaudio.save(wav_file_location, audio, sample_rate, format='wav')
489
 
490
  # Use ffmpeg to add metadata to the video file
491
  metadata_args = [f"{key}={value}" for key, value in metadata.items()]
492
  ffmpeg_metadata = ":".join(metadata_args)
493
- ffmpeg_cmd = f'ffmpeg -y -i "{file_location}" -i "{wav_file_location}" -map 0:v:0 -map 1:a:0 -c:v copy -c:a aac -metadata "{ffmpeg_metadata}" "{new_file_location}"'
494
  subprocess.run(ffmpeg_cmd, shell=True, check=True)
495
 
496
  # Remove temporary WAV file
@@ -498,12 +506,14 @@ def _add_metadata(file_location: Path, metadata: Dict[str, Any]) -> Path:
498
  wav_file_location.unlink()
499
  return new_file_location
500
  elif file_type == ".png":
501
- # Open and process .png file
502
- image = Image.open(file_location)
503
- exif_data = image.info.get("exif", {})
504
- exif_data.update(metadata)
505
- # Add metadata to the file
506
- image.save(new_file_location, exif=exif_data)
 
 
507
  return new_file_location
508
 
509
  return file_location # Return the path to the modified file
@@ -559,7 +569,9 @@ Running on **{os.getenv("SYSTEM", "local")}** (id: {os.getenv("SPACE_ID")}). {_g
559
 
560
  Admins: {', '.join(_fetch_admins())}
561
 
562
- {_get_nb_users()} user(s), {_get_nb_images()} image(s)
 
 
563
 
564
  ### Configuration
565
 
@@ -590,6 +602,14 @@ def _get_nb_images() -> int:
590
  return len([path for path in user_history.folder_path.glob("*/images/*")])
591
  return 0
592
 
 
 
 
 
 
 
 
 
593
 
594
  def _get_msg_is_persistent_storage_enabled() -> str:
595
  if os.getenv("SYSTEM") == "spaces":
 
18
  Update by Surn (Charles Fettinger)
19
  """
20
 
21
+ __version__ = "0.3.0"
22
 
23
  import json
24
  import os
 
34
  import numpy as np
35
  import requests
36
  from filelock import FileLock
37
+ from PIL import Image, PngImagePlugin
38
  import filetype
39
  import wave
40
  from mutagen.mp3 import MP3, EasyMP3
 
112
  columns=5,
113
  height=600,
114
  preview=False,
115
+ show_share_button=True,
116
  show_download_button=True,
117
  )
118
  gr.Markdown(
 
149
 
150
  def save_image(
151
  profile: gr.OAuthProfile | None,
152
+ image: Image.Image | np.ndarray | str | Path,
153
  label: str | None = None,
154
  metadata: Dict | None = None,
155
  ):
 
182
 
183
  def save_file(
184
  profile: gr.OAuthProfile | None,
185
+ image: Image.Image | np.ndarray | str | Path | None = None,
186
  video: str | Path | None = None,
187
  audio: str | Path | None = None,
188
  document: str | Path | None = None,
 
202
  " first."
203
  )
204
  return
205
+
206
+ uniqueId = uuid4().hex[:4]
207
+
208
  # Save new files + metadata
209
  if metadata is None:
210
  metadata = {}
211
  if "datetime" not in metadata:
212
  metadata["datetime"] = str(datetime.now())
 
 
 
 
 
 
 
 
 
 
 
 
213
 
214
  audio_path = None
215
  # Copy audio to storage
216
  if audio is not None:
217
+ audio_path = _copy_file(audio, dst_folder=user_history._user_file_path(username, "audios"), uniqueId=uniqueId)
218
  audio_path = _add_metadata(audio_path, metadata)
219
+
220
+
221
+ video_path = None
222
+ # Copy video to storage - need audio_path if available
223
+ if video is not None:
224
+ video_path = _copy_file(video, dst_folder=user_history._user_file_path(username, "videos"), uniqueId=uniqueId)
225
+ video_path = _add_metadata(video_path, metadata, str(audio_path))
226
+
227
+ # Copy image to storage - need video_path if available
228
+ image_path = None
229
+ if image is not None:
230
+ image_path = _copy_image(image, dst_folder=user_history._user_images_path(username), uniqueId=uniqueId)
231
+ image_path = _add_metadata(image_path, metadata)
232
+
233
  document_path = None
234
  # Copy document to storage
235
  if document is not None:
236
+ document_path = _copy_file(document, dst_folder=user_history._user_file_path(username, "documents"), uniqueId=uniqueId)
237
  document_path = _add_metadata(document_path, metadata)
238
 
239
 
 
265
  _instance = None
266
  initialized: bool = False
267
  folder_path: Path
268
+ display_type: str = "video_path"
269
 
270
  def __new__(cls):
271
  # Using singleton pattern => we don't want to expose an object (more complex to use) but still want to keep
 
291
  path.mkdir(parents=True, exist_ok=True)
292
  return path
293
 
294
+ def _user_file_path(self, username: str, filetype: str = "images") -> Path:
295
  path = self._user_path(username) / filetype
296
  path.mkdir(parents=True, exist_ok=True)
297
  return path
 
340
  images = []
341
  for line in jsonl_path.read_text().splitlines():
342
  data = json.loads(line)
343
+ images.append((data[user_history.display_type], data["label"] or ""))
344
  return list(reversed(images))
345
 
346
 
 
386
  ####################
387
 
388
 
389
+ def _copy_image(image: Image.Image | np.ndarray | str | Path, dst_folder: Path, uniqueId: str = "") -> Path:
390
  try:
391
  """Copy image to the images folder."""
392
  # Already a path => copy it
393
  if isinstance(image, str):
394
  image = Path(image)
395
  if isinstance(image, Path):
396
+ dst = dst_folder / f"{uniqueId}_{Path(image).name}.png" # keep file ext
397
  shutil.copyfile(image, dst)
398
  return dst
399
 
400
  # Still a Python object => serialize it
401
  if isinstance(image, np.ndarray):
402
+ image = Image.Image.fromarray(image)
403
  if isinstance(image, Image):
404
+ dst = dst_folder / f"{Path(image).name}.png"
405
  image.save(dst)
406
  return dst
407
 
 
413
  dst = Path(image)
414
  return dst # Return the original file_location if an error occurs
415
 
416
+ def _copy_file(file: Any | np.ndarray | str | Path, dst_folder: Path, uniqueId: str = "") -> Path:
417
  try:
418
  """Copy file to the appropriate folder."""
419
  # Already a path => copy it
420
  if isinstance(file, str):
421
  file = Path(file)
422
  if isinstance(file, Path):
423
+ dst = dst_folder / f"{file.stem}_{uniqueId}{file.suffix}" # keep file ext
424
  shutil.copyfile(file, dst)
425
  return dst
426
 
427
  # Still a Python object => serialize it
428
  if isinstance(file, np.ndarray):
429
  file = Image.fromarray(file)
430
+ dst = dst_folder / f"{file.filename}_{uniqueId}{file.suffix}"
431
  file.save(dst)
432
  return dst
433
 
434
  # try other file types
435
  kind = filetype.guess(file)
436
  if kind is not None:
437
+ dst = dst_folder / f"{Path(file).stem}_{uniqueId}.{kind.extension}"
438
  shutil.copyfile(file, dst)
439
  return dst
440
  raise ValueError(f"Unsupported file type: {type(file)}")
 
446
  return dst # Return the original file_location if an error occurs
447
 
448
 
449
+ def _add_metadata(file_location: Path, metadata: Dict[str, Any], support_path: str = None) -> Path:
450
  try:
451
  file_type = file_location.suffix
452
  valid_file_types = [".wav", ".mp3", ".mp4", ".png"]
 
484
  elif file_type == ".mp4":
485
  # Open and process .mp4 file
486
  # Add metadata to the file
487
+ if support_path is not None:
488
+ wave_file_location = support_path
489
+ wave_exists = wav_file_location.exists()
490
+ if not wave_exists:
491
+ wav_file_location = file_location.with_suffix(".wav")
492
+ wave_exists = wav_file_location.exists()
493
  if not wave_exists:
494
  # Use torchaudio to create the WAV file if it doesn't exist
495
+ audio, sample_rate = torchaudio.load(str(file_location), normalize=True)
496
  torchaudio.save(wav_file_location, audio, sample_rate, format='wav')
497
 
498
  # Use ffmpeg to add metadata to the video file
499
  metadata_args = [f"{key}={value}" for key, value in metadata.items()]
500
  ffmpeg_metadata = ":".join(metadata_args)
501
+ ffmpeg_cmd = f'ffmpeg -y -i "{str(file_location)}" -i "{str(wav_file_location)}" -map 0:v:0 -map 1:a:0 -c:v copy -c:a aac -metadata "{ffmpeg_metadata}" "{new_file_location}"'
502
  subprocess.run(ffmpeg_cmd, shell=True, check=True)
503
 
504
  # Remove temporary WAV file
 
506
  wav_file_location.unlink()
507
  return new_file_location
508
  elif file_type == ".png":
509
+ image = Image.open(str(file_location))
510
+ # Create a PngInfo object for custom metadata
511
+ pnginfo = PngImagePlugin.PngInfo()
512
+
513
+ for key, value in metadata.items():
514
+ pnginfo.add_text(str(key), str(value))
515
+
516
+ image.save(str(new_file_location), pnginfo=pnginfo)
517
  return new_file_location
518
 
519
  return file_location # Return the path to the modified file
 
569
 
570
  Admins: {', '.join(_fetch_admins())}
571
 
572
+ {_get_nb_users()} user(s), {_get_nb_images()} image(s), {_get_nb_video()} video(s) in history.
573
+
574
+ Display Type: *{_UserHistory().display_type}*
575
 
576
  ### Configuration
577
 
 
602
  return len([path for path in user_history.folder_path.glob("*/images/*")])
603
  return 0
604
 
605
+ def _get_nb_video() -> int:
606
+ user_history = _UserHistory()
607
+ if not user_history.initialized:
608
+ return 0
609
+ if user_history.folder_path is not None and user_history.folder_path.exists():
610
+ return len([path for path in user_history.folder_path.glob("*/videos/*")])
611
+ return 0
612
+
613
 
614
  def _get_msg_is_persistent_storage_enabled() -> str:
615
  if os.getenv("SYSTEM") == "spaces":