ze-sudo commited on
Commit
1bf101a
·
verified ·
1 Parent(s): aaa6168

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +223 -581
app.py CHANGED
@@ -5,7 +5,6 @@ from PIL import Image
5
  import cv2
6
  from datetime import datetime, timedelta
7
  import matplotlib.pyplot as plt
8
- import matplotlib.patches as patches
9
  import matplotlib
10
  import warnings
11
  from collections import deque
@@ -13,51 +12,34 @@ import threading
13
  import time
14
  import os
15
 
16
- # =============================================================================
17
- # 📁 モデル設定(ここを変更するだけでモデルを切り替え可能)
18
- # =============================================================================
19
  MODEL_CONFIG = {
20
- # モデルファイルパス(変更したい場合はここを編集)
21
  'model_path': 'model/1_1_2_deep_studying_classifier.h5',
22
-
23
- # 代替モデルパス(メインが読み込めない場合に試行)
24
  'alternative_paths': [
25
  'models/studying_classifier.h5',
26
  'deep_studying_classifier.h5',
27
  'studying_model.h5'
28
  ],
29
-
30
- # モデル設定
31
  'input_shape': (224, 224, 3),
32
- 'threshold': 0.5, # 勉強中判定の閾値
33
-
34
- # デモモード設定
35
- 'enable_demo_mode': True, # モデル読み込み失敗時のデモモード
36
- 'demo_model_complexity': 'simple' # 'simple' or 'complex'
37
  }
38
- # =============================================================================
39
 
40
- # 🇯🇵 日本語フォント設定(文字化け完全解決)
41
  matplotlib.use('Agg')
42
- try:
43
- # 英語フォントを使用(日本語は後でテキストで表示)
44
- plt.rcParams['font.family'] = ['DejaVu Sans', 'Arial Unicode MS', 'sans-serif']
45
- plt.rcParams['axes.unicode_minus'] = False
46
- # 日本語文字化け回避のため、グラフ内は英語、UIテキストは日本語で分離
47
- except:
48
- plt.rcParams['font.family'] = 'DejaVu Sans'
49
-
50
  warnings.filterwarnings('ignore', category=UserWarning)
51
 
52
- print("🇯🇵 日本語対応学習分析システム起動中...")
53
- print(f"⏰ 起動時刻: 2025-08-06 08:55:44 UTC")
54
  print(f"👤 ユーザー: ze-sudo")
55
- print(f"📁 設定モデル: {MODEL_CONFIG['model_path']}")
56
- print(f"🌐 言語: 日本語完全対応")
57
 
58
  # グローバル変数
59
  model = None
60
  is_recording = False
 
61
  recording_data = deque(maxlen=1000)
62
  recording_times = deque(maxlen=1000)
63
  recording_start_time = None
@@ -65,19 +47,9 @@ analysis_thread = None
65
  current_frame = None
66
  current_prediction = 0.5
67
 
68
- # =============================================================================
69
- # 🤖 モデル読み込み関数(完全に整理・分離)
70
- # =============================================================================
71
-
72
- def check_model_file_exists(model_path):
73
- """モデルファイルの存在確認"""
74
- exists = os.path.exists(model_path)
75
- print(f"📁 ファイルチェック: {model_path} {'✅ 存在' if exists else '❌ 不存在'}")
76
- return exists
77
-
78
- def create_custom_objects():
79
- """TensorFlowカスタムオブジェクト作成"""
80
- print("🔧 カスタムオブジェクト作成中...")
81
 
82
  @tf.keras.utils.register_keras_serializable()
83
  class Cast(tf.keras.layers.Layer):
@@ -99,164 +71,64 @@ def create_custom_objects():
99
  def __str__(self):
100
  return self.name
101
 
102
- def custom_input_layer(*args, **kwargs):
103
- if 'batch_shape' in kwargs:
104
- batch_shape = kwargs.pop('batch_shape')
105
- if batch_shape and len(batch_shape) > 1:
106
- kwargs['input_shape'] = batch_shape[1:]
107
- return tf.keras.layers.InputLayer(*args, **kwargs)
108
-
109
  custom_objects = {
110
  'Cast': Cast,
111
  'cast': Cast,
112
- 'InputLayer': custom_input_layer,
113
  'DTypePolicy': DTypePolicy,
114
  'tf': tf,
115
  }
116
 
117
- print("✅ カスタムオブジェクト作成完了")
118
- return custom_objects
119
-
120
- def try_load_model(model_path, custom_objects):
121
- """単一モデルファイルの読み込み試行"""
122
- print(f"📥 モデル読み込み試行: {model_path}")
123
-
124
  try:
125
- # 戦略1: カスタムオブジェクトスコープで読み込み
126
- print(" 📋 戦略1: カスタムオブジェクトスコープ")
127
- with tf.keras.utils.custom_object_scope(custom_objects):
128
- model = tf.keras.models.load_model(model_path, compile=False)
129
- print(" ✅ 戦略1成功")
130
- return model, "strategy1"
131
-
132
- except Exception as e1:
133
- print(f" ⚠️ 戦略1失敗: {e1}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
- try:
136
- # 戦略2: 直接カスタムオブジェクト指定
137
- print(" 📋 戦略2: 直接カスタムオブジェクト指定")
138
- model = tf.keras.models.load_model(model_path,
139
- compile=False,
140
- custom_objects=custom_objects)
141
- model.compile(optimizer='adam',
142
- loss='binary_crossentropy',
143
- metrics=['accuracy'])
144
- print(" ✅ 戦略2成功")
145
- return model, "strategy2"
146
-
147
- except Exception as e2:
148
- print(f" ❌ 戦略2失敗: {e2}")
149
- return None, f"failed: {e1}"
150
-
151
- def warmup_model(model, input_shape):
152
- """モデルウォームアップ(高速化)"""
153
- print("🔥 モデルウォームアップ中...")
154
- try:
155
- test_input = np.random.rand(1, *input_shape).astype(np.float32)
156
- for i in range(3):
157
- model.predict(test_input, verbose=0)
158
- print("✅ ウォームアップ完了")
159
- return True
160
- except Exception as e:
161
- print(f"⚠️ ウォームアップ失敗: {e}")
162
- return False
163
-
164
- def create_demo_model(complexity='simple'):
165
- """デモモード用モデル作成"""
166
- print(f"🤖 デモモデル作成中({complexity}モード)...")
167
-
168
- if complexity == 'simple':
169
- # シンプル軽量モデル
170
  model = tf.keras.Sequential([
171
  tf.keras.layers.Input(shape=MODEL_CONFIG['input_shape']),
172
  tf.keras.layers.GlobalAveragePooling2D(),
173
  tf.keras.layers.Dense(16, activation='relu'),
174
  tf.keras.layers.Dense(1, activation='sigmoid')
175
  ])
176
- else:
177
- # 複雑デモモデル
178
- model = tf.keras.Sequential([
179
- tf.keras.layers.Input(shape=MODEL_CONFIG['input_shape']),
180
- tf.keras.layers.Conv2D(16, 3, activation='relu'),
181
- tf.keras.layers.GlobalAveragePooling2D(),
182
- tf.keras.layers.Dense(32, activation='relu'),
183
- tf.keras.layers.Dropout(0.3),
184
- tf.keras.layers.Dense(1, activation='sigmoid')
185
- ])
186
-
187
- model.compile(optimizer='adam',
188
- loss='binary_crossentropy',
189
- metrics=['accuracy'])
190
-
191
- # ウォームアップ
192
- warmup_model(model, MODEL_CONFIG['input_shape'])
193
-
194
- print(f"✅ デモモデル作成完了({complexity})")
195
- return model
196
-
197
- def load_model():
198
- """🚀 メインモデル読み込み関数"""
199
- global model
200
-
201
- print("\n" + "="*60)
202
- print("🤖 モデル読み込み開始")
203
- print("="*60)
204
- print(f"📁 メインモデル: {MODEL_CONFIG['model_path']}")
205
- print(f"📂 代替モデル: {MODEL_CONFIG['alternative_paths']}")
206
- print(f"🎯 入力サイズ: {MODEL_CONFIG['input_shape']}")
207
- print(f"⚡ 判定閾値: {MODEL_CONFIG['threshold']}")
208
- print("="*60)
209
-
210
- # カスタムオブジェクト準備
211
- custom_objects = create_custom_objects()
212
-
213
- # メインモデルパス試行
214
- main_path = MODEL_CONFIG['model_path']
215
- if check_model_file_exists(main_path):
216
- model, result = try_load_model(main_path, custom_objects)
217
- if model is not None:
218
- print(f"🎉 メインモデル読み込み成功!({result})")
219
-
220
- # ウォームアップ
221
- if warmup_model(model, MODEL_CONFIG['input_shape']):
222
- print("✅ 本番モデル準備完了")
223
- return True
224
- else:
225
- print("⚠️ ウォームアップ失敗、デモモードに移行")
226
- else:
227
- print(f"❌ メインモデルファイル不存在: {main_path}")
228
-
229
- # 代替モデルパス試行
230
- print("\n📂 代替モデル試行中...")
231
- for i, alt_path in enumerate(MODEL_CONFIG['alternative_paths'], 1):
232
- print(f"🔄 代替モデル{i}: {alt_path}")
233
- if check_model_file_exists(alt_path):
234
- model, result = try_load_model(alt_path, custom_objects)
235
- if model is not None:
236
- print(f"🎉 代替モデル{i}読み込み成功!({result})")
237
-
238
- if warmup_model(model, MODEL_CONFIG['input_shape']):
239
- print("✅ 代替モデル準備完了")
240
- return True
241
- else:
242
- print(f" ❌ ファイル不存在: {alt_path}")
243
-
244
- # デモモード
245
- if MODEL_CONFIG['enable_demo_mode']:
246
- print("\n🤖 デモモードに移行...")
247
- model = create_demo_model(MODEL_CONFIG['demo_model_complexity'])
248
- print("✅ デモモード準備完了")
249
  return False
250
- else:
251
- print("❌ デモモード無効、モデル読み込み完全失敗")
252
- raise Exception("All model loading attempts failed and demo mode is disabled")
253
-
254
- # =============================================================================
255
- # 📊 分析関数群
256
- # =============================================================================
257
 
258
- def analyze_frame_from_image(frame):
259
- """実際のフレーム分析"""
260
  global current_prediction
261
 
262
  if frame is None:
@@ -268,8 +140,7 @@ def analyze_frame_from_image(frame):
268
  else:
269
  img_rgb = np.array(frame)
270
 
271
- # MODEL_CONFIG['input_shape']を使用
272
- target_size = MODEL_CONFIG['input_shape'][:2] # (224, 224)
273
  img_resized = cv2.resize(img_rgb, target_size)
274
  img_array = img_resized.astype(np.float32) / 255.0
275
  img_array = np.expand_dims(img_array, axis=0)
@@ -278,41 +149,21 @@ def analyze_frame_from_image(frame):
278
  current_prediction = np.clip(prediction, 0.0, 1.0)
279
  return current_prediction
280
 
281
- except Exception as e:
282
- print(f"フレーム分析エラー: {e}")
283
  change = (np.random.random() - 0.5) * 0.1
284
  current_prediction = np.clip(current_prediction + change, 0.0, 1.0)
285
  return current_prediction
286
 
287
- def generate_realistic_demo_data():
288
- """現実的なデモデータ生成"""
289
  if len(recording_data) == 0:
290
  return 0.6 + 0.3 * np.random.random()
291
 
292
  prev_val = recording_data[-1]
293
- elapsed = len(recording_data) * 0.5
294
-
295
- if elapsed < 300:
296
- trend = 0.05
297
- elif elapsed < 600:
298
- trend = 0.02
299
- elif elapsed < 1200:
300
- trend = -0.03
301
- else:
302
- trend = -0.05
303
-
304
- change = (np.random.random() - 0.5) * 0.15 + trend * 0.01
305
  return np.clip(prev_val + change, 0.0, 1.0)
306
 
307
- def is_studying(prediction_value):
308
- """勉強中判定(設定可能な閾値使用)"""
309
- return prediction_value > MODEL_CONFIG['threshold']
310
-
311
- # =============================================================================
312
- # 🎬 録画・分析機能
313
- # =============================================================================
314
-
315
- def recording_analysis_loop():
316
  """録画分析ループ"""
317
  global is_recording, recording_data, recording_times, recording_start_time
318
 
@@ -325,9 +176,9 @@ def recording_analysis_loop():
325
  elapsed_seconds = (current_time - recording_start_time).total_seconds()
326
 
327
  if current_frame is not None:
328
- prediction = analyze_frame_from_image(current_frame)
329
  else:
330
- prediction = generate_realistic_demo_data()
331
 
332
  recording_data.append(prediction)
333
  recording_times.append(elapsed_seconds)
@@ -341,8 +192,12 @@ def recording_analysis_loop():
341
  print("🛑 録画分析完了")
342
 
343
  def process_video_stream(frame):
344
- """🎥 ビデオストリーム処理(日本語表示対応)"""
345
- global current_frame, is_recording
 
 
 
 
346
 
347
  if frame is None:
348
  return frame
@@ -352,43 +207,34 @@ def process_video_stream(frame):
352
  if is_recording:
353
  display_frame = frame.copy()
354
 
355
- # 🎨 大きく見やすい録画インジケーター
356
  cv2.circle(display_frame, (40, 40), 20, (255, 0, 0), -1)
357
- cv2.putText(display_frame, "● REC", (70, 50),
358
  cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0), 3)
359
 
360
- # 🇯🇵 日本語ステータス表示(ローマ字で文字化け回避)
361
- if is_studying(current_prediction):
362
- status_romaji = "Benkyou-chu" # 勉強中
363
  status_color = (0, 255, 0)
364
  else:
365
- status_romaji = "Hi-benkyou-chu" # 非勉強中
366
  status_color = (255, 50, 50)
367
 
368
- # 背景ボックス(大きく)
369
- box_height = 120
370
- box_width = 480
371
- cv2.rectangle(display_frame, (10, display_frame.shape[0]-box_height-10),
372
- (box_width, display_frame.shape[0]-10), (0, 0, 0), -1)
373
- cv2.rectangle(display_frame, (10, display_frame.shape[0]-box_height-10),
374
- (box_width, display_frame.shape[0]-10), (255, 255, 255), 3)
375
 
376
- # 大きなステータステキスト
377
- cv2.putText(display_frame, f"Status: {status_romaji}", (25, display_frame.shape[0]-75),
378
- cv2.FONT_HERSHEY_SIMPLEX, 1.0, status_color, 3)
379
-
380
- # スコア表示(大きく)
381
- cv2.putText(display_frame, f"Score: {current_prediction:.2f}", (25, display_frame.shape[0]-45),
382
- cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
383
-
384
- # 閾値と時間表示
385
- cv2.putText(display_frame, f"Threshold: {MODEL_CONFIG['threshold']}", (25, display_frame.shape[0]-15),
386
- cv2.FONT_HERSHEY_SIMPLEX, 0.6, (200, 200, 200), 2)
387
 
388
  if recording_start_time:
389
  elapsed = (datetime.now() - recording_start_time).total_seconds()
390
- cv2.putText(display_frame, f"Jikan: {elapsed:.0f}s", (320, display_frame.shape[0]-15),
391
- cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
392
 
393
  return display_frame
394
 
@@ -396,123 +242,90 @@ def process_video_stream(frame):
396
 
397
  def start_recording():
398
  """録画開始"""
399
- global is_recording, analysis_thread, recording_data, recording_times
400
 
401
  if is_recording:
402
- return "⚠️ 既に録画中です", create_japanese_display()
403
 
404
  recording_data.clear()
405
  recording_times.clear()
406
 
407
  is_recording = True
 
408
 
409
- analysis_thread = threading.Thread(target=recording_analysis_loop)
410
  analysis_thread.daemon = True
411
  analysis_thread.start()
412
 
413
- return "🎬 録画分析中...", create_japanese_display()
414
 
415
  def stop_recording():
416
- """録画停止"""
417
- global is_recording
418
 
419
  if not is_recording:
420
- return "⚠️ 録画していません", create_japanese_display()
421
 
422
  is_recording = False
 
423
  time.sleep(1)
424
 
425
  if len(recording_data) > 0:
426
  total_points = len(recording_data)
427
- study_points = sum(1 for x in recording_data if is_studying(x))
428
  study_percentage = (study_points / total_points * 100) if total_points > 0 else 0
429
  duration = recording_times[-1] if recording_times else 0
430
 
431
  avg_score = sum(recording_data) / len(recording_data)
432
- max_score = max(recording_data)
433
- min_score = min(recording_data)
434
 
435
  result_text = f"""
436
- # 📊 録画分析完了!
437
 
438
- ## 📈 基本結果
439
  - **録��時間**: {duration:.0f}秒 ({duration/60:.1f}分)
440
  - **学習率**: {study_percentage:.1f}%
441
- - **分析ポイント**: {total_points}個
442
- - **判定閾値**: {MODEL_CONFIG['threshold']}
443
-
444
- ## 📋 詳細分析
445
  - **平均スコア**: {avg_score:.3f}
446
- - **最高スコア**: {max_score:.3f}
447
- - **最低スコア**: {min_score:.3f}
448
 
449
- ## 🎯 総合評価
450
- {get_detailed_evaluation_jp(study_percentage, avg_score, duration)}
451
 
452
- ## 💡 改善アドバイス
453
- {get_improvement_advice_jp(study_percentage, avg_score)}
454
  """
455
  else:
456
- result_text = "❌ 録画データがありません"
457
 
458
- return result_text, create_japanese_display()
459
 
460
- def get_detailed_evaluation_jp(study_rate, avg_score, duration):
461
- """🇯🇵 詳細評価(完全日本語)"""
462
- if duration < 60:
463
- time_comment = "短時間の分析でした。"
464
- elif duration < 300:
465
- time_comment = "適度な分析時間でした。"
466
- elif duration < 900:
467
- time_comment = "十分な分析時間でした。"
468
- else:
469
- time_comment = "長時間の分析、お疲れさまでした!"
470
-
471
- if study_rate >= 80 and avg_score >= 0.7:
472
- return f"🏆 **優秀!** 非常に高い集中力を維持できています。{time_comment}"
473
- elif study_rate >= 70 and avg_score >= 0.6:
474
- return f"🌟 **素晴らしい!** 良好な学習状態が保てています。{time_comment}"
475
- elif study_rate >= 60 and avg_score >= 0.5:
476
- return f"👍 **良好!** この調子で続けていきましょう。{time_comment}"
477
- elif study_rate >= 40:
478
- return f"📈 **改善の余地あり** もう少し集中して取り組んでみましょう。{time_comment}"
479
- else:
480
- return f"💪 **要改善** 環境や学習方法を見直してみることをお勧めします。{time_comment}"
481
-
482
- def get_improvement_advice_jp(study_rate, avg_score):
483
- """🇯🇵 改善アドバイス(完全日本語)"""
484
  if study_rate >= 80:
485
- return "🎯 素晴らしい集中力です!現在の学習環境とペースを維持しましょう。"
486
  elif study_rate >= 60:
487
- return "📚 良いペースで学習できています。適度な休憩を取りながら継続しましょう。"
488
  elif study_rate >= 40:
489
- return "⏰ 集中しやすい時間帯を見つけて、学習環境を整えることをお勧めします。"
490
  else:
491
- return "🌟 学習環境の見直し、適切な休憩の取り方、明確な目標設定を検討してみましょう。"
492
 
493
- # =============================================================================
494
- # 🇯🇵 完全日本語UI表示関数
495
- # =============================================================================
 
 
 
496
 
497
- def create_japanese_display():
498
- """🇯🇵 完全日本語対応表示作成(文字化け根本解決)"""
499
  try:
500
  if len(recording_data) < 2:
501
- # 🇯🇵 待機中の日本語表示
502
- fig, ax = plt.subplots(figsize=(14, 8))
503
  fig.patch.set_facecolor('#f8f9fa')
504
 
505
- # 大きなアイコンとテキスト
506
- ax.text(0.5, 0.6, '🎬', fontsize=120, ha='center', va='center',
507
- transform=ax.transAxes)
508
- ax.text(0.5, 0.4, 'Recording Button wo Oshi te Kudasai', fontsize=24, ha='center', va='center',
509
- transform=ax.transAxes, fontweight='bold', color='#333')
510
- ax.text(0.5, 0.3, 'Jidou de Gakushuu Joukyou wo Bunseki shimasu', fontsize=16, ha='center', va='center',
511
- transform=ax.transAxes, color='#666')
512
- ax.text(0.5, 0.2, f'Model: {MODEL_CONFIG["model_path"]}', fontsize=12, ha='center', va='center',
513
- transform=ax.transAxes, color='#888')
514
- ax.text(0.5, 0.15, f'Threshold: {MODEL_CONFIG["threshold"]}', fontsize=12, ha='center', va='center',
515
- transform=ax.transAxes, color='#888')
516
 
517
  ax.set_xlim(0, 1)
518
  ax.set_ylim(0, 1)
@@ -521,272 +334,145 @@ def create_japanese_display():
521
  plt.tight_layout()
522
  return fig
523
 
524
- # 🇯🇵 データありの日本語対応表示
525
- fig = plt.figure(figsize=(16, 10))
526
- gs = fig.add_gridspec(3, 3, height_ratios=[2, 1, 1], width_ratios=[2, 1, 1])
527
-
528
- # メイングラフエリア
529
- ax_main = fig.add_subplot(gs[0, :])
530
 
531
  times = list(recording_times)
532
  values = list(recording_data)
533
-
534
- # 🎨 美しい背景色分け
535
  threshold = MODEL_CONFIG['threshold']
536
- ax_main.fill_between([0, max(times) if times else 100], [threshold, threshold], [1.0, 1.0],
537
- color='lightgreen', alpha=0.3, label='Study Zone')
538
- ax_main.fill_between([0, max(times) if times else 100], [0.0, 0.0], [threshold, threshold],
539
- color='lightcoral', alpha=0.3, label='Non-Study Zone')
540
 
541
- # メインデータライン(太くて目立つ)
542
- ax_main.plot(times, values, linewidth=5, color='#1f77b4', alpha=0.8,
543
- marker='o', markersize=4, markevery=5, label='Study Score')
544
 
545
- # 現在値の強調
546
- if values:
547
- ax_main.scatter([times[-1]], [values[-1]], s=200, c='red',
548
- zorder=10, edgecolors='white', linewidth=3)
 
549
 
550
  # 閾値線
551
- ax_main.axhline(y=threshold, color='orange', linestyle='--', linewidth=3, alpha=0.8,
552
- label=f'Threshold ({threshold})')
553
-
554
- # 設定(英語ラベルで文字化け回避)
555
- ax_main.set_ylim(-0.02, 1.02)
556
- ax_main.set_ylabel('Gakushuu Score', fontsize=16, fontweight='bold')
557
- ax_main.set_xlabel('Keika Jikan (byou)', fontsize=16, fontweight='bold')
558
- ax_main.set_title('Gakushuu Joukyou no Suii', fontsize=20, fontweight='bold', pad=20)
559
-
560
- # Y軸ラベル(文字化け回避)
561
- ax_main.set_yticks([0, threshold/2, threshold, (1+threshold)/2, 1.0])
562
- ax_main.set_yticklabels(['Hi-benkyou', 'Tei-shuuchuu', f'Kyoukai\n({threshold})', 'Benkyou-chu', 'Chou-shuuchuu'], fontsize=12)
563
-
564
- # グリッド
565
- ax_main.grid(True, alpha=0.4, linestyle=':', linewidth=1)
566
- ax_main.set_axisbelow(True)
567
- ax_main.legend(loc='upper right', framealpha=0.9)
568
-
569
- # 🇯🇵 統計パネル(日本語情報)
570
- ax_stats = fig.add_subplot(gs[1, 0])
571
- ax_stats.axis('off')
572
-
573
- if values:
574
- study_ratio = sum(1 for v in values if is_studying(v)) / len(values) * 100
575
- duration_min = times[-1] / 60 if times else 0
576
-
577
- # ローマ字で表示(文字化け回避)
578
- stats_text = f"""Toukei Jouhou
579
-
580
- Jikan: {duration_min:.1f}fun
581
- Gakushuu Ritsu: {study_ratio:.0f}%
582
- Data Suu: {len(values)}ko
583
- Kyoukai Chi: {MODEL_CONFIG['threshold']}"""
584
-
585
- ax_stats.text(0.05, 0.95, stats_text, transform=ax_stats.transAxes,
586
- fontsize=14, verticalalignment='top', fontweight='bold',
587
- bbox=dict(boxstyle="round,pad=0.5", facecolor="#e3f2fd",
588
- edgecolor="#1976d2", linewidth=2, alpha=0.9))
589
-
590
- # 🇯🇵 現在の状態
591
- ax_current = fig.add_subplot(gs[1, 1])
592
- ax_current.axis('off')
593
 
 
594
  if values:
595
- current_val = values[-1]
596
- if current_val > 0.75:
597
- status_emoji = "🏆"
598
- status_text = "Chou-shuuchuu"
599
- status_color = "#4caf50"
600
- elif is_studying(current_val):
601
- status_emoji = "📚"
602
- status_text = "Benkyou-chu"
603
- status_color = "#2196f3"
604
- elif current_val > 0.25:
605
- status_emoji = "😐"
606
- status_text = "Tei-shuuchuu"
607
- status_color = "#ff9800"
608
- else:
609
- status_emoji = "😴"
610
- status_text = "Hi-benkyou"
611
- status_color = "#f44336"
612
-
613
- current_text = f"""Genzai no Joutai
614
-
615
- {status_emoji}
616
- {status_text}
617
-
618
- Score: {current_val:.2f}"""
619
-
620
- ax_current.text(0.5, 0.5, current_text, transform=ax_current.transAxes,
621
- fontsize=14, ha='center', va='center', fontweight='bold',
622
- bbox=dict(boxstyle="round,pad=0.5", facecolor=status_color,
623
- alpha=0.2, edgecolor=status_color, linewidth=2))
624
 
625
- # 🇯🇵 総合評価
626
- ax_eval = fig.add_subplot(gs[1, 2])
627
- ax_eval.axis('off')
 
 
628
 
 
629
  if values:
630
- study_ratio = sum(1 for v in values if is_studying(v)) / len(values) * 100
 
631
 
632
- if study_ratio >= 75:
633
- eval_emoji = "🏆"
634
- eval_text = "Yuushuu"
635
- eval_color = "#4caf50"
636
- elif study_ratio >= 60:
637
- eval_emoji = "🌟"
638
- eval_text = "Ryoukou"
639
- eval_color = "#2196f3"
640
- elif study_ratio >= 40:
641
- eval_emoji = "📈"
642
- eval_text = "Kaizen-chuu"
643
- eval_color = "#ff9800"
644
- else:
645
- eval_emoji = "💪"
646
- eval_text = "Youdoryoku"
647
- eval_color = "#f44336"
648
-
649
- eval_display = f"""Sougou Hyouka
650
-
651
- {eval_emoji}
652
- {eval_text}
653
-
654
- {study_ratio:.0f}%"""
655
 
656
- ax_eval.text(0.5, 0.5, eval_display, transform=ax_eval.transAxes,
657
- fontsize=14, ha='center', va='center', fontweight='bold',
658
- bbox=dict(boxstyle="round,pad=0.5", facecolor=eval_color,
659
- alpha=0.2, edgecolor=eval_color, linewidth=2))
660
-
661
- # ミニグラフ(最新推移)
662
- ax_mini = fig.add_subplot(gs[2, :])
663
 
 
664
  if len(values) > 10:
665
- recent_times = times[-30:] if len(times) > 30 else times
666
- recent_values = values[-30:] if len(values) > 30 else values
667
-
668
- # カラフルな棒グラフ
669
- colors = ['green' if is_studying(v) else 'red' for v in recent_values]
670
- bars = ax_mini.bar(range(len(recent_values)), recent_values, color=colors, alpha=0.7)
671
-
672
- ax_mini.set_ylim(0, 1)
673
- ax_mini.set_ylabel('Score', fontsize=12)
674
- ax_mini.set_xlabel('Saikin no Data Point', fontsize=12)
675
- ax_mini.set_title('Saikin no Suii', fontsize=14, fontweight='bold')
676
- ax_mini.axhline(y=MODEL_CONFIG['threshold'], color='orange', linestyle='--', alpha=0.8)
677
- ax_mini.grid(True, alpha=0.3)
678
 
679
  plt.tight_layout()
680
  return fig
681
 
682
  except Exception as e:
683
- print(f"日本語表示作成エラー: {e}")
684
- # エラー時のシンプル表示
685
  fig, ax = plt.subplots(figsize=(10, 6))
686
- ax.text(0.5, 0.5, 'Hyouji Junbi-chuu...', ha='center', va='center',
687
  transform=ax.transAxes, fontsize=16)
688
- ax.set_title('Gakushuu Bunseki')
689
  ax.axis('off')
690
  return fig
691
 
692
- def get_current_status_jp():
693
- """🇯🇵 現在の状況取得(完全日本語)"""
694
  if is_recording:
695
  if len(recording_data) > 0:
696
- current_status = "🎯 勉強中" if is_studying(current_prediction) else "😴 非勉強中"
697
  elapsed = recording_times[-1] if recording_times else 0
698
 
699
- study_points = sum(1 for x in recording_data if is_studying(x))
700
  study_rate = (study_points / len(recording_data) * 100) if recording_data else 0
701
 
702
  return f"""
703
- # 🎬 録画分析実行中
704
 
705
- ## 🔍 リアルタイム状況
706
- ### {current_status}
707
- - **現在スコア**: `{current_prediction:.3f}`
708
- - **判定閾値**: `{MODEL_CONFIG['threshold']}`
709
- - **経過時間**: `{elapsed:.0f}秒`
710
 
711
- ## 📊 これまでの結果
712
- - **学習率**: `{study_rate:.1f}%`
713
- - **分析済みポイント**: `{len(recording_data)}個`
714
 
715
- ## ⚙️ システム情報
716
- - **モデル**: `{MODEL_CONFIG['model_path']}`
717
- - **入力サイズ**: `{MODEL_CONFIG['input_shape']}`
718
-
719
- ---
720
- **🛑 録画停止ボタンを押すと詳細結果とアドバイスが表示されます**
721
  """
722
  else:
723
  return """
724
  # 🎬 録画開始中
725
 
726
- ## 📡 準備状況
727
- - **状態**: 分析エンジン起動中...
728
- - **カメラ**: データ収集開始中...
729
-
730
- **分析データを収集しています。少々お待ちください...**
731
  """
732
  else:
733
  return f"""
734
- # 📹 録画準備完了
735
 
736
- ## 🚀 使い方(とても簡単!)
737
- 1. **🎬 録画開始**ボタンをクリック
738
- 2. 普通に勉強してください(カメラが自動分析)
739
- 3. **🛑 録画停止**ボタンで詳細結果とアドバイス表示
740
 
741
- ## ⚙️ 現在の設定
742
- - **モデルファイル**: `{MODEL_CONFIG['model_path']}`
743
- - **判定閾値**: `{MODEL_CONFIG['threshold']}`(この値より上で「勉強中」判定)
744
- - **入力画像サイズ**: `{MODEL_CONFIG['input_shape']}`
745
 
746
- ## ✨ 特徴
747
- - **📊 直感的グラフ**: 一目で分かる日本語対応表示
748
- - **🎯 リアルタイム評価**: カメラに現在状態を日本語表示
749
- - **💡 改善アドバイス**: 具体的な日本語アドバイス付き
750
- - **🏆 総合評価**: 分かりやすい日本語評価
751
-
752
- **準備完了!録画ボタンをクリックしてください** 🚀
753
  """
754
 
755
- # =============================================================================
756
- # 🇯🇵 完全日本語Gradioアプリケーション
757
- # =============================================================================
758
-
759
  def create_app():
760
  with gr.Blocks(
761
- title="🇯🇵 日本語学習分析システム",
762
  theme=gr.themes.Soft(),
763
- css=""".gradio-container { max-width: 1400px; margin: auto; }"""
764
  ) as demo:
765
 
766
- # 🇯🇵 完全日本語ヘッダー
767
- gr.HTML(f"""
768
- <div style="text-align: center; padding: 25px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%, #f093fb 100%); color: white; border-radius: 20px; margin-bottom: 25px; box-shadow: 0 10px 30px rgba(0,0,0,0.3);">
769
- <h1 style="margin: 0; font-size: 3em; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);">🇯🇵 学習状況分析システム</h1>
770
- <h2 style="margin: 15px 0; font-size: 1.3em; opacity: 0.9;">完全日本語対応 ✨ 文字化け根本解決版</h2>
771
- <div style="margin-top: 15px; font-size: 0.9em; opacity: 0.8; background: rgba(255,255,255,0.1); padding: 10px; border-radius: 8px;">
772
- 📁 モデル: {MODEL_CONFIG['model_path']} | 🎯 閾値: {MODEL_CONFIG['threshold']} | 📐 入力: {MODEL_CONFIG['input_shape']}
773
- </div>
774
  </div>
775
  """)
776
 
777
  with gr.Row():
778
- # 左側:大きなカメラエリア
779
  with gr.Column(scale=2):
780
  webcam = gr.Image(
781
  sources=["webcam"],
782
  streaming=True,
783
- height=450,
784
- width=600,
785
- label="📹 ライブカメラ(日本語ステータス表示)",
786
  show_label=True
787
  )
788
 
789
- # 大きく分かりやすいボタン
790
  with gr.Row():
791
  start_btn = gr.Button(
792
  "🎬 録画開始",
@@ -802,28 +488,24 @@ def create_app():
802
  scale=1
803
  )
804
 
805
- # 右側:日本語状況表示
806
  with gr.Column(scale=1):
807
  result_display = gr.Markdown(
808
- value=get_current_status_jp(),
809
  elem_id="result_display"
810
  )
811
 
812
- # 🇯🇵 日本語表示エリア
813
  gr.HTML("""
814
- <div style="margin: 25px 0 15px 0; padding: 15px; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border-radius: 15px; text-align: center; border: 2px solid #dee2e6;">
815
- <h3 style="margin: 0; color: #333; font-size: 1.8em;">📊 日本語対応分析結果表示</h3>
816
- <p style="margin: 8px 0 0 0; color: #666; font-size: 1em;">グラフの文字化けを根本解決 + 完全日本語UI</p>
817
  </div>
818
  """)
819
 
820
- japanese_display = gr.Plot(
821
- value=create_japanese_display(),
822
- show_label=False,
823
- elem_id="main_display"
824
  )
825
 
826
- # カメラストリーム処理
827
  webcam.stream(
828
  fn=process_video_stream,
829
  inputs=[webcam],
@@ -834,83 +516,43 @@ def create_app():
834
  # ボタンイベント
835
  start_btn.click(
836
  fn=start_recording,
837
- outputs=[result_display, japanese_display]
838
  )
839
 
840
  stop_btn.click(
841
  fn=stop_recording,
842
- outputs=[result_display, japanese_display]
843
  )
844
 
845
- # 🇯🇵 日本語フッター
846
- gr.HTML(f"""
847
- <div style="text-align: center; margin-top: 25px; padding: 20px; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border-radius: 15px; border: 2px solid #dee2e6;">
848
- <h4 style="margin: 0 0 10px 0; color: #333;">🇯🇵 完全日本語対応版 - 文字化け根本解決</h4>
849
- <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 15px; margin: 15px 0;">
850
- <div style="background: white; padding: 15px; border-radius: 10px; border: 1px solid #ddd;">
851
- <h5 style="margin: 0 0 8px 0; color: #667eea;">📁 モデル設定</h5>
852
- <p style="margin: 0; font-size: 0.9em;">メインパス: {MODEL_CONFIG['model_path']}<br>
853
- 代替パス数: {len(MODEL_CONFIG['alternative_paths'])}<br>
854
- デモモード: {'有効' if MODEL_CONFIG['enable_demo_mode'] else '無効'}</p>
855
- </div>
856
- <div style="background: white; padding: 15px; border-radius: 10px; border: 1px solid #ddd;">
857
- <h5 style="margin: 0 0 8px 0; color: #667eea;">⚙️ 分析設定</h5>
858
- <p style="margin: 0; font-size: 0.9em;">判定閾値: {MODEL_CONFIG['threshold']}<br>
859
- 入力サイズ: {MODEL_CONFIG['input_shape']}<br>
860
- デモ複雑度: {MODEL_CONFIG['demo_model_complexity']}</p>
861
- </div>
862
- </div>
863
- <p style="margin: 10px 0 0 0; color: #666;">
864
- <strong>🎓 ze-sudo制作</strong> |
865
- 完全日本語対応版 |
866
- 2025-08-06 08:55:44 UTC
867
- </p>
868
- <p style="margin: 5px 0 0 0; color: #888; font-size: 0.9em;">
869
- 🇯🇵 日本語UI | 🔧 文字化け根本解決 | 📊 直感的表示 | ⚙️ 簡単設定変更
870
  </p>
871
  </div>
872
  """)
873
 
874
  return demo
875
 
876
- # =============================================================================
877
- # 🚀 メイン実行(完全日本語対応)
878
- # =============================================================================
879
-
880
  if __name__ == "__main__":
881
- print("\n" + "="*80)
882
- print("🇯🇵 完全日本語対応学習分析システム - 文��化け根本解決版")
883
- print("="*80)
884
- print(f"⏰ 起動時刻: 2025-08-06 08:55:44 UTC")
885
- print(f"👤 ユーザー: ze-sudo")
886
- print(f"🌐 言語: 日本語完全対応")
887
- print(f"🔧 文字化け: 根本的に解決")
888
- print(f"📁 モデルファイル: {MODEL_CONFIG['model_path']}")
889
- print(f"🎯 判定閾値: {MODEL_CONFIG['threshold']}")
890
- print(f"📐 入力サイズ: {MODEL_CONFIG['input_shape']}")
891
- print("="*80)
892
 
893
- # モデル読み込み(日本語対応)
894
- print("\n🚀 日本語対応モデル読み込み実行...")
895
- try:
896
- model_loaded = load_model()
897
- print(f"\n📊 システム準備完了:")
898
- print(f" モデル読み込み: {'✅ 本番モード' if model_loaded else '🤖 デモモード'}")
899
- print(f" 日本語対応: ✅ 完全対応")
900
- print(f" 文字化け解決: ✅ 根本解決")
901
- print(f" UI表示: ✅ 日本語わかりやすい表示")
902
- print(f" 設定変更: ✅ MODEL_CONFIG辞書で簡単変更")
903
- except Exception as e:
904
- print(f"❌ システム準備失敗: {e}")
905
- exit(1)
906
 
907
- print(f"\n🇯🇵 日本語対応アプリ起動!")
908
- print(f" 言語: 完全日本語(文字化けなし)")
909
- print(f" 操作: 録画ボタンで簡単操作")
910
- print(f" 表示: 直感的で分かりやすい")
911
- print(f" モデル変更: MODEL_CONFIG辞書を編集するだけ")
912
 
913
- # アプリ起動
914
  app = create_app()
915
 
916
  try:
 
5
  import cv2
6
  from datetime import datetime, timedelta
7
  import matplotlib.pyplot as plt
 
8
  import matplotlib
9
  import warnings
10
  from collections import deque
 
12
  import time
13
  import os
14
 
15
+ # モデル設定
 
 
16
  MODEL_CONFIG = {
 
17
  'model_path': 'model/1_1_2_deep_studying_classifier.h5',
 
 
18
  'alternative_paths': [
19
  'models/studying_classifier.h5',
20
  'deep_studying_classifier.h5',
21
  'studying_model.h5'
22
  ],
 
 
23
  'input_shape': (224, 224, 3),
24
+ 'threshold': 0.5,
25
+ 'enable_demo_mode': True,
26
+ 'demo_model_complexity': 'simple'
 
 
27
  }
 
28
 
29
+ # フォント設定(文字化け解決)
30
  matplotlib.use('Agg')
31
+ plt.rcParams['font.family'] = 'DejaVu Sans'
32
+ plt.rcParams['axes.unicode_minus'] = False
 
 
 
 
 
 
33
  warnings.filterwarnings('ignore', category=UserWarning)
34
 
35
+ print("🎯 学習分析システム起動中...")
36
+ print(f"⏰ 起動時刻: 2025-08-06 09:05:15 UTC")
37
  print(f"👤 ユーザー: ze-sudo")
 
 
38
 
39
  # グローバル変数
40
  model = None
41
  is_recording = False
42
+ is_camera_active = False # カメラ制御用
43
  recording_data = deque(maxlen=1000)
44
  recording_times = deque(maxlen=1000)
45
  recording_start_time = None
 
47
  current_frame = None
48
  current_prediction = 0.5
49
 
50
+ def load_model():
51
+ """モデル読み込み"""
52
+ global model
 
 
 
 
 
 
 
 
 
 
53
 
54
  @tf.keras.utils.register_keras_serializable()
55
  class Cast(tf.keras.layers.Layer):
 
71
  def __str__(self):
72
  return self.name
73
 
 
 
 
 
 
 
 
74
  custom_objects = {
75
  'Cast': Cast,
76
  'cast': Cast,
 
77
  'DTypePolicy': DTypePolicy,
78
  'tf': tf,
79
  }
80
 
 
 
 
 
 
 
 
81
  try:
82
+ print("📥 モデル読み込み中...")
83
+
84
+ # メインパス試行
85
+ if os.path.exists(MODEL_CONFIG['model_path']):
86
+ try:
87
+ with tf.keras.utils.custom_object_scope(custom_objects):
88
+ model = tf.keras.models.load_model(MODEL_CONFIG['model_path'], compile=False)
89
+ print("✅ モデル読み込み成功")
90
+
91
+ # ウォームアップ
92
+ test_input = np.random.rand(1, *MODEL_CONFIG['input_shape']).astype(np.float32)
93
+ for _ in range(3):
94
+ model.predict(test_input, verbose=0)
95
+ return True
96
+ except Exception as e:
97
+ print(f"⚠️ メインパス失敗: {e}")
98
+
99
+ # 代替パス試行
100
+ for alt_path in MODEL_CONFIG['alternative_paths']:
101
+ if os.path.exists(alt_path):
102
+ try:
103
+ with tf.keras.utils.custom_object_scope(custom_objects):
104
+ model = tf.keras.models.load_model(alt_path, compile=False)
105
+ print(f"✅ 代替モデル読み込み成功: {alt_path}")
106
+ return True
107
+ except:
108
+ continue
109
 
110
+ # デモモード
111
+ print("🤖 デモモードで起動")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  model = tf.keras.Sequential([
113
  tf.keras.layers.Input(shape=MODEL_CONFIG['input_shape']),
114
  tf.keras.layers.GlobalAveragePooling2D(),
115
  tf.keras.layers.Dense(16, activation='relu'),
116
  tf.keras.layers.Dense(1, activation='sigmoid')
117
  ])
118
+ model.compile(optimizer='adam', loss='binary_crossentropy')
119
+
120
+ test_input = np.random.rand(1, *MODEL_CONFIG['input_shape']).astype(np.float32)
121
+ for _ in range(3):
122
+ model.predict(test_input, verbose=0)
123
+
124
+ return False
125
+
126
+ except Exception as e:
127
+ print(f"❌ モデル読み込み完全失敗: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  return False
 
 
 
 
 
 
 
129
 
130
+ def analyze_frame(frame):
131
+ """フレーム分析"""
132
  global current_prediction
133
 
134
  if frame is None:
 
140
  else:
141
  img_rgb = np.array(frame)
142
 
143
+ target_size = MODEL_CONFIG['input_shape'][:2]
 
144
  img_resized = cv2.resize(img_rgb, target_size)
145
  img_array = img_resized.astype(np.float32) / 255.0
146
  img_array = np.expand_dims(img_array, axis=0)
 
149
  current_prediction = np.clip(prediction, 0.0, 1.0)
150
  return current_prediction
151
 
152
+ except:
 
153
  change = (np.random.random() - 0.5) * 0.1
154
  current_prediction = np.clip(current_prediction + change, 0.0, 1.0)
155
  return current_prediction
156
 
157
+ def generate_demo_data():
158
+ """デモデータ生成"""
159
  if len(recording_data) == 0:
160
  return 0.6 + 0.3 * np.random.random()
161
 
162
  prev_val = recording_data[-1]
163
+ change = (np.random.random() - 0.5) * 0.15
 
 
 
 
 
 
 
 
 
 
 
164
  return np.clip(prev_val + change, 0.0, 1.0)
165
 
166
+ def recording_loop():
 
 
 
 
 
 
 
 
167
  """録画分析ループ"""
168
  global is_recording, recording_data, recording_times, recording_start_time
169
 
 
176
  elapsed_seconds = (current_time - recording_start_time).total_seconds()
177
 
178
  if current_frame is not None:
179
+ prediction = analyze_frame(current_frame)
180
  else:
181
+ prediction = generate_demo_data()
182
 
183
  recording_data.append(prediction)
184
  recording_times.append(elapsed_seconds)
 
192
  print("🛑 録画分析完了")
193
 
194
  def process_video_stream(frame):
195
+ """カメラストリーム処理"""
196
+ global current_frame, is_camera_active
197
+
198
+ # カメラが無効な場合は何も返さない
199
+ if not is_camera_active:
200
+ return None
201
 
202
  if frame is None:
203
  return frame
 
207
  if is_recording:
208
  display_frame = frame.copy()
209
 
210
+ # 録画インジ���ーター
211
  cv2.circle(display_frame, (40, 40), 20, (255, 0, 0), -1)
212
+ cv2.putText(display_frame, "REC", (70, 50),
213
  cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0), 3)
214
 
215
+ # 状態表示
216
+ if current_prediction > MODEL_CONFIG['threshold']:
217
+ status_text = "Studying"
218
  status_color = (0, 255, 0)
219
  else:
220
+ status_text = "Not Studying"
221
  status_color = (255, 50, 50)
222
 
223
+ # 背景ボックス
224
+ cv2.rectangle(display_frame, (10, display_frame.shape[0]-80),
225
+ (400, display_frame.shape[0]-10), (0, 0, 0), -1)
226
+ cv2.rectangle(display_frame, (10, display_frame.shape[0]-80),
227
+ (400, display_frame.shape[0]-10), (255, 255, 255), 3)
 
 
228
 
229
+ cv2.putText(display_frame, f"Status: {status_text}", (25, display_frame.shape[0]-50),
230
+ cv2.FONT_HERSHEY_SIMPLEX, 0.8, status_color, 2)
231
+ cv2.putText(display_frame, f"Score: {current_prediction:.2f}", (25, display_frame.shape[0]-25),
232
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
 
 
 
 
 
 
 
233
 
234
  if recording_start_time:
235
  elapsed = (datetime.now() - recording_start_time).total_seconds()
236
+ cv2.putText(display_frame, f"Time: {elapsed:.0f}s", (250, display_frame.shape[0]-25),
237
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
238
 
239
  return display_frame
240
 
 
242
 
243
  def start_recording():
244
  """録画開始"""
245
+ global is_recording, is_camera_active, analysis_thread, recording_data, recording_times
246
 
247
  if is_recording:
248
+ return "既に録画中です", create_display()
249
 
250
  recording_data.clear()
251
  recording_times.clear()
252
 
253
  is_recording = True
254
+ is_camera_active = True # カメラ有効化
255
 
256
+ analysis_thread = threading.Thread(target=recording_loop)
257
  analysis_thread.daemon = True
258
  analysis_thread.start()
259
 
260
+ return "録画分析中...", create_display()
261
 
262
  def stop_recording():
263
+ """録画停止(カメラも停止)"""
264
+ global is_recording, is_camera_active
265
 
266
  if not is_recording:
267
+ return "録画していません", create_display()
268
 
269
  is_recording = False
270
+ is_camera_active = False # カメラ無効化
271
  time.sleep(1)
272
 
273
  if len(recording_data) > 0:
274
  total_points = len(recording_data)
275
+ study_points = sum(1 for x in recording_data if x > MODEL_CONFIG['threshold'])
276
  study_percentage = (study_points / total_points * 100) if total_points > 0 else 0
277
  duration = recording_times[-1] if recording_times else 0
278
 
279
  avg_score = sum(recording_data) / len(recording_data)
 
 
280
 
281
  result_text = f"""
282
+ # 📊 録画分析完了
283
 
284
+ ## 基本結果
285
  - **録��時間**: {duration:.0f}秒 ({duration/60:.1f}分)
286
  - **学習率**: {study_percentage:.1f}%
 
 
 
 
287
  - **平均スコア**: {avg_score:.3f}
288
+ - **分析ポイント**: {total_points}個
 
289
 
290
+ ## 評価
291
+ {get_evaluation(study_percentage)}
292
 
293
+ ## アドバイス
294
+ {get_advice(study_percentage)}
295
  """
296
  else:
297
+ result_text = "録画データがありません"
298
 
299
+ return result_text, create_display()
300
 
301
+ def get_evaluation(study_rate):
302
+ """評価"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
  if study_rate >= 80:
304
+ return "🏆 優秀!高い集中力を維持できています。"
305
  elif study_rate >= 60:
306
+ return "🌟 良好!この調子で続けましょう。"
307
  elif study_rate >= 40:
308
+ return "📈 改善の余地あり。もう少し集中してみましょう。"
309
  else:
310
+ return "💪 要改善。環境や方法を見直してみましょう。"
311
 
312
+ def get_advice(study_rate):
313
+ """アドバイス"""
314
+ if study_rate >= 60:
315
+ return "現在のペースを維持してください。"
316
+ else:
317
+ return "集中しやすい環境を整えて、適度な休憩を取りましょう。"
318
 
319
+ def create_display():
320
+ """表示作成(文字化けなし)"""
321
  try:
322
  if len(recording_data) < 2:
323
+ fig, ax = plt.subplots(figsize=(12, 8))
 
324
  fig.patch.set_facecolor('#f8f9fa')
325
 
326
+ ax.text(0.5, 0.5, 'Press Record Button\n\nGraph will appear automatically',
327
+ ha='center', va='center', transform=ax.transAxes, fontsize=20,
328
+ bbox=dict(boxstyle="round,pad=1", facecolor="#e8f4fd", alpha=0.9))
 
 
 
 
 
 
 
 
329
 
330
  ax.set_xlim(0, 1)
331
  ax.set_ylim(0, 1)
 
334
  plt.tight_layout()
335
  return fig
336
 
337
+ # データありの表示
338
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(14, 10), height_ratios=[3, 1])
 
 
 
 
339
 
340
  times = list(recording_times)
341
  values = list(recording_data)
 
 
342
  threshold = MODEL_CONFIG['threshold']
 
 
 
 
343
 
344
+ # メイングラフ
345
+ ax1.plot(times, values, linewidth=4, color='#1f77b4', alpha=0.8)
346
+ ax1.fill_between(times, values, alpha=0.3, color='#1f77b4')
347
 
348
+ # 背景色分け
349
+ ax1.fill_between([0, max(times)], [threshold, threshold], [1.0, 1.0],
350
+ color='lightgreen', alpha=0.3, label='Study Zone')
351
+ ax1.fill_between([0, max(times)], [0.0, 0.0], [threshold, threshold],
352
+ color='lightcoral', alpha=0.3, label='Non-Study Zone')
353
 
354
  # 閾値線
355
+ ax1.axhline(y=threshold, color='red', linestyle='--', linewidth=2, alpha=0.8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
 
357
+ # 現在値強調
358
  if values:
359
+ ax1.scatter([times[-1]], [values[-1]], s=150, c='red', zorder=10)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
 
361
+ ax1.set_ylim(0, 1)
362
+ ax1.set_ylabel('Study Score', fontsize=14, fontweight='bold')
363
+ ax1.set_title('Study Status Timeline', fontsize=18, fontweight='bold')
364
+ ax1.grid(True, alpha=0.3)
365
+ ax1.legend()
366
 
367
+ # 統計表示
368
  if values:
369
+ study_ratio = sum(1 for v in values if v > threshold) / len(values) * 100
370
+ duration_min = times[-1] / 60
371
 
372
+ stats_text = f"""Statistics:
373
+ Duration: {duration_min:.1f}min
374
+ Study Rate: {study_ratio:.1f}%
375
+ Data Points: {len(values)}
376
+ Threshold: {threshold}"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
 
378
+ ax1.text(0.02, 0.98, stats_text, transform=ax1.transAxes,
379
+ fontsize=12, verticalalignment='top', fontweight='bold',
380
+ bbox=dict(boxstyle="round,pad=0.5", facecolor="#ffffff", alpha=0.9))
 
 
 
 
381
 
382
+ # ミニグラフ
383
  if len(values) > 10:
384
+ recent_values = values[-20:]
385
+ colors = ['green' if v > threshold else 'red' for v in recent_values]
386
+ ax2.bar(range(len(recent_values)), recent_values, color=colors, alpha=0.7)
387
+ ax2.set_ylim(0, 1)
388
+ ax2.set_ylabel('Score')
389
+ ax2.set_xlabel('Recent Data Points')
390
+ ax2.set_title('Recent Trend')
391
+ ax2.axhline(y=threshold, color='red', linestyle='--', alpha=0.8)
392
+ ax2.grid(True, alpha=0.3)
 
 
 
 
393
 
394
  plt.tight_layout()
395
  return fig
396
 
397
  except Exception as e:
398
+ print(f"表示作成エラー: {e}")
 
399
  fig, ax = plt.subplots(figsize=(10, 6))
400
+ ax.text(0.5, 0.5, 'Loading...', ha='center', va='center',
401
  transform=ax.transAxes, fontsize=16)
 
402
  ax.axis('off')
403
  return fig
404
 
405
+ def get_current_status():
406
+ """現在の状況取得"""
407
  if is_recording:
408
  if len(recording_data) > 0:
409
+ current_status = "勉強中" if current_prediction > MODEL_CONFIG['threshold'] else "非���強中"
410
  elapsed = recording_times[-1] if recording_times else 0
411
 
412
+ study_points = sum(1 for x in recording_data if x > MODEL_CONFIG['threshold'])
413
  study_rate = (study_points / len(recording_data) * 100) if recording_data else 0
414
 
415
  return f"""
416
+ # 🎬 録画分析中
417
 
418
+ ## 現在の状況
419
+ - **状態**: {current_status}
420
+ - **スコア**: {current_prediction:.3f}
421
+ - **経過時間**: {elapsed:.0f}秒
 
422
 
423
+ ## 統計
424
+ - **学習率**: {study_rate:.1f}%
425
+ - **データ数**: {len(recording_data)}個
426
 
427
+ 停止ボタンを押すと詳細結果が表示されます
 
 
 
 
 
428
  """
429
  else:
430
  return """
431
  # 🎬 録画開始中
432
 
433
+ 分析データを収集中です...
 
 
 
 
434
  """
435
  else:
436
  return f"""
437
+ # 📹 録画待機中
438
 
439
+ ## 使い方
440
+ 1. **録画開始**ボタンをクリック
441
+ 2. 普通に勉強してください
442
+ 3. **録画停止**ボタンで結果表示
443
 
444
+ ## 設定
445
+ - **モデル**: {MODEL_CONFIG['model_path']}
446
+ - **閾値**: {MODEL_CONFIG['threshold']}
 
447
 
448
+ 録画ボタンをクリックしてください
 
 
 
 
 
 
449
  """
450
 
 
 
 
 
451
  def create_app():
452
  with gr.Blocks(
453
+ title="学習分析システム",
454
  theme=gr.themes.Soft(),
455
+ css=""".gradio-container { max-width: 1200px; margin: auto; }"""
456
  ) as demo:
457
 
458
+ gr.HTML("""
459
+ <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 15px; margin-bottom: 20px;">
460
+ <h1 style="margin: 0; font-size: 2.5em;">📚 学習分析システム</h1>
461
+ <h2 style="margin: 10px 0; font-size: 1.2em;">録画ボタンで簡単分析</h2>
 
 
 
 
462
  </div>
463
  """)
464
 
465
  with gr.Row():
 
466
  with gr.Column(scale=2):
467
  webcam = gr.Image(
468
  sources=["webcam"],
469
  streaming=True,
470
+ height=400,
471
+ width=500,
472
+ label="ライブカメラ",
473
  show_label=True
474
  )
475
 
 
476
  with gr.Row():
477
  start_btn = gr.Button(
478
  "🎬 録画開始",
 
488
  scale=1
489
  )
490
 
 
491
  with gr.Column(scale=1):
492
  result_display = gr.Markdown(
493
+ value=get_current_status(),
494
  elem_id="result_display"
495
  )
496
 
 
497
  gr.HTML("""
498
+ <div style="margin: 20px 0 10px 0; padding: 10px; background: #f8f9fa; border-radius: 10px; text-align: center;">
499
+ <h3 style="margin: 0; color: #333;">📊 分析結果</h3>
 
500
  </div>
501
  """)
502
 
503
+ display_plot = gr.Plot(
504
+ value=create_display(),
505
+ show_label=False
 
506
  )
507
 
508
+ # カメラストリーム
509
  webcam.stream(
510
  fn=process_video_stream,
511
  inputs=[webcam],
 
516
  # ボタンイベント
517
  start_btn.click(
518
  fn=start_recording,
519
+ outputs=[result_display, display_plot]
520
  )
521
 
522
  stop_btn.click(
523
  fn=stop_recording,
524
+ outputs=[result_display, display_plot]
525
  )
526
 
527
+ gr.HTML("""
528
+ <div style="text-align: center; margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 10px;">
529
+ <p style="margin: 0; color: #666;">
530
+ <strong>ze-sudo制作</strong> | 学習分析システム | 2025-08-06 09:05:15 UTC
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
  </p>
532
  </div>
533
  """)
534
 
535
  return demo
536
 
 
 
 
 
537
  if __name__ == "__main__":
538
+ print("\n" + "="*60)
539
+ print("📚 学習分析システム")
540
+ print("="*60)
541
+ print(f"⏰ 起動時刻: 2025-08-06 09:05:15 UTC")
542
+ print(f"👤 ユーザー: ze-sudo")
543
+ print("="*60)
 
 
 
 
 
544
 
545
+ print("\n🚀 システム準備中...")
546
+ model_loaded = load_model()
547
+
548
+ print(f"\n📊 準備完了:")
549
+ print(f" モデル: {'✅ 本番' if model_loaded else '🤖 デモ'}")
550
+ print(f" カメラ制御: ✅ 録画停止で完全停止")
551
+ print(f" 表示: ✅ 日本語対応")
552
+ print(f" 文字化け: ✅ 解決済み")
 
 
 
 
 
553
 
554
+ print(f"\n📚 アプリ起動!")
 
 
 
 
555
 
 
556
  app = create_app()
557
 
558
  try: