Keras
vit
MichaelEdward commited on
Commit
24614f0
·
verified ·
1 Parent(s): c5454ba

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. run.py +139 -47
run.py CHANGED
@@ -1,65 +1,157 @@
1
  #!/usr/bin/env python3
2
  """
3
- Single-file script (c.py): make prediction 0 or 1 by loading:
4
-
5
- - input_image path to image (argv[1] or test_image.jpg)
6
- - best.pt YOLO weights
7
- - branch_cache.npz precomputed branches (loaded for reference; prediction uses ViT+YOLO on input_image)
8
- - ViT (yit) natix-network-org/roadwork
9
- - efficientnetv2_branch.keras (via keras_dir)
10
- - fusion_head.keras (via keras_dir)
11
- - final_model final_output.keras (built from the two .keras files if missing)
12
 
13
  Usage:
14
- cd /root/Workspace/aaa && poetry run python hf_refo/c.py [path/to/input_image.jpg]
15
  """
16
  import sys
17
  from pathlib import Path
18
 
19
- REPO_ROOT = Path(__file__).resolve().parents[1]
20
- if str(REPO_ROOT) not in sys.path:
21
- sys.path.insert(0, str(REPO_ROOT))
22
 
23
- # Paths: edit these or set via env
24
- INPUT_IMAGE = REPO_ROOT / "test_image.jpg" # or pass as argv[1]
25
- BEST_PT = REPO_ROOT / "best.pt"
26
- BRANCH_CACHE = REPO_ROOT / "branch_cache.npz"
27
- VIT_REPO = "natix-network-org/roadwork" # yit / ViT
28
- KERAS_DIR = REPO_ROOT / "inception_fusion_keras" # efficientnetv2_branch.keras + fusion_head.keras
29
- FINAL_MODEL = Path(__file__).resolve().parent / "final_output.keras"
30
 
31
 
32
- def main():
33
- from PIL import Image
34
  import numpy as np
 
35
 
36
- # 1) input_image
37
- image_path = Path(sys.argv[1]) if len(sys.argv) > 1 else INPUT_IMAGE
38
- if not image_path.exists():
39
- print(f"Image not found: {image_path}. Create it or run: python hf_refo/c.py /path/to/image.jpg")
40
- sys.exit(1)
41
- input_image = Image.open(image_path).convert("RGB")
42
-
43
- # 2) branch_cache.npz
44
- branch_cache = None
45
- if BRANCH_CACHE.exists():
46
- branch_cache = np.load(BRANCH_CACHE)
47
- n = len(branch_cache.get("p_vit", branch_cache.get("labels", [])))
48
- print(f"Loaded branch_cache.npz ({n} samples).")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  else:
50
- print(f"branch_cache.npz not found at {BRANCH_CACHE} (optional).")
51
-
52
- # 3) best.pt, ViT (yit), efficientnetv2_branch.keras, fusion_head.keras, final_model -> prediction
53
- from hf_refo.inception_model import predict_from_assets
54
-
55
- label = predict_from_assets(
56
- input_image,
57
- best_pt=BEST_PT,
58
- vit_repo=VIT_REPO,
59
- keras_dir=KERAS_DIR,
60
- final_model_path=FINAL_MODEL,
61
- threshold=0.5,
 
 
 
 
 
 
 
 
 
 
 
 
62
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  print(f"Prediction: {label} (0=no roadwork, 1=roadwork)")
64
  return label
65
 
 
1
  #!/usr/bin/env python3
2
  """
3
+ Self-contained prediction script for roadwork-miner (no imports from inception_model or parent repo).
4
+ Uses: image (generated in code or from path), best.pt (YOLO), ViT (HuggingFace), final_output.keras.
5
+ Returns 0 or 1 (no roadwork / roadwork).
 
 
 
 
 
 
6
 
7
  Usage:
8
+ python run.py image.jpg # require image path; no default image
9
  """
10
  import sys
11
  from pathlib import Path
12
 
13
+ DIR = Path(__file__).resolve().parent
14
+ IMG_SIZE = 224
 
15
 
16
+ # Paths (all under this folder)
17
+ BEST_PT = DIR / "best.pt"
18
+ FINAL_MODEL = DIR / "final_output.keras"
19
+ VIT_REPO = "natix-network-org/roadwork"
 
 
 
20
 
21
 
22
+ def _image_to_keras_input(image):
23
+ """PIL or numpy (224,224,3) -> (1, 224, 224, 3) normalized for EfficientNet."""
24
  import numpy as np
25
+ from PIL import Image
26
 
27
+ if not isinstance(image, Image.Image):
28
+ image = Image.fromarray(np.asarray(image).astype(np.uint8))
29
+ if image.size != (IMG_SIZE, IMG_SIZE):
30
+ image = image.resize((IMG_SIZE, IMG_SIZE))
31
+ if image.mode != "RGB":
32
+ image = image.convert("RGB")
33
+ arr = np.array(image, dtype=np.float32) / 255.0
34
+ mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
35
+ std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
36
+ arr = (arr - mean) / std
37
+ return np.expand_dims(arr, axis=0)
38
+
39
+
40
+ def _get_vit_prob(pipe, image_pil):
41
+ out = pipe(image_pil)
42
+ if not isinstance(out, list):
43
+ out = [out]
44
+ for item in out:
45
+ if item.get("label") == "Roadwork":
46
+ return item["score"]
47
+ return 0.0
48
+
49
+
50
+ def _get_yolo_prob(yolo_model, image_pil, roadwork_idx=1):
51
+ import numpy as np
52
+ r = yolo_model.predict(source=image_pil, verbose=False, device="cpu")
53
+ if not r or not hasattr(r[0], "probs") or r[0].probs is None:
54
+ return 0.0
55
+ p = r[0].probs.data
56
+ if hasattr(p, "cpu"):
57
+ p = p.cpu().numpy()
58
  else:
59
+ p = np.asarray(p)
60
+ if p.ndim > 1:
61
+ p = p.ravel()
62
+ idx = min(roadwork_idx, len(p) - 1)
63
+ return float(p[idx])
64
+
65
+
66
+ def load_pipeline():
67
+ """Load ViT, YOLO, and final_output.keras from this folder. Returns dict with vit, yolo, model."""
68
+ from tensorflow import keras
69
+ from transformers import AutoImageProcessor, AutoModelForImageClassification, pipeline
70
+ from ultralytics import YOLO
71
+
72
+ if not FINAL_MODEL.exists():
73
+ raise FileNotFoundError(f"final_output.keras not found at {FINAL_MODEL}")
74
+ if not BEST_PT.exists():
75
+ raise FileNotFoundError(f"best.pt not found at {BEST_PT}")
76
+
77
+ model = keras.models.load_model(FINAL_MODEL)
78
+ pipe = pipeline(
79
+ "image-classification",
80
+ model=AutoModelForImageClassification.from_pretrained(VIT_REPO),
81
+ feature_extractor=AutoImageProcessor.from_pretrained(VIT_REPO, use_fast=True),
82
+ device=-1,
83
  )
84
+ yolo = YOLO(str(BEST_PT))
85
+ return {"vit": pipe, "yolo": yolo, "model": model}
86
+
87
+
88
+ def predict(image, pipeline, threshold=0.5):
89
+ """
90
+ Predict 0 or 1 from one image (PIL or numpy 224x224x3).
91
+ pipeline: from load_pipeline().
92
+ """
93
+ import numpy as np
94
+ from PIL import Image
95
+
96
+ if isinstance(image, np.ndarray):
97
+ image = Image.fromarray(image.astype(np.uint8) if image.ndim == 3 else image[0].astype(np.uint8))
98
+ if image.size != (IMG_SIZE, IMG_SIZE):
99
+ image = image.resize((IMG_SIZE, IMG_SIZE))
100
+ if image.mode != "RGB":
101
+ image = image.convert("RGB")
102
+
103
+ p_vit = _get_vit_prob(pipeline["vit"], image)
104
+ p_yolo = _get_yolo_prob(pipeline["yolo"], image)
105
+
106
+ X_img = _image_to_keras_input(image)
107
+ p_vit_arr = np.array([[float(p_vit)]], dtype=np.float32)
108
+ p_yolo_arr = np.array([[float(p_yolo)]], dtype=np.float32)
109
+
110
+ prob = pipeline["model"].predict([X_img, p_vit_arr, p_yolo_arr], verbose=0)
111
+ roadwork_prob = float(prob[0, 0])
112
+ return 1 if roadwork_prob >= threshold else 0
113
+
114
+
115
+ def make_demo_image(size=IMG_SIZE):
116
+ """Create a 224x224 RGB image in code (no file). Simple gradient for demo."""
117
+ import numpy as np
118
+ from PIL import Image
119
+
120
+ y = np.linspace(0, 1, size).reshape(size, 1)
121
+ x = np.linspace(0, 1, size).reshape(1, size)
122
+ r = (0.4 + 0.2 * x).clip(0, 1) # (1, size) -> broadcast
123
+ g = (0.5 + 0.2 * y).clip(0, 1) # (size, 1) -> broadcast
124
+ b = (0.45 + 0.1 * (x + y)).clip(0, 1) # (size, size)
125
+ r = np.broadcast_to(r, (size, size))
126
+ g = np.broadcast_to(g, (size, size))
127
+ arr = np.stack([r, g, b], axis=-1)
128
+ arr = (arr * 255).astype(np.uint8)
129
+ return Image.fromarray(arr, mode="RGB")
130
+
131
+
132
+ def load_image(path):
133
+ """Load an image from file. Returns PIL Image (RGB)."""
134
+ from PIL import Image
135
+
136
+ path = Path(path)
137
+ if not path.exists():
138
+ raise FileNotFoundError(f"Image not found: {path}")
139
+ return Image.open(path).convert("RGB")
140
+
141
+
142
+ def main():
143
+ if len(sys.argv) < 2:
144
+ print("Usage: python run.py <path_to_image>")
145
+ sys.exit(1)
146
+
147
+ try:
148
+ input_image = load_image(sys.argv[1])
149
+ except FileNotFoundError as e:
150
+ print(e)
151
+ sys.exit(1)
152
+
153
+ pipeline = load_pipeline()
154
+ label = predict(input_image, pipeline, threshold=0.5)
155
  print(f"Prediction: {label} (0=no roadwork, 1=roadwork)")
156
  return label
157