Update app.py
Browse files
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 |
-
|
| 6 |
-
from
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
IMG_SIZE
|
| 13 |
-
|
| 14 |
-
|
| 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
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
h, w = gray.shape
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
return
|
| 39 |
-
|
| 40 |
-
|
| 41 |
def predict(image):
|
| 42 |
if image is None:
|
| 43 |
return "Please upload an image.", {}
|
| 44 |
|
| 45 |
-
|
| 46 |
-
img_array = np.array(img, dtype=np.float32)
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
preds = model.predict(x, verbose=0)[0]
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
scores = {class_names[i]: float(preds[i]) for i in range(len(preds))}
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
return label, scores
|
| 66 |
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 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()
|