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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -110
app.py CHANGED
@@ -1,110 +1,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) TensorFlow ๋ชจ๋ธ ๋กœ๋“œ
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
- # (None, H, W, C) ํ˜•ํƒœ๋ผ๊ณ  ๊ฐ€์ •
20
- input_shape = model.input_shape
21
- if len(input_shape) != 4:
22
- raise ValueError(f"์˜ˆ์ƒ์น˜ ๋ชปํ•œ input_shape: {input_shape}")
23
- _, H, W, C = input_shape
24
-
25
-
26
- # ------------------------------
27
- # 3) ์˜ˆ์ธก ํ•จ์ˆ˜
28
- # ํ•ญ์ƒ JSON์„ ๋ฆฌํ„ดํ•˜๋„๋ก try/except
29
- # ------------------------------
30
- def predict(img: Image.Image):
31
- try:
32
- # 1) ์ด๋ฏธ์ง€ ์ „์ฒ˜๋ฆฌ
33
- img = img.convert("RGB")
34
- img_resized = img.resize((W, H))
35
- arr = np.array(img_resized).astype("float32") / 255.0
36
- X = np.expand_dims(arr, axis=0) # (1, H, W, C)
37
-
38
- # 2) ๋ชจ๋ธ ์ถ”๋ก 
39
- raw = model.predict(X)[0]
40
- probs = np.array(raw, dtype="float32").flatten()
41
-
42
- # 3) ์ถœ๋ ฅ ํ•ด์„
43
- # - ๊ธธ์ด 1 : sigmoid โ†’ p_crack
44
- # - ๊ธธ์ด 2+ : [p_normal, p_crack] ๊ฐ€์ •
45
- if probs.shape[0] == 1:
46
- p_crack = float(probs[0])
47
- p_normal = 1.0 - p_crack
48
-
49
- if p_crack >= 0.5:
50
- label = "crack"
51
- conf = p_crack
52
- else:
53
- label = "normal"
54
- conf = p_normal
55
-
56
- elif probs.shape[0] >= 2:
57
- p_normal = float(probs[0])
58
- p_crack = float(probs[1])
59
-
60
- if p_crack >= p_normal:
61
- label = "crack"
62
- conf = p_crack
63
- else:
64
- label = "normal"
65
- conf = p_normal
66
- else:
67
- # ๋งค์šฐ ํŠน์ดํ•œ ์ผ€์ด์Šค โ†’ ๊ทธ๋ƒฅ argmax
68
- idx = int(np.argmax(probs))
69
- label = f"class_{idx}"
70
- conf = float(probs[idx])
71
-
72
- return {
73
- "data": [
74
- {
75
- "label": label,
76
- "confidence": float(conf),
77
- }
78
- ]
79
- }
80
-
81
- except Exception as e:
82
- # โ— ์—ฌ๊ธฐ์„œ ์˜ˆ์™ธ๋ฅผ ๋ชจ๋‘ ์žก์•„์„œ JSON์œผ๋กœ ๋‚ด๋ ค์คŒ
83
- # ์ด๋ ‡๊ฒŒ ํ•ด์•ผ HF Space๊ฐ€ 500 ์•ˆ ๋˜์ง€๊ณ ,
84
- # ํ”„๋ก ํŠธ์—์„œ Raw Response/JSON Payload๋ฅผ ๋ณผ ์ˆ˜ ์žˆ์Œ.
85
- print("โŒ Error in predict():", repr(e))
86
- return {
87
- "data": [
88
- {
89
- "label": "error",
90
- "confidence": 0.0,
91
- "message": str(e),
92
- }
93
- ]
94
- }
95
-
96
-
97
- # ------------------------------
98
- # 4) Gradio Interface
99
- # ------------------------------
100
- demo = gr.Interface(
101
- fn=predict,
102
- inputs=gr.Image(type="pil", label="Input image"),
103
- outputs=gr.JSON(label="Detection Result"),
104
- title="Crack Detection Classifier (Keras .h5)",
105
- description="์‚ฌ์ง„์„ ์—…๋กœ๋“œํ•˜๋ฉด ๊ท ์—ด/์ •์ƒ ์—ฌ๋ถ€์™€ ํ™•๋ฅ (%)์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.",
106
- flagging_mode="never",
107
- )
108
-
109
- if __name__ == "__main__":
110
- demo.launch()
 
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
+ }