PrashanthB461 commited on
Commit
f6a6cf6
·
verified ·
1 Parent(s): 9a44885

Create Static/app.py

Browse files
Files changed (1) hide show
  1. Static/app.py +61 -0
Static/app.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ```python
2
+ import os
3
+ import torch
4
+ import logging
5
+ from config import CONFIG
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ def setup_static_folder():
10
+ """Ensure static folder and model weights are available."""
11
+ static_dir = "static"
12
+ output_dir = os.path.join(static_dir, "output")
13
+
14
+ # Create static and output directories
15
+ os.makedirs(static_dir, exist_ok=True)
16
+ os.makedirs(output_dir, exist_ok=True)
17
+ logger.info(f"Static directory ensured: {static_dir}")
18
+ logger.info(f"Output directory ensured: {output_dir}")
19
+
20
+ # Check for model weights
21
+ model_path = CONFIG["MODEL_PATH"]
22
+ fallback_model = CONFIG["FALLBACK_MODEL"]
23
+
24
+ if not os.path.isfile(model_path):
25
+ logger.warning(f"Custom model {model_path} not found. Falling back to {fallback_model}.")
26
+ if not os.path.isfile(fallback_model):
27
+ logger.info(f"Downloading fallback model: {fallback_model}")
28
+ try:
29
+ torch.hub.download_url_to_file(
30
+ 'https://github.com/ultralytics/assets/releases/download/v8.3.0/yolov8n.pt',
31
+ fallback_model
32
+ )
33
+ logger.info(f"Downloaded {fallback_model}")
34
+ except Exception as e:
35
+ logger.error(f"Failed to download {fallback_model}: {e}")
36
+ raise
37
+ else:
38
+ logger.info(f"Using custom model: {model_path}")
39
+
40
+ return model_path if os.path.isfile(model_path) else fallback_model
41
+
42
+ # Call this function before loading the model in app.py
43
+ model_path = setup_static_folder()
44
+ ```
45
+
46
+ This code should be inserted in `app.py` before the `load_model()` function, replacing the existing model loading logic. Update the `load_model()` function to use `model_path`:
47
+
48
+ ```python
49
+ def load_model(model_path):
50
+ try:
51
+ model = YOLO(model_path).to(device)
52
+ if device.type == "cuda":
53
+ model.model.half()
54
+ logger.info(f"Model loaded: {model_path}, classes: {model.names}")
55
+ return model
56
+ except Exception as e:
57
+ logger.error(f"Failed to load model: {e}")
58
+ raise
59
+
60
+ model = load_model(model_path)
61
+ ```