Malaji71 commited on
Commit
f77b611
·
verified ·
1 Parent(s): d188fd1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -2
app.py CHANGED
@@ -3,24 +3,32 @@ import torch
3
  import os
4
  import time
5
  import threading
6
- from datetime import datetime
7
  import cv2
8
  from werkzeug.utils import secure_filename
9
  import uuid
10
  import mimetypes
11
  import numpy as np
12
  from PIL import Image
 
13
 
14
  # Configuration
15
  UPLOAD_FOLDER = '/data/uploads'
16
  OUTPUT_FOLDER = '/data/outputs'
 
 
17
 
18
  # Global application state
19
  app_state = {
20
  "cuda_available": torch.cuda.is_available(),
21
  "processing_active": False,
22
  "logs": [],
23
- "processed_files": []
 
 
 
 
 
24
  }
25
 
26
  def ensure_directories():
@@ -59,6 +67,80 @@ def log_message(message):
59
  app_state["logs"] = app_state["logs"][-100:]
60
  print(f"[{timestamp}] {message}")
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  def optimize_gpu():
63
  """Optimize GPU configuration for 4K upscaling"""
64
  try:
@@ -444,6 +526,9 @@ def process_frame_batch(frame_batch, out, device, target_h, target_w):
444
  # Initialize directories
445
  ensure_directories()
446
 
 
 
 
447
  app = Flask(__name__)
448
 
449
  @app.route('/')
@@ -494,6 +579,12 @@ def api_system():
494
  info["storage_outputs"] = f"{output_size / (1024**2):.1f}MB"
495
  info["upload_files_count"] = len(upload_files)
496
  info["output_files_count"] = len(output_files)
 
 
 
 
 
 
497
  except Exception as e:
498
  info["storage_uploads"] = f"Error: {str(e)}"
499
  info["storage_outputs"] = "N/A"
@@ -643,19 +734,76 @@ def api_clear_cache():
643
  except Exception as e:
644
  return jsonify({"success": False, "error": str(e)})
645
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
646
  if __name__ == '__main__':
647
  # Initialize system
648
  log_message("🚀 4K Upscaler starting...")
649
 
650
  try:
 
 
 
651
  # Optimize GPU if available
652
  if optimize_gpu():
653
  log_message("✅ GPU optimized for 4K upscaling")
654
  else:
655
  log_message("⚠️ GPU optimization failed, using CPU fallback")
656
 
 
 
 
 
657
  log_message("✅ 4K Upscaler ready")
658
  log_message("📤 Upload images or videos to upscale to 4K resolution")
 
659
 
660
  except Exception as e:
661
  log_message(f"❌ Initialization error: {str(e)}")
 
3
  import os
4
  import time
5
  import threading
6
+ from datetime import datetime, timedelta
7
  import cv2
8
  from werkzeug.utils import secure_filename
9
  import uuid
10
  import mimetypes
11
  import numpy as np
12
  from PIL import Image
13
+ import schedule
14
 
15
  # Configuration
16
  UPLOAD_FOLDER = '/data/uploads'
17
  OUTPUT_FOLDER = '/data/outputs'
18
+ CLEANUP_INTERVAL_MINUTES = 10
19
+ FILE_MAX_AGE_HOURS = 1
20
 
21
  # Global application state
22
  app_state = {
23
  "cuda_available": torch.cuda.is_available(),
24
  "processing_active": False,
25
  "logs": [],
26
+ "processed_files": [],
27
+ "cleanup_stats": {
28
+ "last_cleanup": None,
29
+ "files_deleted": 0,
30
+ "space_freed_mb": 0
31
+ }
32
  }
33
 
34
  def ensure_directories():
 
67
  app_state["logs"] = app_state["logs"][-100:]
68
  print(f"[{timestamp}] {message}")
69
 
70
+ def cleanup_old_files():
71
+ """Delete files older than FILE_MAX_AGE_HOURS"""
72
+ try:
73
+ current_time = datetime.now()
74
+ cutoff_time = current_time - timedelta(hours=FILE_MAX_AGE_HOURS)
75
+
76
+ files_deleted = 0
77
+ space_freed = 0
78
+
79
+ # Clean upload folder
80
+ for folder_path in [UPLOAD_FOLDER, OUTPUT_FOLDER]:
81
+ if not os.path.exists(folder_path):
82
+ continue
83
+
84
+ for filename in os.listdir(folder_path):
85
+ file_path = os.path.join(folder_path, filename)
86
+
87
+ if os.path.isfile(file_path):
88
+ try:
89
+ # Get file modification time
90
+ file_time = datetime.fromtimestamp(os.path.getmtime(file_path))
91
+
92
+ if file_time < cutoff_time:
93
+ # Get file size before deletion
94
+ file_size = os.path.getsize(file_path)
95
+
96
+ # Delete the file
97
+ os.remove(file_path)
98
+
99
+ files_deleted += 1
100
+ space_freed += file_size
101
+
102
+ log_message(f"🗑️ Deleted old file: {filename} ({file_size / (1024*1024):.1f}MB)")
103
+
104
+ except Exception as e:
105
+ log_message(f"⚠️ Error deleting {filename}: {str(e)}")
106
+
107
+ # Update cleanup stats
108
+ app_state["cleanup_stats"]["last_cleanup"] = current_time.strftime("%Y-%m-%d %H:%M:%S")
109
+ app_state["cleanup_stats"]["files_deleted"] += files_deleted
110
+ app_state["cleanup_stats"]["space_freed_mb"] += space_freed / (1024*1024)
111
+
112
+ if files_deleted > 0:
113
+ log_message(f"🧹 Cleanup completed: {files_deleted} files deleted, {space_freed / (1024*1024):.1f}MB freed")
114
+ else:
115
+ log_message(f"🧹 Cleanup completed: No old files to delete")
116
+
117
+ # Clean up processed files list to remove references to deleted files
118
+ valid_processed_files = []
119
+ for file_info in app_state["processed_files"]:
120
+ output_path = os.path.join(OUTPUT_FOLDER, file_info["output_file"])
121
+ if os.path.exists(output_path):
122
+ valid_processed_files.append(file_info)
123
+
124
+ app_state["processed_files"] = valid_processed_files
125
+
126
+ except Exception as e:
127
+ log_message(f"❌ Error during cleanup: {str(e)}")
128
+
129
+ def run_scheduler():
130
+ """Run the file cleanup scheduler in background"""
131
+ def scheduler_worker():
132
+ while True:
133
+ try:
134
+ schedule.run_pending()
135
+ time.sleep(60) # Check every minute
136
+ except Exception as e:
137
+ log_message(f"❌ Scheduler error: {str(e)}")
138
+ time.sleep(300) # Wait 5 minutes before retrying
139
+
140
+ thread = threading.Thread(target=scheduler_worker, daemon=True)
141
+ thread.start()
142
+ log_message(f"🕒 File cleanup scheduler started (every {CLEANUP_INTERVAL_MINUTES} minutes)")
143
+
144
  def optimize_gpu():
145
  """Optimize GPU configuration for 4K upscaling"""
146
  try:
 
526
  # Initialize directories
527
  ensure_directories()
528
 
529
+ # Set up file cleanup scheduler
530
+ schedule.every(CLEANUP_INTERVAL_MINUTES).minutes.do(cleanup_old_files)
531
+
532
  app = Flask(__name__)
533
 
534
  @app.route('/')
 
579
  info["storage_outputs"] = f"{output_size / (1024**2):.1f}MB"
580
  info["upload_files_count"] = len(upload_files)
581
  info["output_files_count"] = len(output_files)
582
+
583
+ # Add cleanup info
584
+ info["cleanup_stats"] = app_state["cleanup_stats"]
585
+ info["cleanup_interval"] = f"{CLEANUP_INTERVAL_MINUTES} minutes"
586
+ info["file_max_age"] = f"{FILE_MAX_AGE_HOURS} hour(s)"
587
+
588
  except Exception as e:
589
  info["storage_uploads"] = f"Error: {str(e)}"
590
  info["storage_outputs"] = "N/A"
 
734
  except Exception as e:
735
  return jsonify({"success": False, "error": str(e)})
736
 
737
+ @app.route('/api/cleanup-now', methods=['POST'])
738
+ def api_cleanup_now():
739
+ """Manually trigger file cleanup"""
740
+ try:
741
+ cleanup_old_files()
742
+ return jsonify({"success": True, "message": "Manual cleanup completed"})
743
+ except Exception as e:
744
+ return jsonify({"success": False, "error": str(e)})
745
+
746
+ @app.route('/api/storage-stats')
747
+ def api_storage_stats():
748
+ """Get detailed storage statistics"""
749
+ try:
750
+ stats = {
751
+ "cleanup_stats": app_state["cleanup_stats"],
752
+ "current_files": {},
753
+ "total_storage_mb": 0
754
+ }
755
+
756
+ for folder_name, folder_path in [("uploads", UPLOAD_FOLDER), ("outputs", OUTPUT_FOLDER)]:
757
+ if os.path.exists(folder_path):
758
+ files = []
759
+ total_size = 0
760
+
761
+ for filename in os.listdir(folder_path):
762
+ file_path = os.path.join(folder_path, filename)
763
+ if os.path.isfile(file_path):
764
+ file_size = os.path.getsize(file_path)
765
+ file_time = datetime.fromtimestamp(os.path.getmtime(file_path))
766
+
767
+ files.append({
768
+ "name": filename,
769
+ "size_mb": file_size / (1024*1024),
770
+ "created": file_time.strftime("%Y-%m-%d %H:%M:%S"),
771
+ "age_hours": (datetime.now() - file_time).total_seconds() / 3600
772
+ })
773
+ total_size += file_size
774
+
775
+ stats["current_files"][folder_name] = {
776
+ "files": files,
777
+ "count": len(files),
778
+ "total_size_mb": total_size / (1024*1024)
779
+ }
780
+ stats["total_storage_mb"] += total_size / (1024*1024)
781
+
782
+ return jsonify({"success": True, "data": stats})
783
+ except Exception as e:
784
+ return jsonify({"success": False, "error": str(e)})
785
+
786
  if __name__ == '__main__':
787
  # Initialize system
788
  log_message("🚀 4K Upscaler starting...")
789
 
790
  try:
791
+ # Start file cleanup scheduler
792
+ run_scheduler()
793
+
794
  # Optimize GPU if available
795
  if optimize_gpu():
796
  log_message("✅ GPU optimized for 4K upscaling")
797
  else:
798
  log_message("⚠️ GPU optimization failed, using CPU fallback")
799
 
800
+ # Run initial cleanup
801
+ log_message("🧹 Running initial file cleanup...")
802
+ cleanup_old_files()
803
+
804
  log_message("✅ 4K Upscaler ready")
805
  log_message("📤 Upload images or videos to upscale to 4K resolution")
806
+ log_message(f"🗑️ Files will be automatically deleted after {FILE_MAX_AGE_HOURS} hour(s)")
807
 
808
  except Exception as e:
809
  log_message(f"❌ Initialization error: {str(e)}")