OpenLab-NLP commited on
Commit
8616c88
·
verified ·
1 Parent(s): a49a2b2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -0
app.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import tensorflow as tf
4
+ from tensorflow.keras import layers, models
5
+ import os
6
+
7
+ # 1. 모델 아키텍처 재정의 (저장된 가중치를 불러오기 위함)
8
+ class DynamicConv2D(layers.Layer):
9
+ def __init__(self, k=3, **kwargs):
10
+ super().__init__(**kwargs)
11
+ assert k % 2 == 1
12
+ self.k = k
13
+ self.generator = layers.Dense(k * k)
14
+
15
+ def call(self, x):
16
+ B, H, W, C = tf.shape(x)[0], tf.shape(x)[1], tf.shape(x)[2], tf.shape(x)[3]
17
+ kernels = self.generator(x)
18
+ kernels = tf.nn.softmax(kernels, axis=-1)
19
+ pad = (self.k - 1) // 2
20
+ x_pad = tf.pad(x, [[0, 0], [pad, pad], [pad, pad], [0, 0]])
21
+ patches = tf.image.extract_patches(
22
+ images=x_pad,
23
+ sizes=[1, self.k, self.k, 1],
24
+ strides=[1, 1, 1, 1],
25
+ rates=[1, 1, 1, 1],
26
+ padding='VALID'
27
+ )
28
+ patches = tf.reshape(patches, [B, H, W, self.k * self.k, C])
29
+ kernels_exp = tf.expand_dims(kernels, axis=-1)
30
+ return tf.reduce_sum(patches * kernels_exp, axis=3)
31
+
32
+ def build_dynamic_model(input_shape=(28, 28, 1), num_classes=26):
33
+ inputs = layers.Input(shape=input_shape)
34
+
35
+ # 일반 Conv로 기초 특징 추출
36
+ x = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(inputs)
37
+ x = layers.BatchNormalization()(x)
38
+
39
+ # Dynamic Convolution 적용
40
+ x = DynamicConv2D(k=3)(x)
41
+ x = layers.Activation('relu')(x)
42
+ x = layers.MaxPooling2D((2, 2))(x)
43
+
44
+ x = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(x)
45
+ x = DynamicConv2D(k=3)(x)
46
+ x = layers.Activation('relu')(x)
47
+ x = layers.GlobalAveragePooling2D()(x)
48
+
49
+ x = layers.Dense(128, activation='relu')(x)
50
+ outputs = layers.Dense(num_classes, activation='softmax')(x)
51
+
52
+ return models.Model(inputs, outputs)
53
+
54
+ # 2. 모델 로드 (파일 경로 확인 필요)
55
+ model = build_dynamic_model()
56
+ # 파일 경로를 절대 경로로 설정
57
+ weights_path = 'dynamic_conv_alphabet.weights.h5'
58
+
59
+ if os.path.exists(weights_path):
60
+ model.load_weights(weights_path)
61
+ print(f"가중치 로드 성공: {weights_path}")
62
+ else:
63
+ print(f"오류: {weights_path} 파일을 찾을 수 없습니다. 먼저 학습을 수행하세요.")
64
+ # 3. 예측 함수 정의
65
+ def classify_alphabet(sketchpad):
66
+ if sketchpad is None:
67
+ return "글씨를 써주세요."
68
+
69
+ # 3-1. 이미지 데이터 추출 (Gradio의 Sketchpad는 dict 형태일 수 있음)
70
+ # 배경은 검은색(0), 글씨는 흰색(255)인 그레이스케일로 변환
71
+ img = sketchpad["composite"][:, :, 3] # Alpha 채널 사용
72
+
73
+ # 3-2. 전처리 (EMNIST 특유의 회전/반전 해결)
74
+ img = tf.convert_to_tensor(img, dtype=tf.float32)
75
+ img = tf.image.resize(tf.expand_dims(img, axis=-1), (28, 28))
76
+
77
+ # 중요: EMNIST는 이미지가 전치(transpose)되어 있음
78
+ # 사용자가 똑바로 쓴 글씨를 모델이 학습한 방향으로 돌려줍니다.
79
+ img = tf.image.transpose(img)
80
+
81
+ img = img / 255.0 # 정규화
82
+ img = tf.expand_dims(img, axis=0) # (1, 28, 28, 1)
83
+
84
+ # 3-3. 추론
85
+ preds = model.predict(img, verbose=0)[0]
86
+
87
+ # 결과 생성 (A-Z)
88
+ results = {}
89
+ for i in range(26):
90
+ char = chr(ord('A') + i)
91
+ results[char] = float(preds[i])
92
+
93
+ return results
94
+
95
+ # 4. Gradio 인터페이스 구성
96
+ interface = gr.Interface(
97
+ fn=classify_alphabet,
98
+ inputs=gr.Sketchpad(label="알파벳을 그려보세요 (A-Z)", type="numpy"),
99
+ outputs=gr.Label(num_top_classes=3, label="예측 결과"),
100
+ title="Dynamic Conv Alphabet Recognizer",
101
+ description="2D Dynamic Convolution 레이어를 사용한 알파벳 인식기입니다.",
102
+ live=True # 실시간 인식 활성화
103
+ )
104
+
105
+ if __name__ == "__main__":
106
+ interface.launch()