Thompson001 commited on
Commit
4be526a
ยท
verified ยท
1 Parent(s): 0a17b08

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -105
app.py CHANGED
@@ -1,105 +1,108 @@
1
- /// <reference types="vite/client" />
2
-
3
- import { client } from "@gradio/client";
4
-
5
- export const HF_SPACE_URL = "https://thompson001-crack-api.hf.space/";
6
-
7
- export interface InferenceResult {
8
- hasCrack: boolean;
9
- confidence: number;
10
- label: string;
11
- details: string;
12
- isCustomModel: boolean;
13
- }
14
-
15
- // Gradio Result ๊ตฌ์กฐ
16
- interface GradioEvent {
17
- data: any[];
18
- [key: string]: any;
19
- }
20
-
21
- interface HFJsonItem {
22
- label?: string;
23
- confidence?: number;
24
- message?: string;
25
- }
26
-
27
- interface HFJsonPayload {
28
- data: HFJsonItem[];
29
- }
30
-
31
- // -------------------------------------------------------
32
- // HF Space ํ˜ธ์ถœ
33
- // -------------------------------------------------------
34
- export async function predictCrack(file: File): Promise<InferenceResult> {
35
- console.log("๐Ÿ”ต Connecting to HF Spaceโ€ฆ");
36
-
37
- let app;
38
- try {
39
- app = await client(HF_SPACE_URL);
40
- } catch (err) {
41
- console.error("โŒ HF Space ์—ฐ๊ฒฐ ์‹คํŒจ:", err);
42
- throw new Error("HF Space ์—ฐ๊ฒฐ ์‹คํŒจ");
43
- }
44
-
45
- console.log("๐Ÿ”ต Sending image to /predictโ€ฆ");
46
-
47
- let rawResult: GradioEvent;
48
- try {
49
- rawResult = (await app.predict("/predict", {
50
- img: file, // ๋ฐ˜๋“œ์‹œ img
51
- })) as GradioEvent;
52
- } catch (err: any) {
53
- console.error("โŒ /predict ํ˜ธ์ถœ ์‹คํŒจ:", err);
54
- throw new Error("HF Space ์˜ˆ์ธก ํ˜ธ์ถœ ์‹คํŒจ");
55
- }
56
-
57
- console.log("๐Ÿ”ต Raw Response:", rawResult);
58
-
59
- const jsonPayload = rawResult?.data?.[0] as HFJsonPayload;
60
-
61
- console.log("๐Ÿ”ต JSON Payload:", jsonPayload);
62
-
63
- // JSON ์—†๋Š” ๊ฒฝ์šฐ โ†’ ์ •์ƒ ์ทจ๊ธ‰
64
- if (!jsonPayload?.data || jsonPayload.data.length === 0) {
65
- return {
66
- hasCrack: false,
67
- confidence: 1,
68
- label: "์ •์ƒ",
69
- details: "",
70
- isCustomModel: true,
71
- };
72
- }
73
-
74
- const first: HFJsonItem = jsonPayload.data[0];
75
-
76
- const rawLabel = typeof first.label === "string" ? first.label : "normal";
77
- const confidence =
78
- typeof first.confidence === "number" ? first.confidence : 1;
79
-
80
- const normalized = rawLabel.replace(/\s+/g, "").toLowerCase();
81
-
82
- // ์—๋Ÿฌ ์ฒ˜๋ฆฌ
83
- if (normalized === "error") {
84
- throw new Error(first.message || "๋ชจ๋ธ ๋‚ด๋ถ€ ์˜ค๋ฅ˜");
85
- }
86
-
87
- // ๊ท ์—ด ํŒ๋‹จ: crack, damaged ๋“ฑ ํฌํ•จ
88
- const isCrack =
89
- normalized.includes("crack") ||
90
- normalized.includes("positive") ||
91
- normalized.includes("damaged");
92
-
93
- // ๐Ÿ”ฅ ๋„ˆ๊ฐ€ ์›ํ•œ ๋กœ์ง: ์ •์ƒ์ผ ๋•Œ๋Š” % ์ˆจ๊น€
94
- const details = isCrack
95
- ? `๊ท ์—ด ํ™•๋ฅ  ${(confidence * 100).toFixed(1)}%`
96
- : "";
97
-
98
- return {
99
- hasCrack: isCrack,
100
- confidence,
101
- label: isCrack ? "๊ท ์—ด ๊ฐ์ง€" : "์ •์ƒ",
102
- details,
103
- isCustomModel: true,
104
- };
105
- }
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ from PIL import Image
4
+ import tensorflow as tf
5
+
6
+ # ------------------------------
7
+ # 1) ๋ชจ๋ธ ํŒŒ์ผ ๊ฒฝ๋กœ
8
+ # ------------------------------
9
+ MODEL_PATH = "crack_detection.h5"
10
+
11
+ # ------------------------------
12
+ # 2) ๋ชจ๋ธ ๋กœ๋“œ
13
+ # ------------------------------
14
+ model = tf.keras.models.load_model(MODEL_PATH)
15
+ print("๐Ÿ”ฅ Loaded TensorFlow crack classifier")
16
+ print(" Input shape :", model.input_shape)
17
+ print(" Output shape:", model.output_shape)
18
+
19
+ _, H, W, C = model.input_shape
20
+
21
+
22
+ # ------------------------------
23
+ # 3) ์˜ˆ์ธก ํ•จ์ˆ˜
24
+ # ------------------------------
25
+ def predict(img: Image.Image):
26
+ try:
27
+ img = img.convert("RGB")
28
+ img_resized = img.resize((W, H))
29
+
30
+ arr = np.array(img_resized).astype("float32") / 255.0
31
+ X = np.expand_dims(arr, axis=0) # (1, H, W, C)
32
+
33
+ raw = model.predict(X)[0]
34
+ probs = np.array(raw, dtype="float32").flatten()
35
+
36
+ # ------------------------------
37
+ # 1-output (sigmoid) ๋ชจ๋ธ
38
+ # ------------------------------
39
+ if probs.shape[0] == 1:
40
+ p_crack = float(probs[0])
41
+ p_normal = 1.0 - p_crack
42
+
43
+ if p_crack >= 0.5:
44
+ label = "crack"
45
+ conf = p_crack
46
+ else:
47
+ label = "normal"
48
+ conf = p_normal
49
+
50
+ # ------------------------------
51
+ # 2-output (softmax) ๋ชจ๋ธ
52
+ # probs = [p_normal, p_crack]
53
+ # ------------------------------
54
+ elif probs.shape[0] >= 2:
55
+ p_normal = float(probs[0])
56
+ p_crack = float(probs[1])
57
+
58
+ if p_crack >= p_normal:
59
+ label = "crack"
60
+ conf = p_crack
61
+ else:
62
+ label = "normal"
63
+ conf = p_normal
64
+
65
+ else:
66
+ idx = int(np.argmax(probs))
67
+ label = f"class_{idx}"
68
+ conf = float(probs[idx])
69
+
70
+ # ------------------------------
71
+ # ํ”„๋ก ํŠธ ์š”๊ตฌ ๊ตฌ์กฐ
72
+ # ------------------------------
73
+ return {
74
+ "data": [
75
+ {
76
+ "label": label,
77
+ "confidence": float(conf),
78
+ }
79
+ ]
80
+ }
81
+
82
+ except Exception as e:
83
+ print("โŒ Error:", e)
84
+ return {
85
+ "data": [
86
+ {
87
+ "label": "error",
88
+ "confidence": 0.0,
89
+ "message": str(e),
90
+ }
91
+ ]
92
+ }
93
+
94
+
95
+ # ------------------------------
96
+ # 4) Gradio API UI
97
+ # ------------------------------
98
+ demo = gr.Interface(
99
+ fn=predict,
100
+ inputs=gr.Image(type="pil", label="Input image"),
101
+ outputs=gr.JSON(label="Detection Result"),
102
+ title="Crack Detection Classifier (Keras .h5)",
103
+ description="์‚ฌ์ง„์„ ์—…๋กœ๋“œํ•˜๋ฉด ๊ท ์—ด/์ •์ƒ ์—ฌ๋ถ€์™€ ํ™•๋ฅ (%)์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.",
104
+ flagging_mode="never",
105
+ )
106
+
107
+ if __name__ == "__main__":
108
+ demo.launch()