CoolFace
Apppublic

xvadur/Aethero_github

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
aethero_dashboard.py464 linesDownload Raw Back to root
1#!/usr/bin/env python32"""3Aethero Dashboard - Vizualizácia a analýza Aetheron jednotiek4Real-time dashboard pre slovak healthcare developer productivity5"""6 7import json8import pandas as pd9import matplotlib.pyplot as plt10import matplotlib.dates as mdates11import seaborn as sns12from datetime import datetime, timedelta13import numpy as np14from typing import Dict, List, Any15import plotly.graph_objects as go16import plotly.express as px17from plotly.subplots import make_subplots18import os19import glob20 21class AetheroDashboard:22    """23    Interaktívny dashboard pre vizualizáciu Aetheron audit výsledkov24    """25    26    def __init__(self):27        self.audit_data = None28        self.df_units = None29        self.df_sessions = None30        31        # Štýlové nastavenia32        plt.style.use('seaborn-v0_8-darkgrid')33        sns.set_palette("husl")34        35    def load_latest_audit_data(self, audit_dir: str = ".") -> bool:36        """Načítanie najnovších audit dát"""37        audit_files = glob.glob(os.path.join(audit_dir, "aethero_audit_*.json"))38        39        if not audit_files:40            print("❌ Žiadne audit súbory nenájdené")41            return False42        43        # Najnovší súbor44        latest_file = max(audit_files, key=os.path.getctime)45        46        try:47            with open(latest_file, 'r', encoding='utf-8') as f:48                self.audit_data = json.load(f)49            50            # Konverzia na pandas DataFrames51            self._prepare_dataframes()52            print(f"✅ Audit dáta načítané z: {latest_file}")53            return True54            55        except Exception as e:56            print(f"❌ Chyba pri načítaní audit dát: {e}")57            return False58    59    def _prepare_dataframes(self):60        """Príprava pandas DataFrames pre analýzu"""61        if not self.audit_data:62            return63        64        # DataFrame pre Aetheron jednotky65        units_data = []66        for unit in self.audit_data.get('aetheron_units', []):67            unit_dict = unit.copy()68            unit_dict['timestamp'] = pd.to_datetime(unit_dict['timestamp'])69            unit_dict['hour'] = unit_dict['timestamp'].hour70            unit_dict['day_of_week'] = unit_dict['timestamp'].day_name()71            unit_dict['date'] = unit_dict['timestamp'].date()72            units_data.append(unit_dict)73        74        self.df_units = pd.DataFrame(units_data)75        76        # DataFrame pre relácie77        sessions_data = []78        for session in self.audit_data.get('development_sessions', []):79            session_dict = session.copy()80            session_dict['start_time'] = pd.to_datetime(session_dict['start_time'])81            session_dict['end_time'] = pd.to_datetime(session_dict['end_time'])82            session_dict['date'] = session_dict['start_time'].date()83            sessions_data.append(session_dict)84        85        self.df_sessions = pd.DataFrame(sessions_data)86    87    def create_productivity_timeline(self) -> go.Figure:88        """Timeline produktivity s Aetheron jednotkami"""89        if self.df_units is None or len(self.df_units) == 0:90            return go.Figure().add_annotation(text="Žiadne dáta na zobrazenie")91        92        fig = go.Figure()93        94        # Hlavná línia Aetheron hodnôt95        fig.add_trace(go.Scatter(96            x=self.df_units['timestamp'],97            y=self.df_units['aetheron_value'],98            mode='lines+markers',99            name='Aetheron Value',100            line=dict(color='#1f77b4', width=3),101            marker=dict(size=8, color='#1f77b4')102        ))103        104        # Kognitívna záťaž ako secondary y-axis105        fig.add_trace(go.Scatter(106            x=self.df_units['timestamp'],107            y=self.df_units['cognitive_load_estimate'],108            mode='lines',109            name='Cognitive Load',110            yaxis='y2',111            line=dict(color='#ff7f0e', width=2, dash='dash'),112            opacity=0.7113        ))114        115        fig.update_layout(116            title='🚀 Slovak Healthcare Developer - Productivity Timeline',117            xaxis_title='Time',118            yaxis_title='Aetheron Value',119            yaxis2=dict(120                title='Cognitive Load',121                overlaying='y',122                side='right',123                range=[0, 10]124            ),125            hovermode='x unified',126            template='plotly_dark'127        )128        129        return fig130    131    def create_daily_productivity_heatmap(self) -> go.Figure:132        """Heatmapa dennej produktivity"""133        if self.df_units is None or len(self.df_units) == 0:134            return go.Figure()135        136        # Pivot table pre heatmapu137        daily_productivity = self.df_units.groupby(['date', 'hour'])['aetheron_value'].sum().reset_index()138        pivot_data = daily_productivity.pivot(index='date', columns='hour', values='aetheron_value').fillna(0)139        140        fig = go.Figure(data=go.Heatmap(141            z=pivot_data.values,142            x=[f"{h:02d}:00" for h in pivot_data.columns],143            y=[str(d) for d in pivot_data.index],144            colorscale='Viridis',145            colorbar=dict(title="Aetheron Value")146        ))147        148        fig.update_layout(149            title='📅 Daily Development Rhythm Heatmap',150            xaxis_title='Hour of Day',151            yaxis_title='Date',152            template='plotly_dark'153        )154        155        return fig156    157    def create_cognitive_analysis_radar(self) -> go.Figure:158        """Radar chart pre kognitívnu analýzu"""159        if self.df_units is None or len(self.df_units) == 0:160            return go.Figure()161        162        # Agregované metriky163        metrics = {164            'Avg Aetheron Value': self.df_units['aetheron_value'].mean(),165            'Avg Rhythm Score': self.df_units['development_rhythm_score'].mean(),166            'Avg Efficiency': self.df_units['efficiency_multiplier'].mean(),167            'Cognitive Coherence': 10 - self.df_units['cognitive_load_estimate'].mean(),168            'Git Activity': self.df_units['git_commit_count'].mean() * 2,169            'Shell Activity': self.df_units['shell_commands_count'].mean() / 2170        }171        172        # Normalizácia na 0-10 škálu173        max_values = {'Avg Aetheron Value': 5, 'Avg Rhythm Score': 1, 'Avg Efficiency': 1,174                     'Cognitive Coherence': 10, 'Git Activity': 10, 'Shell Activity': 10}175        176        normalized_metrics = {}177        for key, value in metrics.items():178            normalized_metrics[key] = min(10, (value / max_values[key]) * 10)179        180        categories = list(normalized_metrics.keys())181        values = list(normalized_metrics.values())182        183        fig = go.Figure()184        185        fig.add_trace(go.Scatterpolar(186            r=values + [values[0]],  # Zatvorenie kruhu187            theta=categories + [categories[0]],188            fill='toself',189            name='Slovak Developer Profile',190            line_color='#1f77b4'191        ))192        193        fig.update_layout(194            polar=dict(195                radialaxis=dict(196                    visible=True,197                    range=[0, 10]198                )),199            title='🧠 Cognitive Performance Radar - Slovak Healthcare Dev',200            template='plotly_dark'201        )202        203        return fig204    205    def create_session_analysis_chart(self) -> go.Figure:206        """Analýza vývojových relácií"""207        if self.df_sessions is None or len(self.df_sessions) == 0:208            return go.Figure()209        210        fig = make_subplots(211            rows=2, cols=2,212            subplot_titles=('Session Duration vs Aetherony', 'Productivity Rating Distribution',213                           'Cognitive Coherence vs Output', 'Sessions by Day of Week'),214            specs=[[{"secondary_y": False}, {"type": "pie"}],215                   [{"secondary_y": False}, {"type": "bar"}]]216        )217        218        # 1. Duration vs Aetherony scatter219        fig.add_trace(go.Scatter(220            x=self.df_sessions['duration_hours'],221            y=self.df_sessions['total_aetherony'],222            mode='markers',223            marker=dict(224                size=self.df_sessions['cognitive_coherence'] * 20,225                color=self.df_sessions['cognitive_coherence'],226                colorscale='Viridis',227                showscale=True228            ),229            name='Sessions'230        ), row=1, col=1)231        232        # 2. Productivity rating pie233        rating_counts = self.df_sessions['productivity_rating'].value_counts()234        fig.add_trace(go.Pie(235            labels=rating_counts.index,236            values=rating_counts.values,237            name="Productivity"238        ), row=1, col=2)239        240        # 3. Cognitive coherence vs commits241        fig.add_trace(go.Scatter(242            x=self.df_sessions['cognitive_coherence'],243            y=self.df_sessions['commits_count'],244            mode='markers',245            name='Coherence vs Commits'246        ), row=2, col=1)247        248        # 4. Sessions by day of week249        if 'start_time' in self.df_sessions.columns:250            daily_sessions = self.df_sessions.groupby(251                self.df_sessions['start_time'].dt.day_name()252            ).size().reindex(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 253                             'Friday', 'Saturday', 'Sunday'], fill_value=0)254            255            fig.add_trace(go.Bar(256                x=daily_sessions.index,257                y=daily_sessions.values,258                name='Sessions per Day'259            ), row=2, col=2)260        261        fig.update_layout(262            title='📊 Development Sessions Analysis',263            template='plotly_dark',264            height=800265        )266        267        return fig268    269    def generate_executive_summary(self) -> Dict[str, Any]:270        """Generovanie executive summary pre management"""271        if not self.audit_data:272            return {}273        274        metadata = self.audit_data.get('audit_metadata', {})275        summary_stats = self.audit_data.get('summary_statistics', {})276        277        # Výpočet ROI a human capital efficiency278        total_aetherony = metadata.get('total_aetherony_generated', 0)279        total_sessions = metadata.get('total_sessions', 0)280        281        # Odhad nákladov vs výstup (na základe SK healthcare salary)282        avg_slovak_dev_hourly_rate = 25  # EUR/hour283        estimated_dev_hours = total_sessions * 2  # Priemer 2h na session284        estimated_cost = estimated_dev_hours * avg_slovak_dev_hourly_rate285        286        aetheron_value_eur = total_aetherony * 50  # 1 Aetheron = 50 EUR value287        roi_percentage = ((aetheron_value_eur - estimated_cost) / estimated_cost * 100) if estimated_cost > 0 else 0288        289        return {290            'performance_summary': {291                'total_aetherony_generated': total_aetherony,292                'development_efficiency_rating': summary_stats.get('development_efficiency_rating', 'N/A'),293                'average_productivity_per_hour': summary_stats.get('average_aetherony_per_hour', 0),294                'most_productive_day': summary_stats.get('most_productive_day', 'N/A')295            },296            'business_metrics': {297                'estimated_development_hours': estimated_dev_hours,298                'estimated_development_cost_eur': estimated_cost,299                'generated_value_eur': aetheron_value_eur,300                'roi_percentage': round(roi_percentage, 2),301                'human_capital_efficiency': 'Vysoká' if roi_percentage > 100 else 'Stredná'302            },303            'cognitive_insights': {304                'average_cognitive_load': summary_stats.get('average_cognitive_load', 0),305                'cognitive_coherence_trend': 'Stable' if summary_stats.get('average_cognitive_load', 0) < 6 else 'High Load',306                'top_development_patterns': summary_stats.get('top_development_patterns', {})307            },308            'recommendations': self._generate_recommendations(summary_stats, total_aetherony)309        }310    311    def _generate_recommendations(self, stats: Dict, total_aetherony: float) -> List[str]:312        """AI-powered recommendations pre zlepšenie produktivity"""313        recommendations = []314        315        avg_cognitive_load = stats.get('average_cognitive_load', 5)316        avg_rhythm = stats.get('average_rhythm_score', 0.5)317        318        if avg_cognitive_load > 7:319            recommendations.append("🧠 Vysoká kognitívna záťaž - zvážte kratšie working sessions s prestávkami")320        321        if avg_rhythm < 0.6:322            recommendations.append("⚡ Nízky development rhythm - implementujte Pomodoro technique")323        324        if total_aetherony < 10:325            recommendations.append("📈 Nízka produktivita - analyzujte time management a eliminujte distrakcie")326        327        if 'debugging' in str(stats.get('top_development_patterns', {})):328            recommendations.append("🐛 Vysoký debugging ratio - investujte do test coverage a code review")329        330        recommendations.append("🏥 Slovak healthcare context: Optimálne pre part-time development vedľa medicínskej praxe")331        332        return recommendations333    334    def export_dashboard_report(self, output_dir: str = ".") -> str:335        """Export dashboard do HTML reportu"""336        if not self.audit_data:337            return ""338        339        # Generovanie všetkých chartov340        timeline_chart = self.create_productivity_timeline()341        heatmap_chart = self.create_daily_productivity_heatmap()342        radar_chart = self.create_cognitive_analysis_radar()343        session_chart = self.create_session_analysis_chart()344        345        executive_summary = self.generate_executive_summary()346        347        # HTML template348        html_content = f"""349        <!DOCTYPE html>350        <html>351        <head>352            <title>Aethero Development Audit Dashboard</title>353            <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>354            <style>355                body {{ font-family: Arial, sans-serif; margin: 20px; background: #1e1e1e; color: white; }}356                .container {{ max-width: 1200px; margin: 0 auto; }}357                .header {{ text-align: center; margin-bottom: 30px; }}358                .chart-container {{ margin: 20px 0; }}359                .summary-box {{ background: #2d2d2d; padding: 20px; border-radius: 10px; margin: 20px 0; }}360                .metric {{ display: inline-block; margin: 10px; padding: 15px; background: #3d3d3d; border-radius: 5px; }}361                .recommendations {{ background: #0d4f8c; padding: 15px; border-radius: 5px; margin: 10px 0; }}362            </style>363        </head>364        <body>365            <div class="container">366                <div class="header">367                    <h1>🚀 Aethero Development Audit Dashboard</h1>368                    <h2>Slovak Healthcare Developer Performance Analysis</h2>369                    <p>Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>370                </div>371                372                <div class="summary-box">373                    <h3>📊 Executive Summary</h3>374                    <div class="metric">375                        <strong>Total Aetherony:</strong> {executive_summary.get('performance_summary', {}).get('total_aetherony_generated', 0):.2f}376                    </div>377                    <div class="metric">378                        <strong>Efficiency Rating:</strong> {executive_summary.get('performance_summary', {}).get('development_efficiency_rating', 'N/A')}379                    </div>380                    <div class="metric">381                        <strong>ROI:</strong> {executive_summary.get('business_metrics', {}).get('roi_percentage', 0):.1f}%382                    </div>383                    <div class="metric">384                        <strong>Most Productive Day:</strong> {executive_summary.get('performance_summary', {}).get('most_productive_day', 'N/A')}385                    </div>386                </div>387                388                <div class="chart-container">389                    <div id="timeline-chart"></div>390                </div>391                392                <div class="chart-container">393                    <div id="heatmap-chart"></div>394                </div>395                396                <div class="chart-container">397                    <div id="radar-chart"></div>398                </div>399                400                <div class="chart-container">401                    <div id="session-chart"></div>402                </div>403                404                <div class="summary-box">405                    <h3>💡 AI-Powered Recommendations</h3>406                    {''.join([f'<div class="recommendations">{rec}</div>' for rec in executive_summary.get('recommendations', [])])}407                </div>408            </div>409            410            <script>411                Plotly.newPlot('timeline-chart', {timeline_chart.to_json()});412                Plotly.newPlot('heatmap-chart', {heatmap_chart.to_json()});413                Plotly.newPlot('radar-chart', {radar_chart.to_json()});414                Plotly.newPlot('session-chart', {session_chart.to_json()});415            </script>416        </body>417        </html>418        """419        420        # Zápis súboru421        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")422        filename = f"aethero_dashboard_{timestamp}.html"423        filepath = os.path.join(output_dir, filename)424        425        with open(filepath, 'w', encoding='utf-8') as f:426            f.write(html_content)427        428        return filepath429 430def main():431    """Hlavná funkcia dashboard aplikácie"""432    dashboard = AetheroDashboard()433    434    if dashboard.load_latest_audit_data():435        print("🎯 Generujem Aethero Dashboard...")436        437        # Export HTML dashboard438        report_path = dashboard.export_dashboard_report()439        print(f"📊 Dashboard vygenerovaný: {report_path}")440        441        # Executive summary442        summary = dashboard.generate_executive_summary()443        print("\n" + "="*50)444        print("📈 EXECUTIVE SUMMARY")445        print("="*50)446        447        perf = summary.get('performance_summary', {})448        business = summary.get('business_metrics', {})449        450        print(f"🚀 Total Aetherony Generated: {perf.get('total_aetherony_generated', 0):.2f}")451        print(f"⚡ Efficiency Rating: {perf.get('development_efficiency_rating', 'N/A')}")452        print(f"💰 ROI: {business.get('roi_percentage', 0):.1f}%")453        print(f"🧠 Human Capital Efficiency: {business.get('human_capital_efficiency', 'N/A')}")454        455        print("\n💡 Recommendations:")456        for rec in summary.get('recommendations', []):457            print(f"   {rec}")458        459    else:460        print("❌ Spustite najprv aethero_audit.py pre generovanie dát")461 462if __name__ == "__main__":463    main()464