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("""
横軸:実際の時刻 | 縦軸:学習スコア
ze-sudo制作 | 時間軸学習分析システム | 2025-08-06 09:13:46 UTC
📊 横軸:実際の時刻表示 | 🇯🇵 完全日本語対応 | ⏱️ リアルタイム分析