File size: 23,233 Bytes
f079ead
 
 
 
 
4894e36
f079ead
49e20f2
533695c
 
0039884
73363d2
0039884
e5ad1d8
 
1bf101a
e5ad1d8
aaa6168
e5ad1d8
 
 
 
 
 
1bf101a
 
 
e5ad1d8
f079ead
49e20f2
4894e36
1bf101a
 
533695c
f079ead
49e20f2
 
4894e36
533695c
4894e36
f079ead
73363d2
49e20f2
55f2a16
49e20f2
73363d2
 
377a84f
 
4894e36
1bf101a
 
 
e5ad1d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f079ead
1bf101a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80ceb75
1bf101a
 
e5ad1d8
 
 
 
 
 
1bf101a
 
 
 
 
 
 
 
 
 
e5ad1d8
f079ead
1bf101a
 
377a84f
 
 
e5ad1d8
377a84f
 
 
 
 
 
 
1bf101a
e5ad1d8
377a84f
 
 
 
 
 
 
1bf101a
377a84f
 
 
 
1bf101a
 
55f2a16
377a84f
f079ead
55f2a16
1bf101a
377a84f
73363d2
1bf101a
8b3c23f
49e20f2
73363d2
 
 
 
 
80ceb75
73363d2
80ceb75
377a84f
1bf101a
377a84f
1bf101a
73363d2
 
49e20f2
73363d2
377a84f
73363d2
 
55f2a16
73363d2
 
55f2a16
f079ead
377a84f
1bf101a
 
 
 
 
377a84f
 
 
 
 
 
 
 
 
1bf101a
8b3c23f
1bf101a
8b3c23f
 
49e20f2
1bf101a
49e20f2
3add4f7
 
49e20f2
3add4f7
8b3c23f
1bf101a
 
 
 
 
8b3c23f
1bf101a
 
 
 
e5ad1d8
49e20f2
 
 
 
377a84f
 
 
 
 
55f2a16
8b3c23f
49e20f2
73363d2
 
49e20f2
4894e36
73363d2
49e20f2
4894e36
73363d2
49e20f2
4894e36
1bf101a
73363d2
 
4894e36
49e20f2
4894e36
73363d2
49e20f2
1bf101a
73363d2
 
49e20f2
73363d2
 
49e20f2
55f2a16
 
73363d2
 
1bf101a
73363d2
49e20f2
 
 
 
 
0039884
377a84f
55f2a16
73363d2
1bf101a
73363d2
1bf101a
49e20f2
 
 
377a84f
55f2a16
1bf101a
55f2a16
1bf101a
 
8b3c23f
1bf101a
 
73363d2
 
1bf101a
73363d2
49e20f2
73363d2
1bf101a
 
8b3c23f
1bf101a
8b3c23f
1bf101a
8b3c23f
1bf101a
8b3c23f
1bf101a
8b3c23f
1bf101a
 
 
 
 
 
e5ad1d8
49e20f2
 
73363d2
 
1bf101a
8b3c23f
 
49e20f2
 
 
 
 
 
 
8b3c23f
 
 
73363d2
8b3c23f
 
73363d2
 
49e20f2
1bf101a
73363d2
49e20f2
73363d2
e5ad1d8
73363d2
49e20f2
 
 
8b3c23f
1bf101a
49e20f2
 
 
 
 
 
 
55f2a16
3add4f7
49e20f2
 
8b3c23f
1bf101a
49e20f2
 
 
8b3c23f
49e20f2
1bf101a
49e20f2
 
1bf101a
 
8b3c23f
49e20f2
 
 
 
 
 
 
 
 
 
 
1bf101a
49e20f2
1bf101a
49e20f2
 
 
8b3c23f
49e20f2
 
 
 
 
 
8b3c23f
1bf101a
49e20f2
 
 
8b3c23f
49e20f2
8b3c23f
49e20f2
1bf101a
 
49e20f2
 
 
 
1bf101a
49e20f2
 
 
1bf101a
 
49e20f2
 
 
 
 
 
 
533695c
0039884
80ceb75
 
 
49e20f2
73363d2
49e20f2
8b3c23f
49e20f2
533695c
 
f079ead
1bf101a
 
73363d2
 
1bf101a
49e20f2
 
 
 
 
73363d2
1bf101a
55f2a16
 
73363d2
1bf101a
0039884
1bf101a
 
 
49e20f2
 
 
55f2a16
1bf101a
 
 
3add4f7
49e20f2
73363d2
 
49e20f2
 
d76958a
4894e36
49e20f2
 
 
 
 
73363d2
 
49e20f2
e5ad1d8
1bf101a
0039884
1bf101a
 
 
49e20f2
55f2a16
1bf101a
49e20f2
1bf101a
 
e5ad1d8
49e20f2
 
 
 
 
1bf101a
73363d2
0039884
f079ead
80ceb75
49e20f2
533695c
1bf101a
80ceb75
f079ead
49e20f2
1bf101a
 
49e20f2
 
f079ead
 
 
 
8b3c23f
377a84f
 
8b3c23f
1bf101a
 
49e20f2
377a84f
 
f079ead
80ceb75
73363d2
d76958a
73363d2
 
e5ad1d8
80ceb75
 
73363d2
d76958a
73363d2
 
e5ad1d8
4894e36
f079ead
 
73363d2
1bf101a
73363d2
80ceb75
f079ead
49e20f2
533695c
1bf101a
49e20f2
 
533695c
 
 
49e20f2
 
 
 
73363d2
 
1bf101a
377a84f
 
 
 
8b3c23f
377a84f
 
3add4f7
73363d2
 
49e20f2
f079ead
 
73363d2
 
49e20f2
f079ead
 
49e20f2
 
1bf101a
49e20f2
1bf101a
49e20f2
 
 
 
73363d2
f079ead
 
 
 
 
 
1bf101a
49e20f2
1bf101a
49e20f2
1bf101a
49e20f2
 
1bf101a
80ceb75
1bf101a
 
 
 
 
49e20f2
 
1bf101a
e5ad1d8
49e20f2
80ceb75
 
533695c
 
 
 
 
 
 
 
4894e36
533695c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
import gradio as gr
import tensorflow as tf
import numpy as np
from PIL import Image
import cv2
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib
import warnings
from collections import deque
import threading
import time
import os

# モデル設定
MODEL_CONFIG = {
    'model_path': 'model/1_1_2_deep_studying_classifier.h5',
    'alternative_paths': [
        'models/studying_classifier.h5',
        'deep_studying_classifier.h5',
        'studying_model.h5'
    ],
    'input_shape': (224, 224, 3),
    'threshold': 0.5,
    'enable_demo_mode': True,
    'demo_model_complexity': 'simple'
}

# フォント設定(日本語対応)
matplotlib.use('Agg')
plt.rcParams['font.family'] = 'DejaVu Sans'
plt.rcParams['axes.unicode_minus'] = False
warnings.filterwarnings('ignore', category=UserWarning)

print("🕒 時間軸対応学習分析システム起動中...")
print(f"⏰ 起動時刻: 2025-08-06 09:13:46 UTC")
print(f"👤 ユーザー: ze-sudo")

# グローバル変数
model = None
is_recording = False
is_camera_active = False
recording_data = deque(maxlen=1000)
recording_timestamps = deque(maxlen=1000)  # 実際の時刻を保存
recording_start_time = None
analysis_thread = None
current_frame = None
current_prediction = 0.5

def load_model():
    """モデル読み込み"""
    global model
    
    @tf.keras.utils.register_keras_serializable()
    class Cast(tf.keras.layers.Layer):
        def __init__(self, dtype='float32', **kwargs):
            super(Cast, self).__init__(**kwargs)
            self.target_dtype = dtype
        
        def call(self, inputs):
            return tf.cast(inputs, self.target_dtype)
        
        def get_config(self):
            config = super(Cast, self).get_config()
            config.update({'dtype': self.target_dtype})
            return config

    class DTypePolicy:
        def __init__(self, name='float32'):
            self.name = name
        def __str__(self):
            return self.name

    custom_objects = {
        'Cast': Cast,
        'cast': Cast,
        'DTypePolicy': DTypePolicy,
        'tf': tf,
    }
    
    try:
        print("📥 モデル読み込み中...")
        
        # メインパス試行
        if os.path.exists(MODEL_CONFIG['model_path']):
            try:
                with tf.keras.utils.custom_object_scope(custom_objects):
                    model = tf.keras.models.load_model(MODEL_CONFIG['model_path'], compile=False)
                print("✅ モデル読み込み成功")
                
                # ウォームアップ
                test_input = np.random.rand(1, *MODEL_CONFIG['input_shape']).astype(np.float32)
                for _ in range(3):
                    model.predict(test_input, verbose=0)
                return True
            except Exception as e:
                print(f"⚠️ メインパス失敗: {e}")
        
        # 代替パス試行
        for alt_path in MODEL_CONFIG['alternative_paths']:
            if os.path.exists(alt_path):
                try:
                    with tf.keras.utils.custom_object_scope(custom_objects):
                        model = tf.keras.models.load_model(alt_path, compile=False)
                    print(f"✅ 代替モデル読み込み成功: {alt_path}")
                    return True
                except:
                    continue
        
        # デモモード
        print("🤖 デモモードで起動")
        model = tf.keras.Sequential([
            tf.keras.layers.Input(shape=MODEL_CONFIG['input_shape']),
            tf.keras.layers.GlobalAveragePooling2D(),
            tf.keras.layers.Dense(16, activation='relu'),
            tf.keras.layers.Dense(1, activation='sigmoid')
        ])
        model.compile(optimizer='adam', loss='binary_crossentropy')
        
        test_input = np.random.rand(1, *MODEL_CONFIG['input_shape']).astype(np.float32)
        for _ in range(3):
            model.predict(test_input, verbose=0)
        
        return False
        
    except Exception as e:
        print(f"❌ モデル読み込み完全失敗: {e}")
        return False

def analyze_frame(frame):
    """フレーム分析"""
    global current_prediction
    
    if frame is None:
        return MODEL_CONFIG['threshold']
    
    try:
        if isinstance(frame, np.ndarray):
            img_rgb = frame if len(frame.shape) == 3 and frame.shape[2] == 3 else cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        else:
            img_rgb = np.array(frame)
        
        target_size = MODEL_CONFIG['input_shape'][:2]
        img_resized = cv2.resize(img_rgb, target_size)
        img_array = img_resized.astype(np.float32) / 255.0
        img_array = np.expand_dims(img_array, axis=0)
        
        prediction = model.predict(img_array, verbose=0)[0][0]
        current_prediction = np.clip(prediction, 0.0, 1.0)
        return current_prediction
        
    except:
        change = (np.random.random() - 0.5) * 0.1
        current_prediction = np.clip(current_prediction + change, 0.0, 1.0)
        return current_prediction

def generate_demo_data():
    """デモデータ生成"""
    if len(recording_data) == 0:
        return 0.6 + 0.3 * np.random.random()
    
    prev_val = recording_data[-1]
    change = (np.random.random() - 0.5) * 0.15
    return np.clip(prev_val + change, 0.0, 1.0)

def recording_loop():
    """録画分析ループ"""
    global is_recording, recording_data, recording_timestamps, recording_start_time
    
    print("🎬 録画分析開始")
    recording_start_time = datetime.now()
    
    while is_recording:
        try:
            current_time = datetime.now()
            
            if current_frame is not None:
                prediction = analyze_frame(current_frame)
            else:
                prediction = generate_demo_data()
            
            recording_data.append(prediction)
            recording_timestamps.append(current_time)  # 実際の時刻を保存
            
            time.sleep(0.5)
            
        except Exception as e:
            print(f"録画分析エラー: {e}")
            break
    
    print("🛑 録画分析完了")

def process_video_stream(frame):
    """カメラストリーム処理"""
    global current_frame, is_camera_active
    
    if not is_camera_active:
        return None
    
    if frame is None:
        return frame
    
    current_frame = frame
    
    if is_recording:
        display_frame = frame.copy()
        
        # 録画インジケーター
        cv2.circle(display_frame, (40, 40), 20, (255, 0, 0), -1)
        cv2.putText(display_frame, "REC", (70, 50), 
                   cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0), 3)
        
        # 状態表示(日本語)
        if current_prediction > MODEL_CONFIG['threshold']:
            status_text = "Benkyou-chuu"  # 勉強中
            status_color = (0, 255, 0)
        else:
            status_text = "Hi-benkyou"  # 非勉強
            status_color = (255, 50, 50)
        
        # 背景ボックス
        cv2.rectangle(display_frame, (10, display_frame.shape[0]-80), 
                     (400, display_frame.shape[0]-10), (0, 0, 0), -1)
        cv2.rectangle(display_frame, (10, display_frame.shape[0]-80), 
                     (400, display_frame.shape[0]-10), (255, 255, 255), 3)
        
        cv2.putText(display_frame, f"Status: {status_text}", (25, display_frame.shape[0]-50), 
                   cv2.FONT_HERSHEY_SIMPLEX, 0.8, status_color, 2)
        cv2.putText(display_frame, f"Score: {current_prediction:.2f}", (25, display_frame.shape[0]-25), 
                   cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
        
        # 現在時刻表示
        current_time_str = datetime.now().strftime("%H:%M:%S")
        cv2.putText(display_frame, f"Jikan: {current_time_str}", (250, display_frame.shape[0]-25), 
                   cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
        
        return display_frame
    
    return frame

def start_recording():
    """録画開始"""
    global is_recording, is_camera_active, analysis_thread, recording_data, recording_timestamps
    
    if is_recording:
        return "既に録画中です", create_time_axis_display()
    
    recording_data.clear()
    recording_timestamps.clear()
    
    is_recording = True
    is_camera_active = True
    
    analysis_thread = threading.Thread(target=recording_loop)
    analysis_thread.daemon = True
    analysis_thread.start()
    
    return "録画分析中...", create_time_axis_display()

def stop_recording():
    """録画停止"""
    global is_recording, is_camera_active
    
    if not is_recording:
        return "録画していません", create_time_axis_display()
    
    is_recording = False
    is_camera_active = False
    time.sleep(1)
    
    if len(recording_data) > 0:
        total_points = len(recording_data)
        study_points = sum(1 for x in recording_data if x > MODEL_CONFIG['threshold'])
        study_percentage = (study_points / total_points * 100) if total_points > 0 else 0
        
        # 時間計算
        start_time = recording_timestamps[0] if recording_timestamps else datetime.now()
        end_time = recording_timestamps[-1] if recording_timestamps else datetime.now()
        duration_seconds = (end_time - start_time).total_seconds()
        
        avg_score = sum(recording_data) / len(recording_data)
        
        result_text = f"""
# 📊 録画分析完了

## 基本結果
- **録画時間**: {duration_seconds:.0f}秒 ({duration_seconds/60:.1f}分)
- **開始時刻**: {start_time.strftime('%H:%M:%S')}
- **終了時刻**: {end_time.strftime('%H:%M:%S')}
- **学習率**: {study_percentage:.1f}%
- **平均スコア**: {avg_score:.3f}
- **分析ポイント**: {total_points}個

## 評価
{get_evaluation(study_percentage)}

## アドバイス
{get_advice(study_percentage)}
        """
    else:
        result_text = "録画データがありません"
    
    return result_text, create_time_axis_display()

def get_evaluation(study_rate):
    """評価"""
    if study_rate >= 80:
        return "🏆 優秀!高い集中力を維持できています。"
    elif study_rate >= 60:
        return "🌟 良好!この調子で続けましょう。"
    elif study_rate >= 40:
        return "📈 改善の余地あり。もう少し集中してみましょう。"
    else:
        return "💪 要改善。環境や方法を見直してみましょう。"

def get_advice(study_rate):
    """アドバイス"""
    if study_rate >= 60:
        return "現在のペースを維持してください。"
    else:
        return "集中しやすい環境を整えて、適度な休憩を取りましょう。"

def create_time_axis_display():
    """🕒 時間軸対応表示作成(完全日本語)"""
    try:
        if len(recording_data) < 2:
            fig, ax = plt.subplots(figsize=(12, 8))
            fig.patch.set_facecolor('#f8f9fa')
            
            # 日本語メッセージ(ローマ字で文字化け回避)
            ax.text(0.5, 0.6, '🎬', fontsize=120, ha='center', va='center', 
                   transform=ax.transAxes)
            ax.text(0.5, 0.4, 'Rokuga Button wo Oshi te Kudasai', fontsize=20, ha='center', va='center',
                   transform=ax.transAxes, fontweight='bold', color='#333')
            ax.text(0.5, 0.3, 'Jikanjiku Graph ga Jidou Hyouji Saremasu', fontsize=16, ha='center', va='center',
                   transform=ax.transAxes, color='#666')
            
            ax.set_xlim(0, 1)
            ax.set_ylim(0, 1)
            ax.axis('off')
            
            plt.tight_layout()
            return fig
        
        # 🕒 時間軸データありの表示
        fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(14, 10), height_ratios=[3, 1])
        
        timestamps = list(recording_timestamps)
        values = list(recording_data)
        threshold = MODEL_CONFIG['threshold']
        
        # メイングラフ(時間軸)
        ax1.plot(timestamps, values, linewidth=4, color='#1f77b4', alpha=0.8, marker='o', markersize=3)
        ax1.fill_between(timestamps, values, alpha=0.3, color='#1f77b4')
        
        # 背景色分け
        if timestamps:
            time_min = min(timestamps)
            time_max = max(timestamps)
            ax1.fill_between([time_min, time_max], [threshold, threshold], [1.0, 1.0], 
                            color='lightgreen', alpha=0.3, label='Benkyou Zone')
            ax1.fill_between([time_min, time_max], [0.0, 0.0], [threshold, threshold], 
                            color='lightcoral', alpha=0.3, label='Hi-benkyou Zone')
        
        # 閾値線
        ax1.axhline(y=threshold, color='red', linestyle='--', linewidth=2, alpha=0.8, 
                   label=f'Kyoukai-chi ({threshold})')
        
        # 現在値強調
        if values and timestamps:
            ax1.scatter([timestamps[-1]], [values[-1]], s=150, c='red', zorder=10, 
                       edgecolors='white', linewidth=2)
        
        # 軸設定
        ax1.set_ylim(0, 1)
        ax1.set_ylabel('Gakushuu Score', fontsize=14, fontweight='bold')
        ax1.set_title('Gakushuu Joukyou no Jikanjiku Suii', fontsize=18, fontweight='bold', pad=20)
        ax1.grid(True, alpha=0.3)
        ax1.legend()
        
        # 🕒 時間軸フォーマット
        if timestamps:
            ax1.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
            ax1.xaxis.set_major_locator(mdates.SecondLocator(interval=30))
            plt.setp(ax1.xaxis.get_majorticklabels(), rotation=45)
        
        # Y軸ラベル(日本語対応)
        ax1.set_yticks([0, 0.25, threshold, 0.75, 1.0])
        ax1.set_yticklabels(['0.0\n(Hi-benkyou)', '0.25', f'{threshold}\n(Kyoukai)', '0.75', '1.0\n(Shuuchuu)'], 
                           fontsize=11)
        
        # 統計表示
        if values and timestamps:
            study_ratio = sum(1 for v in values if v > threshold) / len(values) * 100
            duration_min = (timestamps[-1] - timestamps[0]).total_seconds() / 60
            start_time_str = timestamps[0].strftime('%H:%M:%S')
            end_time_str = timestamps[-1].strftime('%H:%M:%S')
            
            stats_text = f"""Toukei Jouhou:
Kaishi: {start_time_str}
Shuuryou: {end_time_str}
Jikan: {duration_min:.1f}fun
Gakushuu Ritsu: {study_ratio:.1f}%
Data Suu: {len(values)}ko"""
            
            ax1.text(0.02, 0.98, stats_text, transform=ax1.transAxes, 
                    fontsize=11, verticalalignment='top', fontweight='bold',
                    bbox=dict(boxstyle="round,pad=0.5", facecolor="#ffffff", alpha=0.9,
                             edgecolor="#1976d2", linewidth=2))
        
        # ミニグラフ(最新データ)
        if len(values) > 10:
            recent_timestamps = timestamps[-20:]
            recent_values = values[-20:]
            colors = ['green' if v > threshold else 'red' for v in recent_values]
            
            # 時刻ラベル用のインデックス
            x_indices = range(len(recent_values))
            ax2.bar(x_indices, recent_values, color=colors, alpha=0.7)
            ax2.set_ylim(0, 1)
            ax2.set_ylabel('Score', fontsize=12)
            ax2.set_xlabel('Saikin no Data', fontsize=12)
            ax2.set_title('Saikin no Suii', fontsize=14, fontweight='bold')
            ax2.axhline(y=threshold, color='red', linestyle='--', alpha=0.8)
            ax2.grid(True, alpha=0.3)
            
            # X軸に時刻表示(5つおき)
            if len(recent_timestamps) > 5:
                tick_indices = list(range(0, len(recent_timestamps), max(1, len(recent_timestamps)//5)))
                tick_labels = [recent_timestamps[i].strftime('%H:%M:%S') for i in tick_indices]
                ax2.set_xticks(tick_indices)
                ax2.set_xticklabels(tick_labels, rotation=45, fontsize=10)
        
        plt.tight_layout()
        return fig
        
    except Exception as e:
        print(f"時間軸表示作成エラー: {e}")
        fig, ax = plt.subplots(figsize=(10, 6))
        ax.text(0.5, 0.5, 'Jikanjiku Hyouji Junbi-chuu...', ha='center', va='center',
                transform=ax.transAxes, fontsize=16)
        ax.set_title('Gakushuu Bunseki - Jikanjiku Hyouji')
        ax.axis('off')
        return fig

def get_current_status():
    """現在の状況取得"""
    if is_recording:
        if len(recording_data) > 0:
            current_status = "勉強中" if current_prediction > MODEL_CONFIG['threshold'] else "非勉強中"
            
            # 時間情報
            current_time = datetime.now()
            start_time = recording_timestamps[0] if recording_timestamps else current_time
            elapsed_seconds = (current_time - start_time).total_seconds()
            
            study_points = sum(1 for x in recording_data if x > MODEL_CONFIG['threshold'])
            study_rate = (study_points / len(recording_data) * 100) if recording_data else 0
            
            return f"""
# 🎬 録画分析中

## 現在の状況
- **状態**: {current_status}
- **スコア**: {current_prediction:.3f}
- **現在時刻**: {current_time.strftime('%H:%M:%S')}
- **開始時刻**: {start_time.strftime('%H:%M:%S')}
- **経過時間**: {elapsed_seconds:.0f}秒

## 統計
- **学習率**: {study_rate:.1f}%
- **データ数**: {len(recording_data)}個

停止ボタンを押すと時間軸グラフで詳細結果が表示されます
            """
        else:
            current_time = datetime.now()
            return f"""
# 🎬 録画開始中

## 状況
- **現在時刻**: {current_time.strftime('%H:%M:%S')}
- **状態**: 分析データ収集中...

時間軸グラフで分析結果を表示します
            """
    else:
        current_time = datetime.now()
        return f"""
# 📹 録画待機中

## 使い方
1. **録画開始**ボタンをクリック
2. 普通に勉強してください
3. **録画停止**ボタンで時間軸グラフ表示

## 設定
- **現在時刻**: {current_time.strftime('%H:%M:%S')}
- **モデル**: {MODEL_CONFIG['model_path']}
- **閾値**: {MODEL_CONFIG['threshold']}

## 特徴
- **時間軸表示**: 横軸が実際の時刻
- **日本語対応**: 完全日本語UI
- **リアルタイム**: 0.5秒間隔で分析

録画ボタンをクリックしてください
        """

def create_app():
    with gr.Blocks(
        title="🕒 時間軸学習分析システム", 
        theme=gr.themes.Soft(),
        css=""".gradio-container { max-width: 1200px; margin: auto; }"""
    ) as demo:
        
        # ヘッダー
        gr.HTML("""
        <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 15px; margin-bottom: 20px;">
            <h1 style="margin: 0; font-size: 2.5em;">🕒 学習分析システム</h1>
            <h2 style="margin: 10px 0; font-size: 1.2em;">時間軸グラフで詳細分析 📊 完全日本語対応</h2>
        </div>
        """)
        
        with gr.Row():
            with gr.Column(scale=2):
                webcam = gr.Image(
                    sources=["webcam"],
                    streaming=True,
                    height=400,
                    width=500,
                    label="📹 ライブカメラ(時刻表示付き)",
                    show_label=True
                )
                
                with gr.Row():
                    start_btn = gr.Button(
                        "🎬 録画開始", 
                        variant="primary",
                        size="lg",
                        scale=1
                    )
                    
                    stop_btn = gr.Button(
                        "🛑 録画停止", 
                        variant="secondary",
                        size="lg",
                        scale=1
                    )
            
            with gr.Column(scale=1):
                result_display = gr.Markdown(
                    value=get_current_status(),
                    elem_id="result_display"
                )
        
        # 時間軸グラフ表示エリア
        gr.HTML("""
        <div style="margin: 20px 0 10px 0; padding: 10px; background: #f8f9fa; border-radius: 10px; text-align: center;">
            <h3 style="margin: 0; color: #333;">🕒 時間軸分析グラフ</h3>
            <p style="margin: 5px 0 0 0; color: #666; font-size: 0.9em;">横軸:実際の時刻 | 縦軸:学習スコア</p>
        </div>
        """)
        
        time_axis_plot = gr.Plot(
            value=create_time_axis_display(),
            show_label=False,
            elem_id="time_axis_plot"
        )
        
        # カメラストリーム
        webcam.stream(
            fn=process_video_stream,
            inputs=[webcam],
            outputs=[webcam],
            stream_every=0.1
        )
        
        # ボタンイベント
        start_btn.click(
            fn=start_recording,
            outputs=[result_display, time_axis_plot]
        )
        
        stop_btn.click(
            fn=stop_recording,
            outputs=[result_display, time_axis_plot]
        )
        
        # フッター
        gr.HTML(f"""
        <div style="text-align: center; margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 10px;">
            <h4 style="margin: 0 0 10px 0; color: #333;">🕒 時間軸対応版 - 完全日本語表示</h4>
            <p style="margin: 0; color: #666;">
                <strong>ze-sudo制作</strong> | 時間軸学習分析システム | 2025-08-06 09:13:46 UTC
            </p>
            <p style="margin: 5px 0 0 0; color: #888; font-size: 0.9em;">
                📊 横軸:実際の時刻表示 | 🇯🇵 完全日本語対応 | ⏱️ リアルタイム分析
            </p>
        </div>
        """)
    
    return demo

if __name__ == "__main__":
    print("\n" + "="*60)
    print("🕒 時間軸対応学習分析システム")
    print("="*60)
    print(f"⏰ 起動時刻: 2025-08-06 09:13:46 UTC")
    print(f"👤 ユーザー: ze-sudo")
    print(f"🕒 特徴: 横軸が実際の時刻")
    print(f"🇯🇵 言語: 完全日本語対応")
    print("="*60)
    
    print("\n🚀 システム準備中...")
    model_loaded = load_model()
    
    print(f"\n📊 準備完了:")
    print(f"   モデル: {'✅ 本番' if model_loaded else '🤖 デモ'}")
    print(f"   時間軸: ✅ 横軸が実際の時刻")
    print(f"   日本語: ✅ 完全対応")
    print(f"   カメラ制御: ✅ 録画停止で完全停止")
    
    print(f"\n🕒 時間軸対応アプリ起動!")
    
    app = create_app()
    
    try:
        app.launch(
            server_name="0.0.0.0",
            server_port=7860,
            show_error=True
        )
    except Exception as launch_error:
        print(f"❌ 起動エラー: {launch_error}")
        app.launch()