Ruggero1912 commited on
Commit
0e1bc9b
·
1 Parent(s): 306b92b

feat: implement cache cleanup for Gradio temporary folders to manage disk space, add compatibility with zeroGPU, log request timestamp

Browse files
Files changed (1) hide show
  1. app.py +76 -3
app.py CHANGED
@@ -11,6 +11,19 @@ Author: Generated for decap-dino project
11
  """
12
 
13
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  import gradio as gr
16
 
@@ -110,6 +123,52 @@ def get_example_configs() -> List[str]:
110
  return sorted(example_configs)
111
 
112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  def load_model_from_config(config_file_path: str) -> str:
114
  """
115
  Load the Patchioner model from a config file.
@@ -515,8 +574,12 @@ def generate_caption(mode, image_data) -> Tuple[str, Image.Image]:
515
  """
516
  global loaded_model
517
 
 
 
 
518
  try:
519
- print(f"[DEBUG] generate_caption called with mode: {mode}")
 
520
  print(f"[DEBUG] image_data type: {type(image_data)}")
521
  print(f"[DEBUG] image_data content: {image_data}")
522
 
@@ -598,10 +661,12 @@ def generate_caption(mode, image_data) -> Tuple[str, Image.Image]:
598
  print(traceback.format_exc())
599
  return error_msg, None
600
 
601
-
602
  def generate_trace_caption(image_data, image) -> Tuple[str, Image.Image]:
603
  """Generate caption using traces."""
604
  global loaded_model
 
 
605
 
606
  try:
607
  # Process traces
@@ -674,10 +739,11 @@ def generate_trace_caption(image_data, image) -> Tuple[str, Image.Image]:
674
  print(traceback.format_exc())
675
  return error_msg, None
676
 
677
-
678
  def generate_bbox_caption(image_data, image) -> Tuple[str, Image.Image]:
679
  """Generate caption using bounding boxes."""
680
  global loaded_model
 
681
 
682
  original_image_size = image.size # (width, height)
683
 
@@ -834,6 +900,9 @@ def resize_image_if_needed(editor_value, max_dim=1024):
834
  def create_gradio_interface(model_config_name : str):
835
  """Create and configure the Gradio interface."""
836
 
 
 
 
837
  # Get example files
838
  example_images = get_example_images()
839
  example_configs = get_example_configs()
@@ -1118,6 +1187,10 @@ if __name__ == "__main__":
1118
  print(f"Example images directory: {EXAMPLE_IMAGES_DIR}")
1119
  print(f"Configs directory: {CONFIGS_DIR}")
1120
 
 
 
 
 
1121
  demo = create_gradio_interface(DEFAULT_MODEL_CONFIG)
1122
  if not args.local:
1123
  demo.launch()
 
11
  """
12
 
13
  import os
14
+ import shutil
15
+ import time
16
+ import glob
17
+
18
+ try:
19
+ import spaces
20
+ except ModuleNotFoundError:
21
+ print("Warning: 'spaces' module not found, using mock decorator for local testing.")
22
+ # local testing, mock decorator
23
+ class spaces:
24
+ @staticmethod
25
+ def GPU(func):
26
+ return func
27
 
28
  import gradio as gr
29
 
 
123
  return sorted(example_configs)
124
 
125
 
126
+ def cleanup_gradio_cache(max_folders: int = 100, gradio_temp_dir: str = "/tmp/gradio"):
127
+ """
128
+ Clean up old Gradio temporary folders to prevent disk space issues.
129
+
130
+ Args:
131
+ max_folders: Maximum number of cache folders to keep (default: 100)
132
+ gradio_temp_dir: Path to Gradio temporary directory (default: /tmp/gradio)
133
+ """
134
+ try:
135
+ if not os.path.exists(gradio_temp_dir):
136
+ return
137
+
138
+ # Get all subdirectories in the gradio temp folder
139
+ cache_dirs = []
140
+ for item in os.listdir(gradio_temp_dir):
141
+ item_path = os.path.join(gradio_temp_dir, item)
142
+ if os.path.isdir(item_path):
143
+ cache_dirs.append(item_path)
144
+
145
+ # If we don't have too many folders, no cleanup needed
146
+ if len(cache_dirs) <= max_folders:
147
+ return
148
+
149
+ # Sort by modification time (oldest first)
150
+ cache_dirs.sort(key=os.path.getmtime)
151
+
152
+ # Calculate how many folders to delete
153
+ folders_to_delete = len(cache_dirs) - max_folders
154
+ folders_to_remove = cache_dirs[:folders_to_delete]
155
+
156
+ # Delete the oldest folders
157
+ deleted_count = 0
158
+ for folder_path in folders_to_remove:
159
+ try:
160
+ shutil.rmtree(folder_path)
161
+ deleted_count += 1
162
+ except Exception as e:
163
+ print(f"Warning: Could not delete cache folder {folder_path}: {e}")
164
+
165
+ if deleted_count > 0:
166
+ print(f"🧹 Cleaned up {deleted_count} old Gradio cache folders to save disk space")
167
+
168
+ except Exception as e:
169
+ print(f"Warning: Error during Gradio cache cleanup: {e}")
170
+
171
+
172
  def load_model_from_config(config_file_path: str) -> str:
173
  """
174
  Load the Patchioner model from a config file.
 
574
  """
575
  global loaded_model
576
 
577
+ # Clean up old cache folders on each generation to keep disk usage under control
578
+ cleanup_gradio_cache(max_folders=30) # More aggressive cleanup during active use
579
+
580
  try:
581
+ current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
582
+ print(f"[{current_time}] generate_caption called with mode: {mode}")
583
  print(f"[DEBUG] image_data type: {type(image_data)}")
584
  print(f"[DEBUG] image_data content: {image_data}")
585
 
 
661
  print(traceback.format_exc())
662
  return error_msg, None
663
 
664
+ @spaces.GPU
665
  def generate_trace_caption(image_data, image) -> Tuple[str, Image.Image]:
666
  """Generate caption using traces."""
667
  global loaded_model
668
+
669
+ loaded_model.to("cuda")
670
 
671
  try:
672
  # Process traces
 
739
  print(traceback.format_exc())
740
  return error_msg, None
741
 
742
+ @spaces.GPU
743
  def generate_bbox_caption(image_data, image) -> Tuple[str, Image.Image]:
744
  """Generate caption using bounding boxes."""
745
  global loaded_model
746
+ loaded_model.to("cuda")
747
 
748
  original_image_size = image.size # (width, height)
749
 
 
900
  def create_gradio_interface(model_config_name : str):
901
  """Create and configure the Gradio interface."""
902
 
903
+ # Clean up old Gradio cache folders to prevent disk space issues
904
+ cleanup_gradio_cache(max_folders=50) # Keep only 50 most recent cache folders
905
+
906
  # Get example files
907
  example_images = get_example_images()
908
  example_configs = get_example_configs()
 
1187
  print(f"Example images directory: {EXAMPLE_IMAGES_DIR}")
1188
  print(f"Configs directory: {CONFIGS_DIR}")
1189
 
1190
+ # Initial cleanup of old Gradio cache folders on startup
1191
+ print("🧹 Cleaning up old cache folders...")
1192
+ cleanup_gradio_cache(max_folders=20) # Very aggressive cleanup on startup
1193
+
1194
  demo = create_gradio_interface(DEFAULT_MODEL_CONFIG)
1195
  if not args.local:
1196
  demo.launch()