ze-sudo commited on
Commit
f079ead
·
verified ·
1 Parent(s): dc98df2

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +236 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ import numpy as np
4
+ from PIL import Image
5
+ import cv2
6
+ from datetime import datetime
7
+ import matplotlib.pyplot as plt
8
+
9
+ print("🚀 学習状況分析システム起動中...")
10
+ print(f"⏰ 起動時刻: 2025-08-06 07:10:59 UTC")
11
+ print(f"👤 ユーザー: ze-sudo")
12
+
13
+ # グローバル変数
14
+ model = None
15
+ frame_count = 0
16
+ studying_count = 0
17
+ not_studying_count = 0
18
+
19
+ def load_model():
20
+ """モデル読み込み"""
21
+ global model
22
+ try:
23
+ # カスタムオブジェクト定義(Castレイヤー対応)
24
+ @tf.keras.utils.register_keras_serializable()
25
+ class Cast(tf.keras.layers.Layer):
26
+ def __init__(self, dtype='float32', **kwargs):
27
+ super(Cast, self).__init__(**kwargs)
28
+ self.target_dtype = dtype
29
+
30
+ def call(self, inputs):
31
+ return tf.cast(inputs, self.target_dtype)
32
+
33
+ def get_config(self):
34
+ config = super(Cast, self).get_config()
35
+ config.update({'dtype': self.target_dtype})
36
+ return config
37
+
38
+ # カスタムオブジェクトでモデル読み込み
39
+ with tf.keras.utils.custom_object_scope({'Cast': Cast}):
40
+ model = tf.keras.models.load_model('model/deep_studying_classifier.h5')
41
+
42
+ print("✅ モデル読み込み成功")
43
+ return True
44
+ except Exception as e:
45
+ print(f"❌ モデル読み込み失敗: {e}")
46
+ return False
47
+
48
+ def predict_frame(frame):
49
+ """フレーム予測"""
50
+ global model, frame_count, studying_count, not_studying_count
51
+
52
+ if frame is None or model is None:
53
+ return frame, "カメラを開始してください", create_empty_plot()
54
+
55
+ try:
56
+ frame_count += 1
57
+
58
+ # 画像前処理
59
+ img_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
60
+ img_pil = Image.fromarray(img_rgb)
61
+ img_resized = img_pil.resize((224, 224))
62
+ img_array = np.array(img_resized) / 255.0
63
+ img_array = np.expand_dims(img_array, axis=0)
64
+
65
+ # 予測
66
+ prediction = model.predict(img_array, verbose=0)[0][0]
67
+
68
+ # 統計更新
69
+ if prediction > 0.5:
70
+ studying_count += 1
71
+ status = "📚 学習中"
72
+ color = (0, 255, 0)
73
+ else:
74
+ not_studying_count += 1
75
+ status = "🎮 非学習中"
76
+ color = (0, 0, 255)
77
+
78
+ # フレームに結果描画
79
+ cv2.rectangle(img_rgb, (10, 10), (400, 80), (0, 0, 0), -1)
80
+ cv2.putText(img_rgb, status, (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)
81
+ cv2.putText(img_rgb, f"確率: {prediction:.3f}", (20, 65),
82
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1)
83
+
84
+ # 結果テキスト
85
+ total = studying_count + not_studying_count
86
+ studying_pct = (studying_count / total * 100) if total > 0 else 0
87
+
88
+ result_text = f"""
89
+ # {status}
90
+
91
+ **現在の確率**: {prediction:.4f} ({prediction*100:.1f}%)
92
+ **信頼度**: {prediction if prediction > 0.5 else 1-prediction:.4f}
93
+
94
+ ## 📊 セッション統計
95
+ - 総フレーム: {frame_count}
96
+ - 学習中: {studying_count} ({studying_pct:.1f}%)
97
+ - 非学習中: {not_studying_count} ({100-studying_pct:.1f}%)
98
+
99
+ **更新時刻**: {datetime.now().strftime('%H:%M:%S')}
100
+ """
101
+
102
+ # グラフ作成
103
+ plot = create_stats_plot()
104
+
105
+ return img_rgb, result_text, plot
106
+
107
+ except Exception as e:
108
+ return frame, f"エラー: {str(e)}", create_empty_plot()
109
+
110
+ def create_stats_plot():
111
+ """統計グラフ作成"""
112
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
113
+
114
+ # 円グラフ
115
+ if studying_count + not_studying_count > 0:
116
+ sizes = [studying_count, not_studying_count]
117
+ labels = ['学習中', '非学習中']
118
+ colors = ['#4CAF50', '#f44336']
119
+
120
+ ax1.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
121
+ ax1.set_title('学習時間分布')
122
+ else:
123
+ ax1.text(0.5, 0.5, 'データなし', ha='center', va='center', transform=ax1.transAxes)
124
+ ax1.set_title('学習時間分布')
125
+
126
+ # 棒グラフ
127
+ categories = ['学習中', '非学習中']
128
+ counts = [studying_count, not_studying_count]
129
+ colors = ['#4CAF50', '#f44336']
130
+
131
+ bars = ax2.bar(categories, counts, color=colors, alpha=0.8)
132
+ ax2.set_title('フレーム数')
133
+ ax2.set_ylabel('回数')
134
+
135
+ # 値表示
136
+ for bar, count in zip(bars, counts):
137
+ if count > 0:
138
+ height = bar.get_height()
139
+ ax2.text(bar.get_x() + bar.get_width()/2., height + 0.1,
140
+ str(count), ha='center', va='bottom')
141
+
142
+ plt.tight_layout()
143
+ return fig
144
+
145
+ def create_empty_plot():
146
+ """空のグラフ"""
147
+ fig, ax = plt.subplots(figsize=(8, 5))
148
+ ax.text(0.5, 0.5, '📊 データ収集���...\nカメラを開始してください',
149
+ ha='center', va='center', transform=ax.transAxes, fontsize=14)
150
+ ax.set_title('統計グラフ')
151
+ ax.axis('off')
152
+ return fig
153
+
154
+ def reset_stats():
155
+ """統計リセット"""
156
+ global frame_count, studying_count, not_studying_count
157
+ frame_count = 0
158
+ studying_count = 0
159
+ not_studying_count = 0
160
+ return "🔄 統計をリセットしました", create_empty_plot()
161
+
162
+ # アプリ作成
163
+ def create_app():
164
+ with gr.Blocks(title="📹 学習状況分析", theme=gr.themes.Soft()) as demo:
165
+
166
+ gr.HTML("""
167
+ <div style="text-align: center; padding: 20px; background: linear-gradient(90deg, #667eea, #764ba2); color: white; border-radius: 10px; margin-bottom: 20px;">
168
+ <h1 style="margin: 0; font-size: 2.5em;">📹 学習状況リアルタイム分析</h1>
169
+ <p style="margin: 10px 0;">Webカメラで学習中か非学習中かをAI判定</p>
170
+ <p style="margin: 0; font-size: 0.9em;">開発者: ze-sudo | 2025-08-06 07:10:59 UTC</p>
171
+ </div>
172
+ """)
173
+
174
+ with gr.Row():
175
+ # カメラ
176
+ with gr.Column(scale=1):
177
+ gr.Markdown("## 📷 Webカメラ")
178
+ webcam = gr.Image(
179
+ sources=["webcam"],
180
+ streaming=True,
181
+ height=400,
182
+ label="リアルタイム分析"
183
+ )
184
+
185
+ reset_btn = gr.Button("🔄 統計リセット", variant="secondary")
186
+
187
+ # 結果
188
+ with gr.Column(scale=1):
189
+ gr.Markdown("## 📊 分析結果")
190
+ result_output = gr.Markdown("カメラを開始してください")
191
+
192
+ # グラフ
193
+ with gr.Row():
194
+ stats_plot = gr.Plot(label="📈 統計", value=create_empty_plot())
195
+
196
+ # ストリーミング設定
197
+ webcam.stream(
198
+ fn=predict_frame,
199
+ inputs=[webcam],
200
+ outputs=[webcam, result_output, stats_plot],
201
+ stream_every=0.5,
202
+ time_limit=3600
203
+ )
204
+
205
+ # リセットボタン
206
+ reset_btn.click(
207
+ fn=reset_stats,
208
+ outputs=[result_output, stats_plot]
209
+ )
210
+
211
+ gr.HTML("""
212
+ <div style="text-align: center; margin-top: 20px; padding: 15px; background: #f0f0f0; border-radius: 8px;">
213
+ <p style="margin: 0; color: #666;">
214
+ 🤖 TensorFlow + Gradio + HF Spaces | 🔒 プライバシー保護 | ❤️ Made by ze-sudo
215
+ </p>
216
+ </div>
217
+ """)
218
+
219
+ return demo
220
+
221
+ # メイン実行
222
+ if __name__ == "__main__":
223
+ print("📥 モデル読み込み中...")
224
+ model_loaded = load_model()
225
+
226
+ if model_loaded:
227
+ print("🚀 アプリケーション起動中...")
228
+ app = create_app()
229
+ app.launch(
230
+ server_name="0.0.0.0",
231
+ server_port=7860,
232
+ show_error=True
233
+ )
234
+ else:
235
+ print("❌ モデルが読み込めませんでした")
236
+ print("model/deep_studying_classifier.h5 ファイルを確認してください")
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio==4.44.0
2
+ tensorflow==2.15.0
3
+ opencv-python-headless==4.8.1.78
4
+ pillow==10.0.1
5
+ numpy==1.24.3
6
+ matplotlib==3.7.2