Unearthed commited on
Commit
b38aa7a
Β·
verified Β·
1 Parent(s): 6d1401b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -61
app.py CHANGED
@@ -1,79 +1,140 @@
1
  import gradio as gr
2
  import numpy as np
 
 
3
  from PIL import Image
4
  from huggingface_hub import hf_hub_download
5
- import tensorflow as tf
6
- from tensorflow.keras.applications.efficientnet import preprocess_input
7
-
8
- # ── Config ───────────────────────────────────────────────
9
- MODEL_REPO = "Unearthed/artifact-classifier"
10
- MODEL_FILE = "artifact_classifier.keras"
11
- LABELS_FILE = "labels.txt"
12
- IMG_SIZE = (224, 224)
13
- CONFIDENCE_THRESHOLD = 0.60
14
- TEXTURE_THRESHOLD = 0.15
15
- # ─────────────────────────────────────────────────────────
16
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  print("Loading model...")
18
  model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
19
- model = tf.keras.models.load_model(model_path)
20
-
21
- labels_path = hf_hub_download(repo_id=MODEL_REPO, filename=LABELS_FILE)
22
- with open(labels_path) as f:
23
- class_names = [line.strip() for line in f if line.strip()]
24
-
25
- print("Classes:", class_names)
26
  print("Model ready!")
27
 
28
-
29
- def texture_score(img_array):
30
- gray = np.mean(img_array, axis=2)
31
- patch_size = 8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  h, w = gray.shape
33
- variances = []
34
- for i in range(0, h - patch_size, patch_size):
35
- for j in range(0, w - patch_size, patch_size):
36
- patch = gray[i:i+patch_size, j:j+patch_size]
37
- variances.append(np.var(patch))
38
- return min(np.mean(variances) / 300.0, 1.0)
39
-
40
-
41
  def predict(image):
42
  if image is None:
43
  return "Please upload an image.", {}
44
 
45
- img = image.convert("RGB").resize(IMG_SIZE)
46
- img_array = np.array(img, dtype=np.float32)
47
 
48
- tex = texture_score(img_array)
49
- if tex < TEXTURE_THRESHOLD:
50
- return f"Not an artifact β€” no stone texture detected (texture score: {tex:.2f})", {"notartifact": 1.0}
51
 
52
- x = preprocess_input(img_array.copy())
53
- x = np.expand_dims(x, 0)
54
- preds = model.predict(x, verbose=0)[0]
55
 
56
- top_idx = int(np.argmax(preds))
57
- top_score = float(preds[top_idx])
58
- scores = {class_names[i]: float(preds[i]) for i in range(len(preds))}
59
 
60
- if top_score < CONFIDENCE_THRESHOLD:
61
- label = f"Not an artifact ({top_score*100:.1f}% confidence β€” below {CONFIDENCE_THRESHOLD*100:.0f}% threshold)"
62
- else:
63
- label = f"{class_names[top_idx]} ({top_score*100:.1f}% confidence)"
64
-
65
- return label, scores
66
 
 
 
67
 
68
- with gr.Blocks(title="jAIR World β€” Artifact Classifier") as demo:
69
- gr.Markdown(
70
- """
71
- # πŸͺ¨ jAIR World β€” Artifact Classifier
72
- Upload a photo of a stone object to find out if it's an artifact β€” and which type.
73
- Supports: **arrowheads**, **axehammerstones**, and **scrapers**.
74
- """
75
- )
 
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  with gr.Row():
78
  with gr.Column():
79
  image_input = gr.Image(type="pil", label="Upload image")
@@ -82,10 +143,6 @@ with gr.Blocks(title="jAIR World β€” Artifact Classifier") as demo:
82
  label_output = gr.Textbox(label="Prediction")
83
  scores_output = gr.Label(label="Confidence scores")
84
 
85
- submit_btn.click(
86
- fn=predict,
87
- inputs=image_input,
88
- outputs=[label_output, scores_output]
89
- )
90
 
91
  demo.launch()
 
1
  import gradio as gr
2
  import numpy as np
3
+ import cv2
4
+ import tensorflow as tf
5
  from PIL import Image
6
  from huggingface_hub import hf_hub_download
7
+ from skimage.filters import gabor
8
+ from skimage.color import rgb2gray as sk_rgb2gray
9
+ from scipy.spatial import cKDTree
10
+
11
+ # ── Config ───────────────────────────────────────────────────
12
+ MODEL_REPO = "Unearthed/artifact-classifier"
13
+ MODEL_FILE = "lithic_classifier_0531.h5"
14
+ IMG_SIZE = (224, 224)
15
+
16
+ CONF_THRESHOLD = 0.55
17
+ ENTROPY_THRESHOLD = 1.35
18
+ TEXTURE_THRESHOLD = 15.0
19
+ REGULARITY_THRESHOLD = 0.30
20
+ SYMMETRY_THRESHOLD = 0.38
21
+ ARTIFACT_OVERRIDE_THR = 0.45
22
+
23
+ class_names = ["arrowheads", "axehammerstones", "notartifact", "scrapers"]
24
+
25
+ DISPLAY_CATEGORY = {
26
+ "arrowheads": "Projectile Points",
27
+ "axehammerstones": "Other Lithics",
28
+ "scrapers": "Other Lithics",
29
+ "notartifact": "Non-Artifacts",
30
+ }
31
+
32
+ def display_category(cls_name):
33
+ for key, label in DISPLAY_CATEGORY.items():
34
+ if key in cls_name.lower():
35
+ return label
36
+ return cls_name
37
+
38
+ # ── Load model ───────────────────────────────────────────────
39
  print("Loading model...")
40
  model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
41
+ model = tf.keras.models.load_model(model_path, compile=False)
 
 
 
 
 
 
42
  print("Model ready!")
43
 
44
+ # ── Feature extraction ───────────────────────────────────────
45
+ def build_5channel_input(img_np):
46
+ rgb = img_np.astype(np.float32) / 255.0
47
+ gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY).astype(np.float32)
48
+ blur = cv2.GaussianBlur(gray, (5, 5), 0)
49
+ lap = np.abs(cv2.Laplacian(blur, cv2.CV_32F))
50
+ lap = (lap - lap.min()) / (lap.max() - lap.min() + 1e-8)
51
+ gray_sk = sk_rgb2gray(img_np).astype(np.float64)
52
+ resps = [np.abs(gabor(gray_sk, frequency=0.15, theta=t)[0])
53
+ for t in [0, np.pi/4, np.pi/2]]
54
+ gab = np.mean(resps, axis=0).astype(np.float32)
55
+ gab = (gab - gab.min()) / (gab.max() - gab.min() + 1e-8)
56
+ return np.concatenate([rgb, lap[:,:,np.newaxis], gab[:,:,np.newaxis]], axis=-1)
57
+
58
+ def texture_complexity_score(img_np):
59
+ gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
60
+ return float(cv2.Laplacian(gray, cv2.CV_64F).var())
61
+
62
+ def edge_regularity_score(img_np):
63
+ gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
64
+ edges = cv2.Canny(gray, 50, 150)
65
+ ys, xs = np.where(edges > 0)
66
+ if len(xs) < 20:
67
+ return 0.0
68
+ pts = np.stack([xs, ys], axis=1).astype(np.float32)
69
+ tree = cKDTree(pts)
70
+ dists, _ = tree.query(pts, k=2)
71
+ return float(np.clip(1.0 / (1.0 + np.std(dists[:, 1])), 0, 1))
72
+
73
+ def symmetry_score(img_np):
74
+ gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY).astype(np.float32)
75
  h, w = gray.shape
76
+ left = gray[:, :w//2]
77
+ right = gray[:, w//2:][:, ::-1]
78
+ min_w = min(left.shape[1], right.shape[1])
79
+ left, right = left[:, :min_w], right[:, :min_w]
80
+ corr = np.corrcoef(left.flatten(), right.flatten())[0, 1]
81
+ return float(np.clip((corr + 1) / 2, 0, 1))
82
+
83
+ # ── Main prediction ──────────────────────────────────────────
84
  def predict(image):
85
  if image is None:
86
  return "Please upload an image.", {}
87
 
88
+ img_np = np.array(image.convert("RGB").resize(IMG_SIZE))
 
89
 
90
+ tex_score = texture_complexity_score(img_np)
91
+ reg_score = edge_regularity_score(img_np)
92
+ sym_score = symmetry_score(img_np)
93
 
94
+ if tex_score < TEXTURE_THRESHOLD:
95
+ return "❌ Rejected β€” surface too uniform (not a real stone photo)", {}
 
96
 
97
+ x5 = build_5channel_input(img_np)
98
+ preds = model.predict(np.expand_dims(x5, 0), verbose=0)[0]
 
99
 
100
+ top_idx = int(np.argmax(preds))
101
+ top_cls = class_names[top_idx]
102
+ top_conf = float(preds[top_idx])
103
+ ent = float(-np.sum(preds * np.log(preds + 1e-8)))
 
 
104
 
105
+ notartifact_idx = next((i for i, c in enumerate(class_names) if "notartifact" in c.lower()), None)
106
+ artifact_score_sum = sum(float(preds[i]) for i, c in enumerate(class_names) if "notartifact" not in c.lower())
107
 
108
+ # Override logic
109
+ if top_cls == "notartifact":
110
+ if tex_score > 80 and reg_score > 0.55 and artifact_score_sum > ARTIFACT_OVERRIDE_THR:
111
+ artifact_scores = {c: float(preds[i]) for i, c in enumerate(class_names) if i != notartifact_idx}
112
+ top_cls = max(artifact_scores, key=artifact_scores.get)
113
+ top_conf = artifact_scores[top_cls]
114
+ else:
115
+ merged = {"Non-Artifacts": 1.0}
116
+ return "βœ… Non-Artifacts", merged
117
 
118
+ if top_conf < CONF_THRESHOLD or ent > ENTROPY_THRESHOLD:
119
+ label = "⚠️ Ambiguous β€” consider manual review"
120
+ else:
121
+ label = f"βœ… {display_category(top_cls)} ({top_conf*100:.1f}% confidence)"
122
+
123
+ # Merge scores for display
124
+ merged = {}
125
+ for i, cls in enumerate(class_names):
126
+ lbl = display_category(cls)
127
+ merged[lbl] = merged.get(lbl, 0.0) + float(preds[i])
128
+
129
+ return label, merged
130
+
131
+ # ── Gradio UI ────────────────────────────────────────────────
132
+ with gr.Blocks(title="Unearthed β€” Artifact Classifier") as demo:
133
+ gr.Markdown("""
134
+ # πŸͺ¨ Unearthed β€” Artifact Classifier
135
+ Upload a photo of a stone object to classify it.
136
+ **Categories: Projectile Points Β· Other Lithics Β· Non-Artifacts**
137
+ """)
138
  with gr.Row():
139
  with gr.Column():
140
  image_input = gr.Image(type="pil", label="Upload image")
 
143
  label_output = gr.Textbox(label="Prediction")
144
  scores_output = gr.Label(label="Confidence scores")
145
 
146
+ submit_btn.click(fn=predict, inputs=image_input, outputs=[label_output, scores_output])
 
 
 
 
147
 
148
  demo.launch()